Search code examples
javaiosswiftcryptographyelliptic-curve

Importing ANSI X9.63 formatted key pair in Java


I have generated a key pair on iOS and created a data representation using the following code:

var publicKey, privateKey: SecKey?
let keyattribute = [
    kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
    kSecAttrKeySizeInBits as String : 256
    ] as CFDictionary
SecKeyGeneratePair(keyattribute, &publicKey, &privateKey)

var error: Unmanaged<CFError>?
let pubkeyRep = SecKeyCopyExternalRepresentation(publicKey!, &error) as Data?
let prikeyRep = SecKeyCopyExternalRepresentation(privateKey!, &error) as Data?

According to the documentation from Apple, the SecKeyCopyExternalRepresentation function encodes these keys using uncompressed ANSI X9.63 format

I want to transform these byte arrays into PublicKey and PrivateKey objects in Java.

A few examples that I've found here (using SunJCE) and here (using BouncyCastle) work for the public key, but they don't describe a way to import the private key.


Solution

  • Notice in the Apple documentation how the first 65-bytes are the uncompressed public key (04 || X || Y) concatenated with the private scalar (|| K). Take these bytes off and you can create the private key. I hope this helps somebody.

    /*
     *  For an elliptic curve private key, the output is formatted as the public key
     * concatenated with the big endian encoding of the secret scalar, or 04 || X || Y || K.
     */
    private PrivateKey createECPrivateKey(byte[] rawBytes) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidParameterSpecException {
        KeyFactory kf = KeyFactory.getInstance("EC");
        BigInteger s = new BigInteger(Arrays.copyOfRange(rawBytes, 65, rawBytes.length));
        return kf.generatePrivate(new ECPrivateKeySpec(s, ecParameterSpecForCurve("secp256r1")));
    }