Law*_*nce 5 java encryption rsa
我是密码学的新手。
我想在java中生成RSA密钥并将其写入文件。稍后我想从该文件中读取并取回 RSA 密钥。
密钥生成和写入文件的代码:
public void generate() throws Exception{
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kpair = kpg.genKeyPair();
byte[] publicKeyBytes = kpair.getPublic().getEncoded();
FileOutputStream fos = new FileOutputStream("publicKey");
fos.write(publicKeyBytes);
fos.close();
}
Run Code Online (Sandbox Code Playgroud)
读取和取回 RSA 公钥的代码:
public static Key getKeyFromFile(String fileName) throws Exception{
Key pk = null;
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");
pk = kf.generatePublic(spec);
return pk;
}
Run Code Online (Sandbox Code Playgroud)
当我运行程序时,出现以下错误:
algid parse error, not a sequence
Run Code Online (Sandbox Code Playgroud)
无法弄清楚出了什么问题。
| 归档时间: |
|
| 查看次数: |
7438 次 |
| 最近记录: |