将字符串私钥转换为PrivateKey类型

时间:2019-04-14 13:44:47

标签: java rsa private-key

我下面有字符串格式的RSA私钥。

String privatekey = -----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAqAKCCMKqboM8ywSuNvmf2zuT0e2elxntdEe5msv22jzT89Xa
1Q/V4CeQdZruIw8eTAMa67Dej+3cPdSrjdDnfxcb9L14U9oFPgOyvxVwb+/S8jqm
F9o7Gvm85X972C8izh+K4ndpPtztxkZ0g7cu7RqrCCBzw5SUfi3pgIpprdiKlVDP
4lF7CTwzRH+oi+BxwOABEiuKOJtjOXX1WJhV6ukEy8K6Fq/QOyt/7vgxkm8I8HMo
SMq2UZNswn5/9SqMWuaTBaQbjZ2f77zaq5X/jOiCThTxFNPjPnzhKhG8ekaqIUpB
y9VuICFgdtVQimnlDykrdJWyeOFWPjYl5vehkwIDAQABAoIBAQCN2Ig2ozvHUA/s
i8gWbAyVyKgVrhueEOrUqJXAZoHEYWTFUgGOru7wcBbb4/E4MlRu8pQw90QAml6+
6SXp9rzsJPOaXrkPelvArtij0ZL7PqyHjBKcwsfyD3V3AXnq3GjzQ9g7OXvm8hnh
s6w9ZFQ/JKvPka6LKo9wNI0W1EVC2tggN0Jt6YJFU7trb5TtiQm/B4NKpflZ7PsC
1WOttz0q+VSzF/p04+33OLXugF1crgMr9KCg0uSPi5zCcM+3RVSWDrcZoh+yV4pK
+g5XKKw/BQD9vrUzsLMDjupp4Is0sSEXwMQeRbUZRnUOWVO7E7jrawzhGXV6v4ZT
3PoxB7CxAoGBANkK9ITnfIr1AlF8S1Ok12AlHLYvCPG4TVBw4WNVUX1y3wBXpOmx
t5S2wGpTmyf3LBpw/0m+5EzoghjSb2QnIRFveAxuhxPCPNqxvyzm2D7ycaGJX41y
RfsxvWVQpzvCVH4yV+tkH107ivR2uFDtbDjqlydPyIxmA1Frlm87CODpAoGBAMYq
gLO5EEKxs1MlCzZkuqsEAq+kZVX7y3Kw9rzCJtRQKfYu0IlNFudPg3KpqcbQsrfR
1Psl6iTLXtLe+92NXDOcc9rfj9crmAKmZA1llXOwxe4FOrLWbxk+i6V3qJ2qrf+I
Dwc9+Xrc6ydcDtTHAi3JeIReEbDMvFc6JRiyjwEbAoGAeH68gYyCeCLNxq9aonVB
nP79kadLL+dCBQamGp+jPiIn6+i8hYFEiitrZ5xC500yDvvsvuRbmtb6Yw1xCgkv
Mp7P5xb1puKPJlrH6AXAyDGRJD0/7ych8vMKUtUUAvlAL0+DwAs13mzQGChQ65zk
GDUk9Y41qLx52xn/yoDbzQECgYEAksM9qF1iPpLPBcAEqtc1LJz+xEiTyHeAOMP5
KNj92vY37ZzEUzulv9AywQQIujcsdVlRTGPLIk8APlpo3K/p3kt7vlkedbRSk3vZ
09YtNo5wOJTk4ThQ9bhNwlF5rrOOxBZnUuzCTQ06l17lmQ5+fZydxiLJJVCsGEn2
2XC82osCgYB9maZnLrSZ3Xq4X256/H+Et8TcgqOZGbLuGkNzheheP/E5LcUhQqbP
oJRB24XoX+yw+Do5q2pHHgbrrHwcdg3Xfw9sb5P2JNbtG57mO7QEilIHfUQzQl/U
XSKgJJZ/9bTPlbZmp9ChM9izUv8DI5vjhDputhlEHP4BpHBN03a85Q==
-----END RSA PRIVATE KEY-----

我正在尝试使用下面的代码片段将其转换为PrivateKey类型-

  public PrivateKey generatePrivateKey(String privateKey) throws Exception{

        privateKey = privateKey.replace("-----BEGIN RSA PRIVATE KEY-----", "");
        privateKey = privateKey.replace("-----END RSA PRIVATE KEY-----", "");
        privateKey = privateKey.replaceAll("\\s+", "");
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey.getBytes());
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(keySpec);
    }

我遇到错误-

这让我在generatePrivate方法上出错了。

Execution exception[[InvalidKeySpecException: java.security.InvalidKeyException: invalid key format]]

尝试使用此处的答案Java: Convert DKIM private key from RSA to DER for JavaMail

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

public class pkcs1ToPkcs8 {

    public static void main(String[] args) throws IOException {

        String pkcs1 = //privatekey provided above

            // b64 now contains the base64 "body" of the PEM-PKCS#1 file
            byte[] oldder = Base64.getDecoder().decode(pkcs1.getBytes());

            // concatenate the mostly-fixed prefix plus the PKCS#1 data 
            final byte[] prefix = {0x30,(byte)0x82,0,0, 2,1,0, // SEQUENCE(lenTBD) and version INTEGER 
                    0x30,0x0d, 6,9,0x2a,(byte)0x86,0x48,(byte)0x86,(byte)0xf7,0x0d,1,1,1, 5,0, // AlgID for rsaEncryption,NULL
                    4,(byte)0x82,0,0 }; // OCTETSTRING(lenTBD) 
            byte[] newder = new byte [prefix.length + oldder.length];
            System.arraycopy (prefix,0, newder,0, prefix.length);
            System.arraycopy (oldder,0, newder,prefix.length, oldder.length);
            // and patch the (variable) lengths to be correct
            int len = oldder.length, loc = prefix.length-2; 
            newder[loc] = (byte)(len>>8); newder[loc+1] = (byte)len;
            len = newder.length-4; loc = 2;
            newder[loc] = (byte)(len>>8); newder[loc+1] = (byte)len;

            FileOutputStream fo = new FileOutputStream ("pkcs8_file");
            fo.write (newder); fo.close();
            System.out.println ("converted length " + newder.length);

    }

}

1 个答案:

答案 0 :(得分:1)

GLM_df$Day_Night <- ifelse(findInterval(GLM_df$hour, c(6, 18), rightmost.closed=TRUE) == 1L, 'Day', 'Night') 表示您的密钥是pkcs#1格式,而不是pkcs#8。 Java本身不支持读取pkcs#1密钥。您需要使用bouncycastle库(请参见Read RSA private key of format PKCS1 in JAVA)或使用任何这些解决方案Getting RSA private key from PEM BASE64 Encoded private key file


如果您的密钥是pkcs#8,它将具有标题BEGIN RSA PRIVATE KEY。在这种情况下,为了使代码正常工作,您还需要解码base64中的关键内容


要将pkcs#1密钥转换为pkcs#8,可以使用openssl

BEGIN PRIVATE KEY