Converting byte array to publickey ECDSA

10.3k views Asked by At

I need to use ECDSA algorithm to sign a message and send to receiver in java. Then, receiver should verify sender's signature.

So, for this, receiver has sender's public key but in byte array format after converting java.security.PublicKey to byte array by the command bellow:

byte[] byteArrayPublicKey = publickey.getEncoded();

The format of public key in ECDSA algorithm (before converting it to byte array) is as follow:

Public Key:

X: 8a83c389e7bb817c17bf2db4ed71055f18342b630221b2a3a1ca752502dc2e21

Y: 3eaf48c9ab1700fe0966a0cde196b85af66bb8f0bacef711c9dca2368f9d8470

But, the problem is to convert this byte array to usable format to verify the signature that is java.security.PublicKey by receiver.

In general, is there any solution to verify the signature without converting it to byte array? In the other word, the problem is to verify the signature by sender's public key, using any method.

1

There are 1 answers

6
mazhar islam On BEST ANSWER

But, the problem is to convert this byte array to usable format to verify the signature that is java.security.PublicKey by receiver.

You can solve the problem like this way:

public static ECPublicKey genEcPubKey() throws Exception {
    KeyFactory factory = KeyFactory.getInstance("ECDSA", "BC");
    java.security.PublicKey ecPublicKey = (ECPublicKey) factory
            .generatePublic(new X509EncodedKeySpec(Helper
                    .toByte(ecRemotePubKey))); // Helper.toByte(ecRemotePubKey)) is java.security.PublicKey#getEncoded()
    return (ECPublicKey) ecPublicKey;
}

Note that, you need BouncyCastle provider to do that.

But question remains, how you generate the private key?

public KeyPair ecKeyPairGenerator(String curveName) throws Exception {
    KeyPair keyPair;
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
            "ECDSA", "BC");
    ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec(
            curveName);
    keyPairGenerator.initialize(ecGenParameterSpec, new SecureRandom());
    keyPair = keyPairGenerator.generateKeyPair();
    java.security.PublicKey ecPublicKey = (ECPublicKey) keyPair.getPublic();
    System.out.println("JAVA EC PublicKey: "
            + Helper.toHex(ecPublicKey.getEncoded()));

    // write private key into a file. Just for testing purpose
    FileOutputStream fileOutputStream = new FileOutputStream(
            "ECPrivateKey.key");
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(
            fileOutputStream);
    objectOutputStream.writeObject(keyPair.getPrivate());
    objectOutputStream.close();
    return keyPair;
}

I have the full running code for EC sign/verify in github. You can take a look for better understanding.