Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create EC private key from hex string

I am wondering if this is a correct way to create PrivateKey object in Java from HEX string from this website: https://kjur.github.io/jsrsasign/sample/sample-ecdsa.html

Create a BigInteger from a HEX String:

BigInteger priv = new BigInteger(privateKeyFromSite, 16);

And pass to this method:

import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;

import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.jce.spec.ECPrivateKeySpec;


public static PrivateKey getPrivateKeyFromECBigIntAndCurve(BigInteger s, String curveName) {

    ECParameterSpec ecParameterSpec = ECNamedCurveTable.getParameterSpec(curveName);

    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(s, ecParameterSpec);
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(EC);
        return keyFactory.generatePrivate(privateKeySpec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        e.printStackTrace();
        return null;
    }
}
like image 638
serg.nechaev Avatar asked Aug 24 '18 12:08

serg.nechaev


1 Answers

Yes it's correct, an EC private key is just a number. If you print out your PrivateKey, you'll see the X and Y coordinates of the corresponding public key.

For example, let's say the following key pair was generated (secp256r1):

  • EC Private Key:
    1b9cdf53588f99cea61c6482c4549b0316bafde19f76851940d71babaec5e569

  • EC Public Key:
    0458ff2cd70c9a0897eb90a7c43d6a656bd76bb8089d52c259db6d9a45bfb37eb9882521c3b1e20a8bae181233b939174ee95e12a47bf62f41a62f1a20381a6f03

We plug the private key bytes into your function:

BigInteger priv = new BigInteger("1b9cdf53588f99cea61c6482c4549b0316bafde19f76851940d71babaec5e569", 16);
PrivateKey privateKey = getPrivateKeyFromECBigIntAndCurve(priv, "secp256r1");
System.out.println(privateKey);

And print it:

EC Private Key [91:05:8a:28:94:f9:5c:cb:c4:34:b8:69:e4:39:d4:57:59:c7:51:35]
        X: 58ff2cd70c9a0897eb90a7c43d6a656bd76bb8089d52c259db6d9a45bfb37eb9
        Y: 882521c3b1e20a8bae181233b939174ee95e12a47bf62f41a62f1a20381a6f03

As you can see, if you concatenate 04 + X + Y, you'll get the original public key, (04 is the uncompressed EC point tag).

like image 160
rustyx Avatar answered Nov 10 '22 01:11

rustyx