JAVA RSA与AES混合加密解密

背景系统最近要上云,一部分数据是oracle数据库的,所以需要一个中转接口负责数据传输,接口数据需要保障安全,所以选择了RSA与AES结合的方式进行加密处理。

集百家之所长,最后得已实现。

目录

方案

RSA加密解密

AES加密解密

RAS与AES加密解密整合


方案


       具体过程是先由接收方创建RSA密钥对,接收方通过Internet发送RSA公钥到发送方,同时保存RSA私钥。而发送方创建AES密钥,并用该AES密钥加密待传送的明文数据,同时用接受的RSA公钥加密AES密钥,最后把用RSA公钥加密后的AES密钥同密文一起通过Internet传输发送到接收方。当接收方收到这个被加密的AES密钥和密文后,首先调用接收方保存的RSA私钥,并用该私钥解密加密的AES密钥,得到AES密钥。最后用该AES密钥解密密文得到明文。
--------------------- 

RSA、AES加密原理


RSA加密解密

import javax.crypto.Cipher;
import java.io.IOException;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAUtil {

    /**
     * 生成秘钥对
     * @return
     * @throws Exception
     */
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        return keyPair;
    }

    /**
     * 获取公钥(Base64编码)
     * @param keyPair
     * @return
     */
    public static String getPublicKey(KeyPair keyPair){
        PublicKey publicKey = keyPair.getPublic();
        byte[] bytes = publicKey.getEncoded();
        return byte2Base64(bytes);
    }

    /**
     * 获取私钥(Base64编码)
     * @param keyPair
     * @return
     */
    public static String getPrivateKey(KeyPair keyPair){
        PrivateKey privateKey = keyPair.getPrivate();
        byte[] bytes = privateKey.getEncoded();
        return byte2Base64(bytes);
    }

    /**
     * 将Base64编码后的公钥转换成PublicKey对象
     * @param pubStr
     * @return
     * @throws Exception
     */
    public static PublicKey string2PublicKey(String pubStr) throws Exception{
        byte[] keyBytes = base642Byte(pubStr);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    /**
     * 将Base64编码后的私钥转换成PrivateKey对象
     * @param priStr
     * @return
     * @throws Exception
     */
    public static PrivateKey string2PrivateKey(String priStr) throws Exception{
        byte[] keyBytes = base642Byte(priStr);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    /**
     * 公钥加密
     * @param content
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static byte[] publicEncrypt(byte[] content, PublicKey publicKey) throws Exception{
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] bytes = cipher.doFinal(content);
        return bytes;
    }

    /**
     * 私钥解密
     * @param content
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static byte[] privateDecrypt(byte[] content, PrivateKey privateKey) throws Exception{
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] bytes = cipher.doFinal(content);
        return bytes;
    }

    /**
     * 字节数组转Base64编码
     * @param bytes
     * @return
     */
    public static String byte2Base64(byte[] bytes){
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * Base64编码转字节数组
     * @param base64Key
     * @return
     * @throws IOException
     */
    public static byte[] base642Byte(String base64Key) {
        return Base64.getDecoder().decode(base64Key);
    }
}

AES加密解密

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESUtil {

    /**
     * 生成AES秘钥,然后Base64编码
     * @return
     * @throws Exception
     */
    public static String genKeyAES() throws Exception{
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);
        SecretKey key = keyGen.generateKey();
        String base64Str = byte2Base64(key.getEncoded());
        return base64Str;
    }

    /**
     * 将Base64编码后的AES秘钥转换成SecretKey对象
     * @param base64Key
     * @return
     * @throws Exception
     */
    public static SecretKey loadKeyAES(String base64Key) throws Exception{
        SecretKeySpec key = new SecretKeySpec(base64Key.getBytes("utf-8"), "AES");
        return key;
    }

    /**
     * 字节数组转Base64编码
     * @param bytes
     * @return
     */
    public static String byte2Base64(byte[] bytes){
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * Base64编码转字节数组
     * @param base64Key
     * @return
     */
    public static byte[] base642Byte(String base64Key) {
        return Base64.getDecoder().decode(base64Key);
    }

    /**
     * 加密
     * @param source
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encryptAES(byte[] source, SecretKey key) throws Exception{
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(source);
    }

    /**
     * 解密
     * @param source
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptAES(byte[] source, SecretKey key) throws Exception{
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(source);
    }

}

RAS与AES加密解密整合

public class TestAesAndRsa {
    //测试RSA与AES的结合。
    //					客户端用公钥加密AES秘钥,AES秘钥加密实际内容;
    //					服务端用私钥解密AES秘钥,AES秘钥解密实际内容
    public static void testAesAndRsa() throws Exception {
        //===============生成公钥和私钥,公钥传给客户端,私钥服务端保留==================
        //生成RSA公钥和私钥,并Base64编码,生成一次以后,就写死在配置文件或代码中,下次不再重新生成
        KeyPair keyPair = RSAUtil.getKeyPair();
        String publicKeyStr = RSAUtil.getPublicKey(keyPair);
        String privateKeyStr = RSAUtil.getPrivateKey(keyPair);
        System.out.println("RSA公钥Base64编码:" + publicKeyStr);
        System.out.println("RSA私钥Base64编码:" + privateKeyStr);

        //=================客户端=================
        //hello, i am infi, good night!  需要加密的实际内容
        String message = "hello, i am infi, good night!";
        //将Base64编码后的公钥转换成PublicKey对象
        PublicKey publicKey = RSAUtil.string2PublicKey(publicKeyStr);
        //生成AES秘钥,并Base64编码
        String aesKeyStr = AESUtil.genKeyAES();
        System.out.println("AES秘钥Base64编码:" + aesKeyStr);
        //用公钥加密AES秘钥
        byte[] publicEncrypt = RSAUtil.publicEncrypt(aesKeyStr.getBytes(), publicKey);
        //公钥加密AES秘钥后的内容Base64编码
        String publicEncryptStr = RSAUtil.byte2Base64(publicEncrypt);
        System.out.println("公钥加密AES秘钥并Base64编码的结果:" + publicEncryptStr);

        //将Base64编码后的AES秘钥转换成SecretKey对象
        SecretKey aesKey = AESUtil.loadKeyAES(aesKeyStr);
        //用AES秘钥加密实际的内容
        byte[] encryptAES = AESUtil.encryptAES(message.getBytes(), aesKey);
        //AES秘钥加密后的内容Base64编码
        String encryptAESStr = AESUtil.byte2Base64(encryptAES);
        System.out.println("AES秘钥加密实际的内容并Base64编码的结果:" + encryptAESStr);


        //##############	网络上传输的内容有Base64编码后的公钥加密AES秘钥的结果 和 Base64编码后的AES秘钥加密实际内容的结果   #################
        //##############	即publicEncryptStr和encryptAESStr	###################


        //===================服务端================
        //将Base64编码后的私钥转换成PrivateKey对象
        PrivateKey privateKey = RSAUtil.string2PrivateKey(privateKeyStr);
        //公钥加密AES秘钥后的内容(Base64编码),进行Base64解码
        byte[] publicEncrypt2 = RSAUtil.base642Byte(publicEncryptStr);
        //用私钥解密,得到aesKey
        byte[] aesKeyStrBytes = RSAUtil.privateDecrypt(publicEncrypt2, privateKey);
        //解密后的aesKey
        String aesKeyStr2 = new String(aesKeyStrBytes);
        System.out.println("解密后的aesKey(Base64编码): " + aesKeyStr2);

        //将Base64编码后的AES秘钥转换成SecretKey对象
        SecretKey aesKey2 = AESUtil.loadKeyAES(aesKeyStr2);
        //AES秘钥加密后的内容(Base64编码),进行Base64解码
        byte[] encryptAES2 = AESUtil.base642Byte(encryptAESStr);
        //用AES秘钥解密实际的内容
        byte[] decryptAES = AESUtil.decryptAES(encryptAES2, aesKey2);
        //解密后的实际内容
        System.out.println("解密后的实际内容: " + new String(decryptAES));
    }


}

参考:java实现RSA+AES的简单加密解密

以上为JAVA RSA与AES混合加密


遇到问题:与我对接的系统是c#开发的,所以在对接的时候会遇到问题,AES解密会报错 Illegal key size or default parameters

c# RSA与AES加密解密

AES报错指南

 

 

  • 3
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当然可以!下面是一个使用RSAAES混合加密的示例代码: ```python from Crypto.Cipher import AES, PKCS1_OAEP from Crypto.PublicKey import RSA from Crypto.Random import get_random_bytes # 生成RSA密钥对 key = RSA.generate(2048) private_key = key.export_key() public_key = key.publickey().export_key() # 加密数据 data = b'This is a secret message.' # 使用AES生成随机密钥 session_key = get_random_bytes(16) # 使用RSA公钥加密AES密钥 rsa_cipher = PKCS1_OAEP.new(RSA.import_key(public_key)) encrypted_session_key = rsa_cipher.encrypt(session_key) # 使用AES加密数据 aes_cipher = AES.new(session_key, AES.MODE_EAX) ciphertext, tag = aes_cipher.encrypt_and_digest(data) # 传输加密后的数据和密钥... # 接收方解密数据 # 使用RSA私钥解密AES密钥 rsa_cipher = PKCS1_OAEP.new(RSA.import_key(private_key)) session_key = rsa_cipher.decrypt(encrypted_session_key) # 使用AES解密数据 aes_cipher = AES.new(session_key, AES.MODE_EAX) decrypted_data = aes_cipher.decrypt_and_verify(ciphertext, tag) print(decrypted_data.decode()) ``` 在这个示例中,首先生成了一个RSA密钥对。然后,生成了一个随机的AES密钥,并使用RSA公钥加密了该密钥。接下来,使用AES密钥对要加密的数据进行加密,并生成了一个认证标签。最后,发送加密后的数据和加密AES密钥给接收方。 接收方使用RSA私钥解密接收到的AES密钥,并使用解密后的AES密钥解密数据,并进行认证。 请注意,这只是一个简单的示例代码,用于演示RSAAES混合加密的基本概念。在实际应用中,需要更多的安全措施和错误处理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值