Search code examples
javaiosrsapublic-keycommoncrypto

Public Key exchange between iOS and Java


I would like to share a public key generated on an iPhone/iPad with an Java based Server or an Android device. On the Java side (Server or Android) I would like to use java.security and libcommonCrypto (the SecKeyRef stuff) on iOS.

I've got everything working except the public key exchange between these two platforms. By using SecItemCopyMatching I can only export the public key into some format not supported by anything else then Apple. With Java I can load public keys as X509 certificate (through java.security.X509EncodedKeySpec) or as module and exponent (through java.security.RSAPublicKeySpec).

Now I need to know how to export a SecKeyRef as X509 certificate or (what I guess is the easier solution) get the module and exponent from it. And I also need the way backwards.

Here is some sample public key loaded from a SecKeyRef and encoded to BASE64:

MIGJAoGBAMYgXP6rvD/Y8F0VQE0HvxpVnnOxXYl5TDlOfW/leyrCLWGWg9Jp+Tl9dYvK/zWgNpoEfFzMVRpUk9UHcIaDWHW3g0BpS2MVC3Vs/0e2eu6S2WMGHpzqcJB51jJRbnqXQ23nVKC2YE520Po3EvFyTr8MlFJqTCJrovgc7fze4RI5AgMBAAE=

Solution

  • The protocol Apples libcommonCrypto is using is described in RFC3347 and is the modulus and public exponent as a ASN.1 sequence.

    An RSA public key should be represented with the ASN.1 type RSAPublicKey:

      RSAPublicKey ::= SEQUENCE {
          modulus           INTEGER,  -- n
          publicExponent    INTEGER   -- e
      }
    

    Quote from RFC3347, Ver. 2.1, A.1.1