解密加密的私钥:数据不是对象ID

时间:2019-03-25 08:39:29

标签: java encryption private-key

我尝试解密像这样的加密私钥字符串

-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIFHDBO...
-----END ENCRYPTED PRIVATE KEY-----

我也移走了头和脚。但这引发了异常:

Exception in thread "main" java.io.IOException: ObjectIdentifier() -- data isn't an object ID (tag = 48)
    at sun.security.util.ObjectIdentifier.<init>(ObjectIdentifier.java:257)
    at sun.security.util.DerInputStream.getOID(DerInputStream.java:314)
    at com.sun.crypto.provider.PBES2Parameters.engineInit(PBES2Parameters.java:267)
    at java.security.AlgorithmParameters.init(AlgorithmParameters.java:293)
    at sun.security.x509.AlgorithmId.decodeParams(AlgorithmId.java:132)
    at sun.security.x509.AlgorithmId.<init>(AlgorithmId.java:114)
    at sun.security.x509.AlgorithmId.parse(AlgorithmId.java:372)
    at javax.crypto.EncryptedPrivateKeyInfo.<init>(EncryptedPrivateKeyInfo.java:95)
    at com.cargosmart.mci3.as2.process.as2control.KeystoreController.decryptKey(KeystoreController.java:162)
    at com.cargosmart.mci3.as2.process.as2control.KeystoreController.main(KeystoreController.java:147)

这是代码

import org.bouncycastle.util.encoders.Base64;

String key = "-----BEGIN ENCRYPTED PRIVATE KEY-----MIII-----END ENCRYPTED PRIVATE KEY-----";
key = standardizePem(key);
key = key.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----\n", "").replace("\n-----END ENCRYPTED PRIVATE KEY-----", "");
byte[] b = Base64.decode(key);

// here is the exception line
EncryptedPrivateKeyInfo pkinfo = new EncryptedPrivateKeyInfo(b);

函数standardizePem旨在格式化密钥字符串

public static String standardizePem(String cert) {
        String SEPARATOR = "-----";
        String LINE_SEPERATOR = "\n";
        String temp[] = cert.split(SEPARATOR);
        String certHead = temp[1];
        String certEnd = temp[3];
        String certContent = temp[2];
        String regex = "(.{64})";
        certContent = certContent.replaceAll(regex,"$1\n");
        final String pem = SEPARATOR + certHead + SEPARATOR + LINE_SEPARATOR +  certContent + LINE_SEPARATOR + SEPARATOR + certEnd + SEPARATOR;
        return pem;
    }

有人可以解决吗?

感谢您的帮助。

0 个答案:

没有答案