Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading raw 64-byte long ECDSA public key in Java

I have a raw (r,s) format ECDSA NIST P-256 public key. It seems that there is no simple way to load it into an object that implements java.security.interfaces.ECPublicKey.

What is the cleanest way to load a 64 byte public key so that it can be used to check signatures?

like image 712
user1094206 Avatar asked May 25 '15 21:05

user1094206


People also ask

How to encode EC keys in Java?

To save yourself the pain of doing the above, encode your EC key under X.509, which will fully describe the key and make loading it much much easier. In java, with the ECPublicKey, all you need to do is call ECPublicKey.getEncoded () and pass/save the byte array to where you need the key next.

What version of Java do I need to run the EC?

Java 7 is required for the EC functionality and Java 8 for the Base 64 encoder / decoder, no additional libraries-just plain Java. Note that this will actually display the public key as a named curve when printed out, something most other solutions won't do. If you have an up-to-date runtime, this other answer is more clean.

What is ECDSA and how does it work?

Bitcoin uses a digital signature system called ECDSA to control the ownership of bitcoins. In short, a digital signature system allows you to generate your own private / public key pair, and use the private key to generate digital signatures that proves you are the owner of the public key without having to reveal the private key.

How do I get the public key of an EC keyfactory?

// Retrieve EC KeyFactory KeyFactory ECFactory = KeyFactory.getInstance ("EC"); // Generate public key via KeyFactory PublicKey pubKey = ECFactory.generatePublic (new X509EncodedKeySpec (data)); ECPublicKey ECPubKey = (ECPublicKey) pubKey;


2 Answers

Java 7 is required for the EC functionality and Java 8 for the Base 64 encoder / decoder, no additional libraries - just plain Java. Note that this will actually display the public key as a named curve when printed out, something most other solutions won't do. If you have an up-to-date runtime, this other answer is more clean.

This answer is going to be tough if we do this using ECPublicKeySpec. So lets cheat a bit and use X509EncodedKeySpec instead:

private static byte[] P256_HEAD = Base64.getDecoder().decode("MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE");

/**
 * Converts an uncompressed secp256r1 / P-256 public point to the EC public key it is representing.
 * @param w a 64 byte uncompressed EC point consisting of just a 256-bit X and Y
 * @return an <code>ECPublicKey</code> that the point represents 
 */
public static ECPublicKey generateP256PublicKeyFromFlatW(byte[] w) throws InvalidKeySpecException {
    byte[] encodedKey = new byte[P256_HEAD.length + w.length];
    System.arraycopy(P256_HEAD, 0, encodedKey, 0, P256_HEAD.length);
    System.arraycopy(w, 0, encodedKey, P256_HEAD.length, w.length);
    KeyFactory eckf;
    try {
        eckf = KeyFactory.getInstance("EC");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("EC key factory not present in runtime");
    }
    X509EncodedKeySpec ecpks = new X509EncodedKeySpec(encodedKey);
    return (ECPublicKey) eckf.generatePublic(ecpks);
}

Usage:

ECPublicKey key = generateP256PublicKeyFromFlatW(w);
System.out.println(key);

The idea behind this is to create a temporary X509 encoded key, which happily ends with the public point w at the end. The bytes before that contain the ASN.1 DER encoding of the OID of the named curve and structural overhead, ending with byte 04 indicating an uncompressed point. Here is an example what the structure looks like, using value 1 and 2 for the 32-byte X and Y.

The 32-byte X and Y values of the uncompressed point values removed to create the header. This only works because the point is statically sized - it's location at the end is only determined by the size of the curve.

Now all that is required in the function generateP256PublicKeyFromFlatW is to add the received public point w to the header and run it through the decoder implemented for X509EncodedKeySpec.


The above code uses a raw, uncompressed public EC point - just a 32 byte X and Y - without the uncompressed point indicator with value 04. Of course it is easy to support 65 byte compressed points as well:

/**
 * Converts an uncompressed secp256r1 / P-256 public point to the EC public key it is representing.
 * @param w a 64 byte uncompressed EC point starting with <code>04</code>
 * @return an <code>ECPublicKey</code> that the point represents 
 */
public static ECPublicKey generateP256PublicKeyFromUncompressedW(byte[] w) throws InvalidKeySpecException {
    if (w[0] != 0x04) {
        throw new InvalidKeySpecException("w is not an uncompressed key");
    }
    return generateP256PublicKeyFromFlatW(Arrays.copyOfRange(w, 1, w.length));
}

Finally, I generated the constant P256_HEAD head value in base 64 using:

private static byte[] createHeadForNamedCurve(String name, int size)
        throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, IOException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
    ECGenParameterSpec m = new ECGenParameterSpec(name);
    kpg.initialize(m);
    KeyPair kp = kpg.generateKeyPair();
    byte[] encoded = kp.getPublic().getEncoded();
    return Arrays.copyOf(encoded, encoded.length - 2 * (size / Byte.SIZE));
}

called by:

String name = "NIST P-256";
int size = 256;
byte[] head = createHeadForNamedCurve(name, size);
System.out.println(Base64.getEncoder().encodeToString(head));
like image 145
Maarten Bodewes Avatar answered Sep 25 '22 22:09

Maarten Bodewes


What is the cleanest way to load a 64 byte public key so that it can be used to check signatures?

The cleanest I could muster ! Should work with other curves too..

NOTE: Limited to the SunJCE provider or Android API 26+ (there may be more providers with this functionality, I am unaware of them at the moment.

public static ECPublicKey rawToEncodedECPublicKey(String curveName, byte[] rawBytes) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidParameterSpecException {
    KeyFactory kf = KeyFactory.getInstance("EC");
    byte[] x = Arrays.copyOfRange(rawBytes, 0, rawBytes.length/2);
    byte[] y = Arrays.copyOfRange(rawBytes, rawBytes.length/2, rawBytes.length);
    ECPoint w = new ECPoint(new BigInteger(1,x), new BigInteger(1,y));
    return (ECPublicKey) kf.generatePublic(new ECPublicKeySpec(w, ecParameterSpecForCurve(curveName)));
}

public static ECParameterSpec ecParameterSpecForCurve(String curveName) throws NoSuchAlgorithmException, InvalidParameterSpecException {
    AlgorithmParameters params = AlgorithmParameters.getInstance("EC");
    params.init(new ECGenParameterSpec(curveName));
    return params.getParameterSpec(ECParameterSpec.class);
}
like image 33
datKiDfromNY Avatar answered Sep 23 '22 22:09

datKiDfromNY