想将明文用rsa密钥加密,密钥保存在byte数组中。
代码如下:
Cipher cipher=Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, ???);
问题是在cipher的第二个参数中,需要填入Key类型的rsa密钥。我的rsa密钥原来是保存在文本文件中的,读出来之后变成了Byte数组类型,请问如何把它转换成Key类型(或者RSAPrivateKey)?
代码如下:
Cipher cipher=Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, ???);
问题是在cipher的第二个参数中,需要填入Key类型的rsa密钥。我的rsa密钥原来是保存在文本文件中的,读出来之后变成了Byte数组类型,请问如何把它转换成Key类型(或者RSAPrivateKey)?
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;
}
PKCS8EncodedKeySpec encodedPrivateKey = new PKCS8EncodedKeySpec(keydata);
key = kf.generatePrivate(encodedPrivateKey);
这2句上面