RSA加解密

    @Test
    public void generateKeys() throws NoSuchAlgorithmException {
       KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
       keyPairGenerator.initialize(2048);

        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        //生成公钥
        PublicKey publicKey = keyPair.getPublic();
        //生成私钥
        PrivateKey privateKey = keyPair.getPrivate();
        log.info("public Key:[{}]\n",Base64.encode(publicKey.getEncoded()));
        log.info("private Key:[{}]",Base64.encode(privateKey.getEncoded()));

    }

RSA加解密

@Slf4j
public class RSAUtil {
    private static Object RSAPublicKeypubKey;

    //公钥
    private static String publicKey =
            "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv1EgDEAIYVFbvV1JwK0i\n" +
                    "6GSJpUXqN1OF3XIQlHMEy8pqsFUCQ8g1FsIoVUbWSuTWKD//L9qMacrjLs9Ot5ER\n" +
                    "Cs+xkMfBbLrPXRMGkhXlDaRuYTVhAYWb/5r4ukPa+spsoLByqlV8bMA5yvy+vFSs\n" +
                    "xZumNmCr9Gy1kDMBePQPqpejOJW8OEqKhPOOBQN7jmsuWbhvBoH8n1tAWvpCDsI8\n" +
                    "Ipevgwj4hqNcx0M6d8IOY8FJ8d86BpmGJEvEP+TESudGRDxt3Gyto3i/JPiWPtBL\n" +
                    "ESJePemNr059boh7vkW4fxnlG7VziopPEnQOFe9bDHGOZrj75cgIfXQzpoyuXcBf\n" +
                    "vwIDAQAB\n";

    //私钥
    private static String privateKey =
            "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC/USAMQAhhUVu9\n" +
                    "XUnArSLoZImlReo3U4XdchCUcwTLymqwVQJDyDUWwihVRtZK5NYoP/8v2oxpyuMu\n" +
                    "z063kREKz7GQx8Fsus9dEwaSFeUNpG5hNWEBhZv/mvi6Q9r6ymygsHKqVXxswDnK\n" +
                    "/L68VKzFm6Y2YKv0bLWQMwF49A+ql6M4lbw4SoqE844FA3uOay5ZuG8GgfyfW0Ba\n" +
                    "+kIOwjwil6+DCPiGo1zHQzp3wg5jwUnx3zoGmYYkS8Q/5MRK50ZEPG3cbK2jeL8k\n" +
                    "+JY+0EsRIl496Y2vTn1uiHu+Rbh/GeUbtXOKik8SdA4V71sMcY5muPvlyAh9dDOm\n" +
                    "jK5dwF+/AgMBAAECggEADvbDcPHZNfNtH4Sabi2cm1yxv3GWfjlUMRvo3BOa/m2Y\n" +
                    "pq4ffTm9nUgWa4Uc4cLAVWmcBhwr+2JZHqIsYANCt/vCwbY+FMkPyxHf47E+tzBz\n" +
                    "SbspGTtgFkAC0F7aU99dW7wxW81P7Bmk65GVQZnF4bbo6zvodzfBg8PZi6JbT1Zm\n" +
                    "VMBnHxHxkMoD/Ik3vZv9HXypdUk0OPhMAmG7ElAWcqiNcOsIsJK09/WDHjVELE04\n" +
                    "ddz6D+5+UUxSSRB+PVR2HGdbm6q5Q+qzbobEICKpyikwg0muq9cJduP6uJVIlMBJ\n" +
                    "Yi36FqFMyE5Ud3cENLa5xDBk8THJNmB4vll8XMgMoQKBgQDkZphBubcxopE2OFmA\n" +
                    "Ge5o8YFUXCPOBtbWx2UriJIJtLHDrCKIrXbImH5GZ7/isC6aguCP2ppVpITlxT48\n" +
                    "m8BbfAO5vvtx5yFS+hsIq3q7wqQVMWqvR9z+9sgcy0XbxT7T2ZemTTecUsEJXCLa\n" +
                    "8FqIKAHGK42CK+VmdenO8Xoo5wKBgQDWb154n3vXzIfcN3qGJrEsaZ/vHn+q12rk\n" +
                    "ssJDK2/I0NUJO0I/uXEFhD7BvEmRZ2SAVacSNFv34Dtadup8NNw7i1HGCvKJA1wm\n" +
                    "SbgqDA2l1sjdQFM40m67ZmZLvlxlQ6afRL7MtbZpJ58z+wxXkhrlVnrS9rioEiXe\n" +
                    "VC7fgm1/aQKBgEorTtI5HtZNdl5nGhlRUmxd0KO2cCIdcnK4uY/Tf6kLNpbWNTix\n" +
                    "K9ukOY1fb56Lm/as/YN5d5jMHiQHU1iXM3YB5avR6xFn/xhVA6ZjGS4T3PjM3Voi\n" +
                    "Og/Jz94Z3Iurl+VvyaFFfgOTlAAYHXF/j8abR0g1KHTXEF2feNes7wCNAoGBAITM\n" +
                    "pfoX8u97eGw2Y4fvMGxr4aOKBNC95jJKTqqgnPMF+dlkvKuQYeFjvCXpQLpvCLu9\n" +
                    "z+EjUg2Z7cghuyg+6GFr77Gxl/CohwojP42yt0UMVotHSgL3t6IRUar48mm4Utly\n" +
                    "DqPiqVxIMH1VrZgSINwFCb3bFBLqYk9lXT4InV15AoGAU8qD6hJLwidWrooYnWPM\n" +
                    "xWMRrCO1XTENCbNst5e5YBIzNIN5V+2GhPAOACf1GQsj1i0laI4oX0GNVbUCHBpi\n" +
                    "6lYsgZgd1+A5HmV97t1DDql6xgWGY+K2sbVfMOrF7MLwPFuthPZJVGlTkHGpTnhb\n" +
                    "uxZkOGxgUK0Q9fKr1y2E/FE=\n";




    /**
     * RSA公钥加密
     *
     * @return 密文
     * @paramstr加密字符串
     * @parampublicKey公钥
     */
    public static String encrypt(String str) {
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKeypubKey = null;
        String outStr = null;
        try {
            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            e.printStackTrace();
            //            log.info(e.getMessage(),e);
        }
        //RSA加密
        return outStr;
    }


    /**
     * RSA私钥解密
     *
     * @return 铭文
     * @paramstr加密字符串
     * @paramprivateKey私钥
     */
    public static String decrypt(String str){
        //64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8));
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = null;
        //RSA解密
        Cipher cipher = null;
        String outStr = null;
        try {
            priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            outStr = new String(cipher.doFinal(inputByte));
        } catch (Exception e) {
            e.printStackTrace();
            //            log.info(e.getMessage(),e);
        }
        return outStr;
    }


}
posted @ 2022-05-06 16:51  肖恩雷  阅读(150)  评论(0编辑  收藏  举报