RSA是一种非对称加密算法,一般采用公钥加密,私钥解密的形式
生成密钥对
首先创建KeyPairGenerator类的对象,用于生成公钥和私钥对// 生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
然后初始化密钥对的长度,最低长度512位,并且长度不能低于明文的长度// 初始化密钥大小为1024位
keyPairGen.initialize(1024);
利用keyPairGen对象生成密钥对,保存在KeyPair类中KeyPair keyPair = keyPairGen.generateKeyPair();
从keyPair类中获取公钥和私钥RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
加密(encrypt)protected static byte[] encrypt(RSAPublicKey publicKey, byte[] srcBytes) {
if (publicKey != null) {
try {
// Cipher负责完成加密或解密工作,基于RSA
Cipher cipher = Cipher.getInstance(ALGORITHM);
// 根据公钥,对Cipher对象进行初始化
cipher.init(Cipher.ENCRYPT_MODE