从文件中写入和读取RSA密钥:java

时间:2014-06-08 09:35:20

标签: 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();
}

读取和取回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;
}

当我运行程序时,我收到以下错误:

algid parse error, not a sequence

无法弄清楚出了什么问题。

0 个答案:

没有答案