java+aes+ras_AES与RAS结合加解密方案

该博客详细介绍了如何使用Java实现AES和RSA两种加密算法的结合,包括加载公钥和私钥,进行加密和解密操作。通过示例展示了如何使用RSA加密AES的密钥,然后使用AES对数据进行加密,最后使用RSA解密得到AES密钥并解密数据的过程。
摘要由CSDN通过智能技术生成

importjava.io.IOException;importjava.security.InvalidKeyException;importjava.security.KeyFactory;importjava.security.NoSuchAlgorithmException;importjava.security.PrivateKey;importjava.security.PublicKey;importjava.security.interfaces.RSAPublicKey;importjava.security.spec.InvalidKeySpecException;importjava.security.spec.PKCS8EncodedKeySpec;importjava.security.spec.X509EncodedKeySpec;importjavax.crypto.BadPaddingException;importjavax.crypto.Cipher;importjavax.crypto.IllegalBlockSizeException;importjavax.crypto.NoSuchPaddingException;importorg.apache.commons.codec.binary.Base64;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importsun.misc.BASE64Decoder;public classRSAUtils {private static final Logger LOGGER = LoggerFactory.getLogger(RSAUtils.class);public static final String KEY_ALGORITHM = "RSA";public static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";public static final String PUBLIC_KEY = "publicKey";public static final String PRIVATE_KEY = "privateKey";public static final int KEY_SIZE = 1024;public static final String PLAIN_TEXT = "MANUTD is the greatest club in the world";public static final String DEFAULT_PRIVATE_KEY =

"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALLzcCAoQaBK3X0cPbsu1xKUsuwQ\n" +

"vtVz12t16ARd2fza5H6A3aekI1DZV/+U6IT7LQm/75uOlTpek7W8nRZJsrxqK523RILCds5UEkGE\n" +

"yM87RulTtL+acMBUg3nPxUQiBKj7W79VNDmxX5pO55d/tlIXl9tldQahykkLNSS8HTLzAgMBAAEC\n" +

"gYAhqBOAmNGu+iWqMDOUDv04a2szZvrdXoo3lddratNi8TBkcow9yWsy+43HbhRFXpBb8xN3qFt8\n" +

"vOj/F1hcJsRMxikzSnnDPtri48mx6esMG2v/Jt+eb5tfk4fTmboXXWRMiSjFG8B6cAaCxEwaykSV\n" +

"CSI4S23aWrnJ9I6tezNDQQJBAPiQ7OqNb1/J7nWsKeWZCLLWYwZK2wCmb+IQZ8WUi4mIUlj6tkBX\n" +

"rD+XAmdK1OXgjLHUlMAM0GZ0NQJfD++FdvECQQC4TYYliyJTjXoWDEBWWaVASRfK7RXBq8JTeXGg\n" +

"5bjQZzJsmfqS5aU8Qz1AZyc9gjXuMJMqszv+WuyQ5vyLHPAjAkEAwvC2PcWqoU83KyZYvW5lugwV\n" +

"IWw3kaz2di8zk2tKfBRjsND/ejrIJh8CjYvMqHSRIy57cpsaHh/pKvDvCIR9oQJBAKGceVFanBMg\n" +

"MDo9K/2MRngEoDR1iWp2rsR77cPlLRayJ2lL7In7jdU2MPPUgHhTQe9H8QS0fpsgJ+k4Y6OpEHkC\n" +

"QBvpHMdDZG9e7+eTeHTss5eZ6MzEA0umVZYrk+9egqDD5bVl11E/A6xoAMzRPsfsBxxaltnXwCyr\n" +

"HjjWbeNVKso=";public static final String DEFAULT_PUBLIC_KEY =

"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCy83AgKEGgSt19HD27LtcSlLLsEL7Vc9drdegE\n" +

"Xdn82uR+gN2npCNQ2Vf/lOiE+y0Jv++bjpU6XpO1vJ0WSbK8aiudt0SCwnbOVBJBhMjPO0bpU7S/\n" +

"mnDAVIN5z8VEIgSo+1u/VTQ5sV+aTueXf7ZSF5fbZXUGocpJCzUkvB0y8wIDAQAB";/*** 获取公钥

*@parampublicKeyStr

*@return*@throwsException*/

public static PublicKey loadPublicKey(String publicKeyStr) throwsException {try{

BASE64Decoder base64Decoder= newBASE64Decoder();byte[] buffer =base64Decoder.decodeBuffer(publicKeyStr);

KeyFactory keyFactory= KeyFactory.getInstance("RSA");

X509EncodedKeySpec keySpec= newX509EncodedKeySpec(buffer);

RSAPublicKey publicKey=(RSAPublicKey) keyFactory.generatePublic(keySpec);returnrestorePublicKey(publicKey.getEncoded());

}catch(NoSuchAlgorithmException e) {throw new Exception("无此算法");

}catch(InvalidKeySpecException e) {throw new Exception("公钥非法");

}catch(IOException e) {throw new Exception("公钥数据内容读取错误");

}catch(NullPointerException e) {throw new Exception("公钥数据为空");

}

}/*** 还原公钥,X509EncodedKeySpec 用于构建公钥的规范

*

*@paramkeyBytes

*@return

*/

public static PublicKey restorePublicKey(byte[] keyBytes) throwsException {

X509EncodedKeySpec x509EncodedKeySpec= newX509EncodedKeySpec(keyBytes);try{

KeyFactory factory=KeyFactory.getInstance(KEY_ALGORITHM);

PublicKey publicKey=factory.generatePublic(x509EncodedKeySpec);returnpublicKey;

}catch (NoSuchAlgorithmException |InvalidKeySpecException e) {//TODO Auto-generated catch block

throw new Exception("");

}

}/*** 通过私钥KEY获取解密私钥

*@paramprivateKeyStr

*@return*@throwsException*/

public static PrivateKey loadPrivateKey(String privateKeyStr) throwsException {try{

BASE64Decoder base64Decoder= newBASE64Decoder();byte[] buffer =base64Decoder.decodeBuffer(privateKeyStr);

PKCS8EncodedKeySpec keySpec= newPKCS8EncodedKeySpec(buffer);

KeyFactory keyFactory= KeyFactory.getInstance("RSA");

PrivateKey privateKey=keyFactory.generatePrivate(keySpec);returnrestorePrivateKey(privateKey.getEncoded());

}catch(NoSuchAlgorithmException e) {throw new Exception("无此算法");

}catch(InvalidKeySpecException e) {throw new Exception("公钥非法");

}catch(IOException e) {throw new Exception("公钥数据内容读取错误");

}catch(NullPointerException e) {throw new Exception("公钥数据为空");

}

}/*** 获取私钥

*@paramkeyBytes

*@return

*/

public static PrivateKey restorePrivateKey(byte[] keyBytes) {

PKCS8EncodedKeySpec pkcs8EncodedKeySpec= newPKCS8EncodedKeySpec(keyBytes);try{

KeyFactory factory=KeyFactory.getInstance(KEY_ALGORITHM);

PrivateKey privateKey=factory.generatePrivate(pkcs8EncodedKeySpec);returnprivateKey;

}catch (NoSuchAlgorithmException |InvalidKeySpecException e) {//TODO Auto-generated catch block

LOGGER.error("获取私钥失败", e);

}return null;

}/*** 加密,三步走。

*

*@paramkey

*@paramplainText

*@return

*/

public static byte[] RSAEncode(PublicKey key, byte[] plainText) {try{

Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM);

cipher.init(Cipher.ENCRYPT_MODE, key);returncipher.doFinal(plainText);

}catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException |BadPaddingException e) {//TODO Auto-generated catch block

LOGGER.error("加密失败", e);

}return null;

}/*** 解密,三步走。

*

*@paramkey

*@paramencodedText

*@return

*/

public static byte[] RSADecode(PrivateKey key, byte[] encodedText) {try{

Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM);

cipher.init(Cipher.DECRYPT_MODE, key);returncipher.doFinal(encodedText);

}catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException |BadPaddingException e) {//TODO Auto-generated catch block

LOGGER.error("解密失败", e);

}return null;

}public static void main(String[] ar) throwsException {

String str= "{\"a\":\"欢迎来到chacuo\"}";

System.out.println("待加密报文:" +str);

PublicKey publicKey=loadPublicKey(DEFAULT_PUBLIC_KEY);

PrivateKey privateKey=loadPrivateKey(DEFAULT_PRIVATE_KEY);//String encodeStr = Base64.encodeBase64String(RSAEncode(publicKey, str.getBytes()));//System.out.println("加密后密文:" + encodeStr);//String decodeStr = new String(RSADecode(privateKey, Base64.decodeBase64(encodeStr)));//System.out.println("解密后密文:" + decodeStr);

String randomKey=String.valueOf(System.currentTimeMillis());

System.out.println("随机KEY randomKey:"+randomKey);

String cipherText=AESUtils.encrypt(str,randomKey);

System.out.println("AES加密请求内容cipherText:"+cipherText);

String cipherKey=Base64.encodeBase64String(RSAEncode(publicKey, randomKey.getBytes()));

System.out.println("RSA加密后的key:"+cipherKey);

System.out.println("请求内容:{\"encryptStr\":\"" + cipherText+"\",\"aesKey\":\""+cipherKey+"\"}");

String key= newString(RSADecode(privateKey, Base64.decodeBase64(cipherKey)));

System.out.println("RSA私钥解密后的key:"+key);

String decodeData=AESUtils.decrypt(cipherText,key);

System.out.println("AES解密后:"+decodeData);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值