需求
利用RSA
密钥对对字符串加解密。
代码
package test;
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class Encrypt {
public static void main(String[] agrs) throws Exception{
String text = "hello world";
byte[] textBytes = text.getBytes();
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.genKeyPair();
byte[] publicKey = keyPair.getPublic().getEncoded();
byte[] privateKey = keyPair.getPrivate().getEncoded();
byte[] encryptContent = encrypt(textBytes, publicKey);
byte[] decryptContent = decypt(encryptContent, privateKey);
String content = new String(decryptContent);
System.out.println("解密的字符串为:" + content);
}
/*
* 加密
* */
public static byte[] encrypt(byte[] textBytes, byte[] publicKeyBytes) throws Exception{
//公钥
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyBytes);
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
//Cipher加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptBytes = cipher.doFinal(textBytes);
return encryptBytes;
}
/*
* 解密
* */
public static byte[] decypt(byte[] encryptBytes, byte[] privateKeyBytes) throws Exception{
//私钥
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
//Cipher解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptBytes = cipher.doFinal(encryptBytes);
return decryptBytes;
}
}
运行结果为:
解密的字符串为:hello world
说明
用Cipher
对字符串进行加解密。
先实例化Cipher,然后初始化,初始化有两个参数,第一个为模式,实际上是个数字。第二个参数为公钥或者私钥。
最后只需要执行doFinal(byte[] )
就可以加解密了。
如果是文件,亦可以先通过将文件读取到流,转化为byte[]
在加解密。