private static final String ALGORITHM = "RSA";
private static final String PRIVATE_KEY_PATH = "D:\rsa_private.isa";
private static final String PUBLIC_KEY_PATH = "D:\rsa_public.isa";
/**
* 生成公钥和私钥并存储到文件中
* @throws Exception
*/
@Test
public void geneKeyPair() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();//私钥
PublicKey publicKey = keyPair.getPublic();//公钥
byte[] privateKeyBytes = privateKey.getEncoded();//私钥对应的字节数组
byte[] publicKeyBytes = publicKey.getEncoded();//公钥对应的字节数组
Files.write(Paths.get(PRIVATE_KEY_PATH), privateKeyBytes);
Files.write(Paths.get(PUBLIC_KEY_PATH), publicKeyBytes);
}
@Test
public void testEncrypt() throws Exception {
this.encrypt("Hello RSA");
}
/**
* 公钥加密
* @param value
* @return
* @throws Exception
*/
private byte[] encrypt(String value) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
//读取公钥对应的字节数组
byte[] publicKeyCode = Files.readAllBytes(Paths.get(PUBLIC_KEY_PATH));
//构造公钥,存储起来的公钥需要使用X509EncodedKeySpec进行读取
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyCode);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
//根据已有的KeySpec生成对应的公钥
PublicKey publicKey = keyFactory.generatePublic(keySpec);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(value.getBytes());
System.out.println(Base64.getEncoder().encodeToString(result));
return result;
}
/**
* 私钥解密
* @throws Exception
*/
@Test
public void testDecrypt() throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
byte[] privateKeyCode = Files.readAllBytes(Paths.get(PRIVATE_KEY_PATH));
//私钥需要通过PKCS8EncodedKeySpec来读取
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyCode);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
//生成私钥
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
String content = "Java Program";
byte[] input = this.encrypt("Java Program");
byte[] result = cipher.doFinal(input);
Assert.assertTrue(content.equals(new String(result)));
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有