简体   繁体   中英

Issue in generating private key

Private key generation

          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;
}

I am using it here

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

but its showing error

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

I am passing a (.p12) file in getStoredPrivateKey(String filePath) function.

why its giving error?

P12 is is keystore type where multiple keys and certificates can be stored and a password can be used to protect them. You can search about P12 (PKCS12) on Internet. Your file is P12 file, so most likely it is PKCS12 format file.

To get private key from P12 file use below code. You need below things before calling this code.

filePath . String path (absolute) of P12 file.

filePassword . It is a char[]. Represents password of p12 file.

keyPassword . It is a char[]. Represents password for private key. Most likely it is same as filePassword.

alias . A String. Represents by which alias a private key stored in P12 archive/keystore.

To check what is the alias of your private key you can use below command

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

It will ask for password then print multiple lines. Look for

Entry Type: PrivatKeyEntry

There you will find the alias.

Initialize these variables and then use below code to get private key. You can also get Certificates/Public key associate with this key. Look for API of PrivateKeyEntry

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM