如何将byte[]类型的数据赋值给RSAPrivateKey?

clovexmu 2006-11-05 07:04:10
想将明文用rsa密钥加密,密钥保存在byte数组中。
代码如下:
Cipher cipher=Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, ???);
问题是在cipher的第二个参数中,需要填入Key类型的rsa密钥。我的rsa密钥原来是保存在文本文件中的,读出来之后变成了Byte数组类型,请问如何把它转换成Key类型(或者RSAPrivateKey)?
...全文
455 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
hbwhwang 2006-11-08
  • 打赏
  • 举报
回复
关键就在:
PKCS8EncodedKeySpec encodedPrivateKey = new PKCS8EncodedKeySpec(keydata);
key = kf.generatePrivate(encodedPrivateKey);
这2句上面
hbwhwang 2006-11-08
  • 打赏
  • 举报
回复
我以前做的,给你参考一下:
private Key getKeyFromFile(String filename, int type) throws FileNotFoundException {
FileInputStream fis = null;
fis = new FileInputStream(filename);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int b;
try {
while ((b = fis.read()) != -1) {
baos.write(b);
}
} catch (IOException e) {
e.printStackTrace();
}
byte[] keydata = baos.toByteArray();

Key key = null;
try {
KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
switch (type) {
case PRIVATE:
PKCS8EncodedKeySpec encodedPrivateKey = new PKCS8EncodedKeySpec(keydata);
key = kf.generatePrivate(encodedPrivateKey);
return key;
case PUBLIC:
X509EncodedKeySpec encodedPublicKey = new X509EncodedKeySpec(keydata);
key = kf.generatePublic(encodedPublicKey);
return key;
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}

return key;
}

clovexmu 2006-11-08
  • 打赏
  • 举报
回复
up
clovexmu 2006-11-05
  • 打赏
  • 举报
回复
RSAPrivateKey不接受以byte[]为参数的构造函数。
rumlee 2006-11-05
  • 打赏
  • 举报
回复
你看看RSAPrivateKey这个类有哪些构造方法啊,如果能够直接接受byte[]作为参数,那不就很简单了,如果不能够直接接受,看它构造方法能够接受什么,想办法转换一下。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧