java - java中从文件中获取私钥

标签 java cryptography private-key

我有带有“key”扩展名的私钥文件。我知道它是由“Admin-PKI”程序生成的。我必须将其读取为java中PrivateKey类型的对象才能将其用于数字签名生成。我尝试打开它在文本编辑器中,但没有“开始私钥”和“结束私钥”等页眉和页脚。我如何知道使用什么算法来生成私钥?我可以在不知道算法的情况下执行此操作吗?

最佳答案

下面的代码加载文件key.pem,您将需要 bouncycaSTLe 库 ( http://bouncycastle.org/ )

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.security.KeyPair;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMReader;

public class LoadKey {

    public static void main(String [] args) throws Exception {
        Security.addProvider(new BouncyCastleProvider());
        KeyPair keyPair = readKeyPair(new File("key.pem"));
    }

    private static KeyPair readKeyPair(File privateKey) throws IOException {
        FileReader fileReader = new FileReader(privateKey);
        PEMReader r = new PEMReader(fileReader);
        try {
            return (KeyPair) r.readObject();
        } catch (IOException ex) {
            throw new IOException("The private key could not be decrypted", ex);
        } finally {
            r.close();
            fileReader.close();
        }
    }
}

编译并运行

javac -cp bcprov-jdk16-146.jar:. LoadKey.java
java -cp bcprov-jdk16-146.jar:. -ea LoadKey

关于java - java中从文件中获取私钥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20418391/

相关文章:

javac junit 给出 "error: package org.junit does not exist"

java - opencv java修改像素值

java - 破解 N 位 RSA 模数

javascript - web crypto api - 如何导出 key 对?

安卓工作室 : Installation failed since APK was not signed

java - 如何使用 Java 获取给定证书文件的私钥

Java Azure 函数卡住 "Executing"

java - BitmapTextureAtlasTextureRegionFactory.createFromAsset 崩溃

encryption - Openssl "data greater than mod len"

c# - 使用 Bouncy CaSTLe 加密和存储私钥+公钥