RSA 密钥对
最近做的项目有要求对传输的数据进行加密和解密,所以就用到了RSA非对称加密,所以在这里记录一下。
首先介绍下什么是RSA加密算法吧(复制的)
RSA加密算法是一种非对称加密算法。在公开密钥加密和电子商业中RSA被广泛使用。RSA是1977年由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的。当时他们三人都在麻省理工学院工作。RSA就是他们三人姓氏开头字母拼在一起组成的。
在公开密钥密码体制中,加密密钥(即公开密钥)PK是公开信息,而解密密钥(即秘密密钥)SK是需要保密的。加密算法E和解密算法D也都是公开的。虽然解密密钥SK是由公开密钥PK决定的,由于无法计算出大数n的欧拉函数phi(N),所以不能根据PK计算出SK
正是基于这种理论,1978年出现了著名的RSA算法,它通常是先生成一对RSA 密钥,其中之一是保密密钥,由用户保存;另一个为公开密钥,可对外公开,甚至可在网络服务器中注册。为提高保密强度,RSA密钥至少为500位长,一般推荐使用1024位。这就使加密的计算量很大。为减少计算量,在传送信息时,常采用传统加密方法与公开密钥加密方法相结合的方式,即信息采用改进的DES或IDEA密钥加密,然后使用RSA密钥加密对话密钥和信息摘要。对方收到信息后,用不同的密钥解密并可核对信息摘要。RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作。RSA是被研究得最广泛的公钥算法,从提出到现今的三十多年里,经历了各种攻击的考验,逐渐为人们接受,截止2017年被普遍认为是最优秀的公钥方案之一。出自:https://www.jianshu.com/p/d614ba4720ec
下面是数据的加密和解密过程
public class RSAGenerator{
public static void main(String[] args) throws Exception {
String data = "abc";
KeyPair keyPair = generateRSAKeyPair(DEFAULT_KEY_SIZE);
PublicKey aPublic = keyPair.getPublic(); // 公钥
PrivateKey aPrivate = keyPair.getPrivate(); // 私钥
String strPriKey = new String(Base64.getEncoder().encode(aPrivate.getEncoded()));
String strPubKey = new String(Base64.getEncoder().encode(aPublic.getEncoded()));
System.out.println(strPubKey);
System.out.println("-------------");
System.out.println(strPriKey);
System.out.println("--------------");
System.out.println("加密如下");
System.out.println("vvvvvvvvvvvv");
byte[] encrypt = encrypt(data.getBytes(), aPublic);
System.out.println(new String(encrypt));
System.out.println("解密如下");
System.out.println("vvvvvvvvvvvv");
byte[] bytes1 = decrypt(encrypt, aPrivate);
System.out.println(new String(bytes1));
}
public static final String RSA = "RSA";// 非对称加密密钥算法
public static final String ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding";//加密填充方式
public static final int DEFAULT_KEY_SIZE = 1024;//秘钥默认长度
public static final byte[] DEFAULT_SPLIT = "#PART#".getBytes(); // 当要加密的内容超过bufferSize,则采用partSplit进行分块加密
public static final int DEFAULT_BUFFERSIZE = (DEFAULT_KEY_SIZE / 8) - 11;// 当前秘钥支持加密的最大字节数
public static KeyPair generateRSAKeyPair(int keyLength) {
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
kpg.initialize(keyLength);
return kpg.genKeyPair();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
//公钥加密
public static byte[] encrypt(byte[] content, PublicKey publicKey) throws Exception{
Cipher cipher=Cipher.getInstance(ECB_PKCS1_PADDING);//java默认"RSA"="RSA/ECB/PKCS1Padding"
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(content);
}
//私钥解密
public static byte[] decrypt(byte[] content, PrivateKey privateKey) throws Exception{
Cipher cipher=Cipher.getInstance(ECB_PKCS1_PADDING);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(content);
}
}