Search code examples
javadigital-signaturekeystorepublic-key-encryptiondigital-certificate

Update/Delete Certificate chain: Cannot assign the key to the given alias


I want to update my previous self-signed certificate with new one eg: chains which is returned (signed CSR) from TEST CA. My default keystore is: Windows-MY

  • Step 1: I have created a private-public key pair, self-signed certifcate and CSR(private key is stored in Windows-MY with self-signed certificate).

  • Step 2: sent CSR to CA.

  • Step 3: CA returns a certificate chain for that public key.

Now I want to replace that self-signed certificate with the CA returned certificate. NB: I have the private key stored in my store.

Key privKey = keyStore.getKey(commonName, keyPass);
System.out.println("invalid private key :" + (privKey == null));

// keyStore.deleteEntry(commonName);
// keyStore.load(null, keyPass);

if (isPrivateKeyAvailable) {
    System.out.println("name:" + commonName + " is updatded");
    keyStore.setKeyEntry(commonName, privKey, keyPass, chains);
} else {
    System.out.println("name:" + commonName + " does not exist");
}

But I am getting these errors:

java.lang.UnsupportedOperationException: Cannot assign the key to the given alias. at sun.security.mscapi.KeyStore.engineSetKeyEntry(KeyStore.java:415) at sun.security.mscapi.KeyStore$MY.engineSetKeyEntry(KeyStore.java:55) at java.security.KeyStore.setKeyEntry(Unknown Source) at keygenerator.KeyInstaller.installCertificateInWindowsStore(KeyInstaller.java:284) at keygenerator.KeyInstaller.doJob(KeyInstaller.java:167) at keygenerator.KeyGeneration.installCertificate(KeyGeneration.java:171) at keygenerator.KeyGeneration.main(KeyGeneration.java:68)


Solution

  • Windows keystore (named Windows-MY from Java) is not directly writable. You need to pack the private key and the certificate chain returned by CA into a PKCS#12 file (.p12) and import it using The Windows import tool.