RSA是目前最流行的非对称密码,目前广泛应用在数字签名,数字证书上。
那么什么是非对称密码呢?就是给明文加密的密钥和给密文解密的密钥是不一样的。其中,对外暴露的是公钥,自己保留的是私钥,如果用公钥加密,就只能用私钥解密,如果用私钥加密就只能用公钥解密。
所以实现非对称密码,需要生成公私钥对。而由于RSA的非对称密码原理是基于大素数因子的难分解性,所以每次在生成公私钥对的时候在一开始都会随机产生两个素数p,q。所以每次生成的公私钥对也是不相同的。
接下来我们就开始用Java自带的API完成RSA的公私钥对生成和加密解密操作。
- 在Java中,对于非对称密码操作的一个类是:KeyPairGenerator,密钥对生成器类,这个类在java.security.KeyPairGenerator包下。这个类在产生对象的时候需要往构造方法中传入一个String的值,告诉密钥对生成器生成的是哪一中密码的密钥对。
//使用RSA算法获得密钥对生成器对象keyPairGenerator
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
//设置密钥长度为1024
keyPairGenerator.initialize(1024);
//生成密钥对
KeyPair keyPair = keyPairGenerator.generateKeyPair();
//获取公钥
Key publicKey = keyPair.getPublic();
//获取私钥
Key privateKey = keyPair.getPrivate();
- 获取到公私钥对的时候,为了方便后续操作,我们一般将这两个key对象持久化到本地保存起来。(由于暂时没能实现保存到数据库中【Key类型和String类型无法转化】,因此需要保存到本地中)
- 在Java中提供了Cipher加密解密器来实现加解密操作,这个类在import javax.crypto.Cipher包下。在产生这个加密解密器对象的时候,需要在他的构造方法中传俩个值,一个是功能,一个是算法种类。功能就是说告诉他接下来这个对象是需要做加密操作还是解密操作,算法种类就是告诉他使用的加密算法。
//获取一个加密算法为RSA的加解密器对象cipher。
Cipher cipher = Cipher.getInstance("RSA");
//设置为加密模式,并将公钥给cipher。
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
//获得密文
byte[] secret = cipher.doFinal(str.getBytes());
//进行Base64编码并返回
return new BASE64Encoder().encode(secret);
- 同样的,解密算法也是使用Cilpher。
Cipher cipher = Cipher.getInstance("RSA");
//传递私钥,设置为解密模式。
cipher.init(Cipher.DECRYPT_MODE, privateKey);
//解密器解密由Base64解码后的密文,获得明文字节数组
byte[] b = cipher.doFinal(new BASE64Decoder().decodeBuffer(secret));
//转换成字符串
return new String(b);
以上就是使用Java自带API完成RSA密钥对生成和加密解密的方法。
============================================================
封装成一个RSAUtils
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Scanner;
import javax.crypto.Cipher;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
*
* @author 张伦琦—绝世好玉
*
*/
class RSAUtils {
//默认公钥的持久化文件存放位置
private static String PUBLIC_KEY_FILE = "PublicKey";
//默认私钥的持久化文件存放位置
private static String PRIVATE_KEY_FILE = "PrivateKey";
//设置公私钥持久化文件的存放位置
public static void setKeyPath(String path) {
if (PUBLIC_KEY_FILE.equals("PublicKey")) {
PUBLIC_KEY_FILE = path + (path.endsWith("//")?"PublicKey":"/PublicKey");
PRIVATE_KEY_FILE = path + (path.endsWith("//")?"PrivateKey":"/PrivateKey");
}
}
//创建公私钥对
private static void createKeyPair() throws Exception {
//使用RSA算法获得密钥对生成器对象keyPairGenerator
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
//设置密钥长度为1024
keyPairGenerator.initialize(1024);
//生成密钥对
KeyPair keyPair = keyPairGenerator.generateKeyPair();
//获取公钥
Key publicKey = keyPair.getPublic();
//获取私钥
Key privateKey = keyPair.getPrivate();
//保存公钥对象和私钥对象为持久化文件
ObjectOutputStream oos1 = null;
ObjectOutputStream oos2 = null;
try {
oos1 = new ObjectOutputStream(new FileOutputStream(PUBLIC_KEY_FILE));
oos2 = new ObjectOutputStream(
new FileOutputStream(PRIVATE_KEY_FILE));
oos1.writeObject(publicKey);
oos2.writeObject(privateKey);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
oos1.close();
oos2.close();
}
}
//RSA加密
public static String encryptWithRSA(String str) throws Exception {
createKeyPair();
Key publicKey = null;
//读取持久化的公钥对象
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
publicKey = (Key) ois.readObject();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
ois.close();
}
//获取一个加密算法为RSA的加解密器对象cipher。
Cipher cipher = Cipher.getInstance("RSA");
//设置为加密模式,并将公钥给cipher。
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
//获得密文
byte[] secret = cipher.doFinal(str.getBytes());
//进行Base64编码
return new BASE64Encoder().encode(secret);
}
//RSA解密
public static String decryptWithRSA(String secret) throws Exception {
Key privateKey;
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
privateKey = (Key) ois.readObject();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
ois.close();
}
Cipher cipher = Cipher.getInstance("RSA");
//传递私钥,设置为解密模式。
cipher.init(Cipher.DECRYPT_MODE, privateKey);
//解密器解密由Base64解码后的密文,获得明文字节数组
byte[] b = cipher.doFinal(new BASE64Decoder().decodeBuffer(secret));
//转换成字符串
return new String(b);
}
}
public class RSA_Demo {
public static void main(String[] args) throws Exception {
//设置公私钥对存放路径,可选,默认是工程目录
//RSAUtils.setKeyPath(str);
System.out.println("请输入明文:");
Scanner sca = new Scanner(System.in);
String str =sca.nextLine();
System.out.println("============================");
String secret = RSAUtils.encryptWithRSA(str);
System.out.println("经过RSA加密后的密文为:");
System.out.println(secret);
System.out.println("============================");
String original = RSAUtils.decryptWithRSA(secret);
System.out.println("经过RSA解密后的原文为:");
System.out.println(original);
}
}
来源于: