-3

I use this code generate Private and Public certificate:

            Security.addProvider(new BouncyCastleProvider());
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
            keyPairGenerator.initialize(2048, new SecureRandom());

            KeyPair keyPair = keyPairGenerator.generateKeyPair();

I tried to Store Private and public key into DB using direct toString() like this keyPair.getPublic().toString() but I get values into DB:

RSA Private CRT Key [5e:cf:06:fc:ff:52:cd:16:3a:b4:28:42:dc:c2:5b:9c:e3:fc:a8:c1],[56:66:d1:a4]
             modulus: b3b9ae25337bedf971aa2767412eec0f2d7792873e9c500eb0cff747e5f80b182f3f29ed97b28471de8c68346354bb4fdbe8f8f3ba1b09e745e3235ffdd2ff11efe379cca27914a6a6754e6f967f21358c05462bc20426f7f8c4df0f6632673897b17d8a0592b6291c9281dd3e94b0ed9c8f02dc02df9d8ae8dc2688dfadcb2a94840b2b22a4528e1169b79056288b111a70ebebc8e838e17943c0b88b103c27bbaa6c40624babde1e97e86a42e532cb58c0948705b8943a0f203d648828848e20e5d4ea0aaab8b06d804732352c8eae01cc9672e5140e34dc5054d073d8e617b211fa80ccac810045d4def198e587ff0b7ba858dfa11fd3682cdfeb88d360df
     public exponent: 10001

Which is not correct. What is the proper way to get the certificates as a String and store them in DB?

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808
  • `KeyPair` is `Serializable` so you could save it that way – g00se Aug 26 '23 at 15:53
  • 1
    With `keyPair.getPublic().getEncoded()` the public key is returned as DER encoded key in the common X.509/SPKI format (`byte[]`) which can be stored in binary or, if a string is preferred, Base64 encoded. – Topaco Aug 26 '23 at 16:01
  • 1
    Similarly, `keyPair.getPrivate().getEncoded()` returns the private key DER encoded in the popular PKCS#8 format (`byte[]`). Note that keys and certificates are not the same thing. – Topaco Aug 26 '23 at 16:05
  • ok I get `Required type: String, Provided: byte[]` What should be database filed type? Now I use String type. Is it more appropriate to use byte[] filed type? – Peter Penzov Aug 26 '23 at 17:03

0 Answers0