java读取DER格式的私钥

发布于 2024-12-20 17:22:49 字数 3425 浏览 2 评论 0原文

我有以下代码来读取 PKCS#8 格式的私钥

public void encryptHash(String hashToEncrypt, String pathOfKey, String Algorithm) {
    FileInputStream fis = null;
    byte[] encodedKey = null;
    try {

        File f = new File(pathOfKey);
        encodedKey = new byte[(int)f.length()];

        fis = new FileInputStream(f);
        fis.read(encodedKey);
        fis.close();

        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));

        Signature rsaSigner = Signature.getInstance("SHA1withRSA");
        rsaSigner.initSign(privateKey);

        fis = new FileInputStream(hashToEncrypt);
        BufferedInputStream bis = new BufferedInputStream(fis);
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = bis.read(buffer)) >= 0) {
            try {
                rsaSigner.update(buffer, 0, len);
            } catch (SignatureException ex) {
                Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        bis.close();

        byte[] signature = rsaSigner.sign();

        System.out.println(new String(signature));

    } catch (SignatureException ex) {
        Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeySpecException ex) {
        Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            fis.close();
        } catch (IOException ex) {
            Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

,但出现以下异常。

dic 09, 2011 1:59:59 PM firmaelectronica.DataEncryptor encryptHash
Grave: null
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DER input, Integer tag error
    at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:217)
    at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
    at firmaelectronica.DataEncryptor.encryptHash(DataEncryptor.java:40)
    at firmaelectronica.FirmaElectronica.main(FirmaElectronica.java:39)
Caused by: java.security.InvalidKeyException: IOException : DER input, Integer tag error
    at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:361)
    at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:367)
    at sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(RSAPrivateCrtKeyImpl.java:91)
    at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:75)
    at sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:316)
    at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:213)
    ... 3 more

知道出了什么问题吗?我在 OpenSSL openssl pkcs8 -inform DER -in aaa010101aaa_FIEL.key -out aaa010101aaa_FIEL_key.pem 上尝试过,它有效,但是当我想以 DER 格式读取密钥时,它只是发送该异常。

I have the following code to read a private key in PKCS#8 format

public void encryptHash(String hashToEncrypt, String pathOfKey, String Algorithm) {
    FileInputStream fis = null;
    byte[] encodedKey = null;
    try {

        File f = new File(pathOfKey);
        encodedKey = new byte[(int)f.length()];

        fis = new FileInputStream(f);
        fis.read(encodedKey);
        fis.close();

        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));

        Signature rsaSigner = Signature.getInstance("SHA1withRSA");
        rsaSigner.initSign(privateKey);

        fis = new FileInputStream(hashToEncrypt);
        BufferedInputStream bis = new BufferedInputStream(fis);
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = bis.read(buffer)) >= 0) {
            try {
                rsaSigner.update(buffer, 0, len);
            } catch (SignatureException ex) {
                Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        bis.close();

        byte[] signature = rsaSigner.sign();

        System.out.println(new String(signature));

    } catch (SignatureException ex) {
        Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeySpecException ex) {
        Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            fis.close();
        } catch (IOException ex) {
            Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

But I'm getting the following exception.

dic 09, 2011 1:59:59 PM firmaelectronica.DataEncryptor encryptHash
Grave: null
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DER input, Integer tag error
    at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:217)
    at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
    at firmaelectronica.DataEncryptor.encryptHash(DataEncryptor.java:40)
    at firmaelectronica.FirmaElectronica.main(FirmaElectronica.java:39)
Caused by: java.security.InvalidKeyException: IOException : DER input, Integer tag error
    at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:361)
    at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:367)
    at sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(RSAPrivateCrtKeyImpl.java:91)
    at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:75)
    at sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:316)
    at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:213)
    ... 3 more

any idea what is wrong? I tried this on OpenSSL openssl pkcs8 -inform DER -in aaa010101aaa_FIEL.key -out aaa010101aaa_FIEL_key.pem and it works but when I want to read the key in DER format it just sends that exception.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

森末i 2024-12-27 17:22:50

终于看到了这个线程 Encrypting with RSA private key in Java< /a> 找到了答案。

首先,我必须取消对密钥的保护,如下所示

openssl pkcs8 -inform DER -in myDERPassProtectedPrivate.key -outform PEM -out myPEMPrivate.key

它要求我输入密码,然后我得到了文件 myPEMPrivate.key 完成后,继续删除保护密钥的密码,如下所示

openssl pkcs8 -topk8 -nocrypt -in myPEMPrivate.key -outform DER -out myNotAnyMoreProtectedPrivate.key

有了这个,我现在可以使用上面的代码加载密钥。如果我们想在 java 中拥有受密码保护的密钥,强烈建议使用密钥库。

PS我试图避免使用 openssl pkcs8 -topk8 -nocrypt -inform der -in myDERPassProtectedPrivate.key -outform der -out myDERNoPassProtectedPrivate.key 摆脱保护密钥的密码的两个步骤,但我不这样做不知道为什么我遇到错误 解密密钥时出错 我使用了 WinOpenSSL 也许这就是我收到该错误的原因。

Well finally looking at this thread Encrypting with RSA private key in Java found the answer.

First I had to unprotect the key, as follows

openssl pkcs8 -inform DER -in myDERPassProtectedPrivate.key -outform PEM -out myPEMPrivate.key

it asked me for my password and then I had the file myPEMPrivate.key Once done this proceed to get rid of the password protecting the key like follows

openssl pkcs8 -topk8 -nocrypt -in myPEMPrivate.key -outform DER -out myNotAnyMoreProtectedPrivate.key

with this I'm now able to load the key with the code above. If we want to have a pass-protected key in java it is highly advisable to use a keystore.

P.S. I tried to avoid the 2 steps to get rid of the password protecting the key with openssl pkcs8 -topk8 -nocrypt -inform der -in myDERPassProtectedPrivate.key -outform der -out myDERNoPassProtectedPrivate.key but I don't know why I had the error Error decrypting key I used WinOpenSSL maybe that's the reason why I got that error.

放血 2024-12-27 17:22:50

使用这个:

-passin arg

<块引用>

输入文件密码来源。有关 arg 格式的更多信息,请参阅 openssl(1) 中的 PASS PHRASE ARGUMENTS 部分。

命令应如下所示:

openssl pkcs8 -inform DER -in myDERPassProtectedPrivate.key -outform PEM -passin pass:12345678a -out myPEMPrivate.key

OpenSSL 网站 https://www.openssl.org/docs/apps/pkcs8.html

Use this:

-passin arg

the input file password source. For more information about the format of arg see the PASS PHRASE ARGUMENTS section in openssl(1).

Command should look like:

openssl pkcs8 -inform DER -in myDERPassProtectedPrivate.key -outform PEM -passin pass:12345678a -out myPEMPrivate.key

OpenSSL website https://www.openssl.org/docs/apps/pkcs8.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文