All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.maxiaofa.captcha.spring.boot.framework.utils.RsaUtils Maven / Gradle / Ivy

package com.maxiaofa.captcha.spring.boot.framework.utils;

import com.maxiaofa.captcha.spring.boot.framework.constants.Constants;
import com.maxiaofa.captcha.spring.boot.properties.RotateCaptchaProperties;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

/**
 * rsa工具类
 * @author MaXiaoFa
 */
public class RsaUtils {

    /**
     * RSA私钥解密
     *
     * @param str 加密字符串
     * @return 密文
     */
    public static String decrypt(String str){
        //64位解码加密后的字符串
        byte[] inputByte = Base64.getDecoder().decode(str.getBytes(StandardCharsets.UTF_8));
        //base64编码的私钥
        byte[] decoded = Base64.getDecoder().decode(SpringUtils.getBean(RotateCaptchaProperties.Rsa.class).getRsaPrivate());
        Cipher cipher = null;
        String ciphertext = null;
        try {
            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(Constants.RSA).generatePrivate(new PKCS8EncodedKeySpec(decoded));
            //RSA解密
            cipher = Cipher.getInstance(Constants.RSA);
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            ciphertext = new String(cipher.doFinal(inputByte));
        }catch (Exception e){
            e.printStackTrace();
        }
        return ciphertext;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy