首页 / JAVA / 如何在java中用RSA密钥加密解密
如何在java中用RSA密钥加密解密
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何在java中用RSA密钥加密解密,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2473字,纯文字阅读大概需要4分钟。
内容图文
![如何在java中用RSA密钥加密解密](/upload/InfoBanner/zyjiaocheng/706/1fdfdd9ff57249719731340ba6ad0d82.jpg)
我需要用openssl生成的rsaprivatekey.pem和rsapublickey.pem密钥替换从Unix到java代码的加密和解密步骤
我生成了密钥
openssl genrsa -out /tmp/rsaprivatekey.pem -des3 1024
openssl rsa -in /tmp/rsaprivatekey.pem -pubout -out /tmp/rsapublickey.pem
我在unix中使用键(我需要在java中执行)
echo "Text to encript"| openssl rsautl -encrypt -inkey /tmp/rsapublickey.pem -pubin -out out.enc
openssl rsautl -decrypt -inkey /tmp/rsaprivatekey.pem -in out.enc
这是我尝试这样做的
public static void main(String[] args) {
Base64 base64 = new Base64();
String TextStream = "this is the input text";
byte[] Cipher;
System.out.println("input:\n" + TextStream);
Cipher = encrypt(TextStream);
System.out.println("cipher:\n" + base64.encodeAsString(Cipher));
System.out.println("decrypt:\n" + decrypt(Cipher));
}
private static byte[] encrypt(String Buffer) {
try {
Cipher rsa;
rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.ENCRYPT_MODE, getPrivateKey(PRIVATE_PATH));
return rsa.doFinal(Buffer.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String decrypt(byte[] buffer) {
try {
Cipher rsa;
rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.DECRYPT_MODE, getPrivateKey(PUBLIC_PATH));
byte[] utf8 = rsa.doFinal(buffer);
return new String(utf8, "UTF8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static PrivateKey getPrivateKey(String filename) throws Exception {
File f = new File(filename);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) f.length()];
dis.readFully(keyBytes);
dis.close();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
public static PublicKey getPublicKey(String filename) throws Exception {
File f = new File(filename);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) f.length()];
dis.readFully(keyBytes);
dis.close();
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
但它不起作用,PKCS8EncodedKeySpec / X509EncodedKeySpec不正确…但我不知道放什么
解决方法:
我认为您在阅读PEM文件时遇到问题. JPA不直接支持PEM格式.您有两个选项,要么将它们转换为DER编码文件(您可以使用openSSL执行此操作),也可以使用bouncy castle API来读取(或写入)PEM文件.您感兴趣的课程称为PEMReader(也可能是PEMWriter).在bouncycastle网站上的Here is the Javadoc.
内容总结
以上是互联网集市为您收集整理的如何在java中用RSA密钥加密解密全部内容,希望文章能够帮你解决如何在java中用RSA密钥加密解密所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。