【问题标题】:Issue in generating private key生成私钥的问题
【发布时间】:2016-10-11 03:08:34
【问题描述】:

私钥生成

          public PrivateKey getStoredPrivateKey(String filePath) {
    PrivateKey privateKey = null;
    byte[] keydata = getKeyData(filePath);
    PKCS8EncodedKeySpec encodedPrivateKey = new PKCS8EncodedKeySpec(keydata);
    KeyFactory keyFactory = null;
    try {
        keyFactory = KeyFactory.getInstance("RSA");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    try {
        System.out.println("hello");
        privateKey = keyFactory.generatePrivate(encodedPrivateKey);
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    }
    return privateKey;
}

我在这里使用它

  PrivateKey privateKey = new KryptoUtil().getStoredPrivateKey(privateKeyFilePath);

但显示错误

    hello
    java.security.spec.InvalidKeySpecException:                          
    java.security.InvalidKeyException: IOException : version mismatch: (supported:     00, parsed:     03
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(Unknown Source)

我在 getStoredPrivateKey(String filePath) 函数中传递一个 (.p12) 文件。

为什么会报错?

【问题讨论】:

  • 您确定您的私钥符合规范 PKCS#8。尝试使用其他规范,如 RSAPrivateKeySpec
  • 我怎样才能确定它不是 PKCS#8

标签: java key private-key key-pair


【解决方案1】:

P12 是密钥库类型,可以存储多个密钥和证书,并且可以使用密码来保护它们。您可以在 Internet 上搜索有关 P12 (PKCS12) 的信息。你的文件是P12文件,所以很可能是PKCS12格式的文件。

要从 P12 文件中获取私钥,请使用以下代码。在调用此代码之前,您需要以下内容。

文件路径。 P12文件的字符串路径(绝对)。

文件密码。它是一个字符 []。代表p12文件的密码。

keyPassword。它是一个字符 []。表示私钥的密码。最多 可能与 filePassword 相同。

别名。一个字符串。表示存储在 P12 中的私钥使用哪个别名 存档/密钥库。

要检查您的私钥的别名是什么,您可以使用以下命令

keytool -list -v -keystore <yourfile>.p12 -storetype pkcs12

它会要求输入密码,然后打印多行。寻找

Entry Type: PrivatKeyEntry

在那里你会找到别名。

初始化这些变量,然后使用下面的代码来获取私钥。您还可以获得与此密钥关联的证书/公钥。寻找 PrivateKeyEntry 的 API

KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream(filePath), filePassword);
PrivateKeyEntry keyEntry = (PrivateKeyEntry) ks.getEntry(alias, new KeyStore.PasswordProtection(keyPassword));
PrivateKey key = privateKeyEntry.getPrivateKey();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-06
    • 2022-01-13
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 2013-01-07
    相关资源
    最近更新 更多