Convert java.security.PrivateKey to Chilkat PrivateKey, java.security.cert.Certificate to Chilkat Certificate

Question:

We are facing some problems about private key and x509 cert.
In our case, we already have instance of java.security.PrivateKey and java.security.cert.Certificate
How can we convert these instance to CkPrivateKey and CkCert for using in CkXmlDSignGen?

Private Key Answer:

  1. Google java.security.PrivateKey
  2. Go to reference doc page: https://docs.oracle.com/javase/8/docs/api/java/security/PrivateKey.html
  3. Find way to get the private key in some format.  (Chilkat can load from any format.)  The answer is “getEncoded” — https://docs.oracle.com/javase/8/docs/api/java/security/Key.html#getEncoded–
  4. getEncoded returns a byte array.
  5. Get the byte array as a base64 string:
    String encoded = Base64.getEncoder().encodeToString(privKeyBytes);
  6. Looking at Chilkat’s CkPrivateKey class, we’ll want to load the key using LoadAnyFormat.
  7. LoadAnyFormat accepts a BinData.  Therefore, create a BinData object and load it with the base64 string by calling BinData.AppendEncoded
  8. Call CkPrivateKey.LoadAnyFormat, passing the BinData object and an empty string for the password (because you Java’s getEncoded produced the private key in a non-encrypted format).

 

Certificate Answer:

  1. Google java.security.cert.Certificate
  2. Go to https://docs.oracle.com/javase/8/docs/api/java/security/cert/Certificate.html
  3. Again we have a “getEncoded” function.
  4. getEncoded returns a byte array of —  “for example, X.509 certificates would be encoded as ASN.1 DER”
  5. Get the ASN.1 DER byte array as a base64 string:  String encoded = Base64.getEncoder().encodeToString(certAsnDerBytes);
  6. Create a Chilkat.Cert object (CkCert in Java)
  7. Load it by calling SetFromEncoded (passing the base64 string)