springboot整合AES+RSA加密

RSA和AES简介

RSA
加密机制:属于非对称加密,公钥用于对数据进行加密,私钥对数据进行解密,两者不可逆。公钥和私钥是同时生成的,且一一对应。比如:A拥有公钥,B拥有公钥和私钥。A将数据通过公钥进行加密后,发送密文给B,B可以通过私钥进行解密。
AES
加密机制:属于对称加密,就是说,A用密钥对数据进行AES加密后,B用同样的密钥对密文进行AES解密。

加密思路:

  1. 调用方先将请求参数用AES加密,再利用RSA公钥对AES的密钥值加密;
  2. 调用方将加密后的数据发送给服务端;
  3. 服务端接收到头信息里的加密串,先用RSA私钥解密出AES密钥值,再用解密出的AES密钥值解密请求参数;
  4. 处理完毕后,服务端再用AES密钥对响应参数加密;
  5. 将加密后的结果返回给调用方。

混合加密原因

  1. 单纯的使用 RSA(非对称加密)方式,效率会很低,因为非对称加密解密方式虽然很保险,但是过程复杂,耗费时间长,性能不高;
  2. RSA优势在于数据传输安全,且对于几个字节的数据,加密和解密时间基本可以忽略,所以用它非常适合加密 AES 秘钥(一般16个字节);
  3. 单纯的使用AES(对称加密)方式的话,非常不安全。这种方式使用的密钥是一个固定的密钥,客户端和服务端是一样的,一旦密钥被人获取,那么,我们所发的每一条数据都会被都对方破解;
  4. AES有个很大的优点,那就是加密解密效率很高,而我们传输正文数据时,正好需要这种加解密效率高的,所以这种方式适合用于传输量大的数据内容。

AES加密工具:

public class AESUtil {
        /**
         * 密钥算法
         */
        private static final String KEY_ALGORITHM = "AES";
        private static String bit = "321";
        /**
         * 加密/解密算法 / 工作模式 / 填充方式
         * Java 6支持PKCS5Padding填充方式
         * Bouncy Castle支持PKCS7Padding填充方式
         */
        private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS7Padding";

        static {
            //如果是PKCS7Padding填充方式,则必须加上下面这行
            Security.addProvider(new BouncyCastleProvider());
        }

        /**
         * 生成密钥
         * @return	密钥
         * @throws Exception
         */
        public static String generateKey() throws Exception {
            //实例化密钥生成器
            KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
            kg.init(128, new SecureRandom(bit.getBytes()));
            //生成密钥
            SecretKey secretKey = kg.generateKey();
            //获得密钥的字符串形式
            return Base64.encodeBase64String(secretKey.getEncoded());
        }

        public static Key getKey(String strKey) {
            try {
                if (strKey == null) {
                    strKey = "";
                }
                KeyGenerator _generator = KeyGenerator.getInstance("AES");
                SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
                secureRandom.setSeed(strKey.getBytes());
                _generator.init(128, secureRandom);
                return _generator.generateKey();
            } catch (Exception e) {
                throw new RuntimeException(" 初始化密钥出现异常 ");
            }
        }
        public static String aesEncrypt(String sourceStr, String encryptKey) throws Exception {
            return encrypt(sourceStr, Base64.encodeBase64String(encryptKey.getBytes()));
        }
         /**
         * AES加密
         * @param source 源字符串
         * @param key 密钥
         * @return 加密后的密文
         * @throws Exception
         */
        public static String encrypt(String source, String key) throws Exception {
            byte[] sourceBytes = source.getBytes(StandardCharsets.UTF_8);
            byte[] keyBytes = Base64.decodeBase64(key);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            SecretKeySpec secretKey = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
            System.out.println("secretKey length:" + secretKey.getEncoded().length);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] decrypted = cipher.doFinal(sourceBytes);
            return Base64.encodeBase64String(decrypted);
        }

        public static String aesDecrypt(String encryptedStr, String decryptKey) throws Exception {
            return decrypt(encryptedStr, Base64.encodeBase64String(decryptKey.getBytes()));
        }
        /**
         * AES解密
         * @param encryptStr 加密后的密文
         * @param key 密钥
         * @return 源字符串
         * @throws Exception
         */
        public static String decrypt(String encryptStr, String key) throws Exception {
            byte[] sourceBytes = Base64.decodeBase64(encryptStr);
            byte[] keyBytes = Base64.decodeBase64(key);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, KEY_ALGORITHM));
            byte[] decoded = cipher.doFinal(sourceBytes);
            return new String(decoded, StandardCharsets.UTF_8);
        }
}

RSA加密工具:

public class RsaUtil {

    /**
     * 安全加固 PHP填充方式
     */
    private static final String CIPHER_ALGORITHM = "RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING";

    /**
     * 用于封装随机产生的公钥与私钥
     */
    private static Map<Integer, String> keyMap = new HashMap<Integer, String>();

    /**
     * 0表示公钥
     */
    private final static Integer publicKeyFlag = 0;

    /**
     * 1表示私钥
     */
    private final static Integer privateKeyFlag = 1;

    /**
     * 算法
     */
    private final static String algorithm = "RSA";

    /**
     * 密钥大小为96-1024位
     */
    private final static Integer keySize = 1024;

    /**
     * 随机生成密钥对
     * @throws NoSuchAlgorithmException
     */
    public static Map<Integer, String> genKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(algorithm);
        // 初始化密钥对生成器
        keyPairGen.initialize(keySize,new SecureRandom());
        // 生成一个密钥对,保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 得到公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        // 得到私钥字符串
        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
        // 将公钥和私钥保存到Map
        keyMap.put(publicKeyFlag,publicKeyString);
        keyMap.put(privateKeyFlag,privateKeyString);
        return keyMap;
    }
    /**
     * RSA公钥加密
     * @param str 加密字符串
     * @param publicKey 公钥
     * @param urlSafe url安全
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt( String str, String publicKey, boolean urlSafe ) throws Exception{
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] bdata=cipher.doFinal(str.getBytes("UTF-8"));
        if(urlSafe) {
           return  Base64.encodeBase64URLSafeString(bdata);
        }
        return Base64.encodeBase64String(bdata);
    }

    /**
     * RSA私钥解密
     * @param str 加密字符串
     * @param privateKey 私钥
     * @return 铭文
     * @throws Exception 解密过程中的异常信息
     */
    public static String decrypt(String str, String privateKey) throws Exception{
        //64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKey);
            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(algorithm).generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        return new String(cipher.doFinal(inputByte));
    }


    /**
     * RSA公钥加密(RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING)
     *
     * @param str
     *            加密字符串
     * @param publicKey
     *            公钥
     * @return 密文
     * @throws Exception
     *             加密过程中的异常信息
     */
    public static String encryptNew( String str, String publicKey) throws Exception{

        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] byteData=cipher.doFinal(str.getBytes("UTF-8"));

        return  Base64.encodeBase64String(byteData);
    }

    /**
     * RSA私钥解密(RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING)
     *
     * @param str
     *            加密字符串
     * @param privateKey
     *            私钥
     * @return 铭文
     * @throws Exception
     *             解密过程中的异常信息
     */
    public static String decryptNew(String str, String privateKey) throws Exception{
        //64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(algorithm).generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        return new String(cipher.doFinal(inputByte));
    }
}
  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,我们可以使用RSA算法来加密AES的密钥,然后使用AES算法来加密数据。 1. 生成RSA公私钥对 ```java KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048); KeyPair keyPair = generator.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); ``` 2. 使用RSA公钥加密AES密钥 ```java // 生成AES密钥 KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128); SecretKey secretKey = keyGenerator.generateKey(); // 使用RSA公钥加密AES密钥 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encryptedKey = cipher.doFinal(secretKey.getEncoded()); ``` 3. 使用AES密钥加密数据 ```java // 使用AES密钥加密数据 byte[] rawData = "hello world".getBytes("UTF-8"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedData = cipher.doFinal(rawData); ``` 4. 使用RSA私钥解密AES密钥 ```java // 使用RSA私钥解密AES密钥 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedKey = cipher.doFinal(encryptedKey); SecretKey originalKey = new SecretKeySpec(decryptedKey, 0, decryptedKey.length, "AES"); ``` 5. 使用AES密钥解密数据 ```java // 使用AES密钥解密数据 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, originalKey); byte[] decryptedData = cipher.doFinal(encryptedData); ``` 注意事项: - AES密钥需要保密,不能直接传输或存储。 - RSA加密的数据长度不能超过RSA公钥的长度。因此,如果需要加密的数据较长,可以使用AES算法对数据进行分块加密

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值