Load the original 64 byte ECDSA public key in Java

I have an ECDSA NIST p-256 public key in the original (R, s) format There seems to be no easy way to load it into the implementation Java security. interfaces. In the object of ecpublickey

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

Solution

If we use ecpublickeyspec to do this, the answer will become very difficult So let's do one thing:

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

public static EcpublicKey convertP256Key(byte[] w) throws InvalidKeySpecException {
    byte[] encodedKey = new byte[P256_HEAD.length + w.length];
    System.arraycopy(P256_HEAD,encodedKey,P256_HEAD.length);
    System.arraycopy(w,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 = convertP256Key(w);
System.out.println(key);

I use my mind:

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));
}

come from:

String name = "NIST P-256";
int size = 256;
byte[] head = createHeadForNamedCurve(name,size);
System.out.println(Base64.getEncoder().encodeToString(head));

The idea is to create an x509 encoded key, which ends with a common point w (the byte containing ASN. 1 der encoding of oid of the named curve and structure overhead, ending with byte 04), indicating the uncompressed point) Then we replace the last "random" point w with W and decode it again

Java 7 requires EC 7 function and Java 8 for base 64 encoder / decoder, without additional libraries and things Note that when printing, the public key is actually displayed as a named curve, and other solutions will not be executed

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>