Java笔记-非对称加密RSA的使用
Posted IT1995
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java笔记-非对称加密RSA的使用相关的知识,希望对你有一定的参考价值。
使用OpenSSL生成对应RSA私钥和RSA公钥:
#rsa私钥:
genrsa -out rsa_private_key.pem 1024
pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform pem -nocrypt -out rsa_private_key_8.pem
#rsa公钥:
rsa -in rsa_private_key_8.pem -pubout -out rsa_public_key.pem
Base64使用的是这样Maven
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
这里生成的公钥和私钥是Base64的,如下:
公钥:
所以用的时候需要先用base64解密。
使用逻辑是这样的,先那这些密钥进行Base64解密。
在用公钥给内容加密,用私钥解密:
Base64相关的代码:
DataSecret.java
package cn.it1995.tool;
import org.apache.commons.codec.binary.Base64;
import java.io.UnsupportedEncodingException;
public class DataSecret {
public static byte[] encode(byte[] txt) throws UnsupportedEncodingException {
return Base64.encodeBase64(txt);
}
public static byte[] decode(String txt){
return Base64.decodeBase64(txt);
}
}
RSA.java
package cn.it1995.tool;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RSA {
private static final String RSA_ALGORITHM = "RSA/ECB/PKCS1Padding";
//加密回的是base64
public static String encrypt(String data, String key) throws UnsupportedEncodingException {
String message = data;
byte[] decode = DataSecret.decode(key);
byte[] result = new byte[]{0};
try {
RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
.generatePublic(new X509EncodedKeySpec(decode));
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
result = cipher.doFinal(message.getBytes("UTF-8"));
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (InvalidKeySpecException e) {
e.printStackTrace();
}
catch (NoSuchPaddingException e) {
e.printStackTrace();
}
catch (BadPaddingException e) {
e.printStackTrace();
}
catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
catch (InvalidKeyException e) {
e.printStackTrace();
}
return new String(DataSecret.encode(result));
}
//解密
public static String decrypt(String encrypted, String key){
byte[] content = DataSecret.decode(encrypted);
byte[] decoded = DataSecret.decode(key);
byte[] result = new byte[]{0};
try {
RSAPrivateCrtKey priKey = (RSAPrivateCrtKey)KeyFactory.getInstance("RSA")
.generatePrivate(new PKCS8EncodedKeySpec(decoded));
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, priKey);
result = cipher.doFinal(content);
}
catch (InvalidKeySpecException e){
e.printStackTrace();
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (NoSuchPaddingException e) {
e.printStackTrace();
}
catch (InvalidKeyException e) {
e.printStackTrace();
}
catch (BadPaddingException e) {
e.printStackTrace();
}
catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
return new String(result);
}
}
调用代码:
private static final String PUB_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCjuN97tkBc0QcKGU9oXydaQN7q" +
"wZnThxTOmdIc8O1yuA9FrDZpZ3Sz908vTqM/YPZkOUaYrGwsBO7FeQovoX7nQPKu" +
"YQpRDqt7OKzhwPavyynH0Jz38PDyCBw45zwl4Ux8BtsggTrGVxAqNjO4KkuyL1QS" +
"8amn4Fzl1CBre8Y0gQIDAQAB";
private static final String PRI_KEY = "MIICdAIBADANBgkqhkiG9w0BAQEFAASCAl4wggJaAgEAAoGBAKO433u2QFzRBwoZ" +
"T2hfJ1pA3urBmdOHFM6Z0hzw7XK4D0WsNmlndLP3Ty9Ooz9g9mQ5RpisbCwE7sV5" +
"Ci+hfudA8q5hClEOq3s4rOHA9q/LKcfQnPfw8PIIHDjnPCXhTHwG2yCBOsZXECo2" +
"M7gqS7IvVBLxqafgXOXUIGt7xjSBAgMBAAECgYAgp0uzcdsOaAY+ZmPnDitcHdoX" +
"+jsC7EsjFZzJduf03G73V2yWwzKMfkPFzKpUhrM9tAq3gpQkh2tT6Vs1usEDbrDd" +
"e08Cc3D5YWK7HuTfO3kkJTSNOK0JfuT1UQaTjCmDQWWjPmYbu6UN0UDv4Mo26dgl" +
"cp9h0wlaPsSFN3O97QJBANgj+4i7ABAdbTuUfq6Tcr38E7wYSFTUeL5jTd4sO636" +
"+KJ6zx4uTXAmxnt9OdIY1ihLRqDh8VbiorqOelGf6iMCQQDB6jZver3mTMe6ntSY" +
"hx3JWOCDM3ULkPvOWGrAcRsNKjyIuo37taXa7fuqmVQQq9MJYikJfilMhkgwkV/X" +
"ihcLAkBsOvBskj9A0ottJzmcT4dIbR6wtHQbzl078NwAIaQsxZyVN+vY0BTE0RXY" +
"pmc6tmcevDr8uscv28Liqg/EKdCDAkAjL9C44djblUsYvgFtu/bXtlzm8ctnUeOf" +
"ScP1L5DtDqD1XoStDAUQeOaVykTK0aL1rO4tXss3q5Yl2fs+LTyJAj8f7N5kzw08" +
"9S5OWCHoEm5UOeAvjFh//cjXi6lyqetBW3w17muZ2OumUAbKJXksyzmT6/QRpkX3" +
"S0w/tqdJXLs=";
public static void main(String[] args) throws UnsupportedEncodingException {
String content = "123456";
String encrypted = RSA.encrypt(content, PUB_KEY);
System.out.println(encrypted);
System.out.println(RSA.decrypt(encrypted, PRI_KEY));
......
......
}
运行截图如下:
以上是关于Java笔记-非对称加密RSA的使用的主要内容,如果未能解决你的问题,请参考以下文章