Java Crypto Libraries

Java Crypto Libraries

...

Cryptography in Java

    JCA, Bouncy Castle and Web3j:Hashes, ECC and ECDSA

JCA, Bouncy Castle and Web3j

    Cryptography in Java is based on the Java Cryptography Architecture (JCA)
      Typical Java style: lot of boilerplate code
    Bouncy Castle is the leading Java cryptography library
    Web3j – a simplified library for Ethereum and secp256k1

ECDSA in Java: Install the Crypto Libraries

    This Maven dependency will install the following libraries:
      org.web3j.crypto– Ethereum style secp256k1 EC cryptography
      org.bouncycastle– BouncyCastle crypto provider for Java
1
<dependency>
2
<groupId>org.web3j</groupId>
3
<artifactId>crypto</artifactId>
4
<version>3.3.1</version>
5
</dependency>
Copied!

ECDSA in Java: Initialize the Application

1
import org.bouncycastle.util.encoders.Hex;
2
import org.web3j.crypto.*;
3
import java.math.BigInteger;
Copied!

ECDSA in Java: Generate / Load Keys

1
// Generate random private key
2
// BigInteger privKey = Keys.createEcKeyPair().getPrivateKey();
3
4
BigInteger privKey = new BigInteger(
5
"97ddae0f3a25b92268175400149d65d6887b9cefaf28ea2c078e05cdc15a3c0a", 16);
6
BigInteger pubKey = Sign.publicKeyFromPrivate(privKey);
7
ECKeyPair keyPair = new ECKeyPair(privKey, pubKey);
8
9
System.out.println("Private key: " + privKey.toString(16));
10
System.out.println("Public key: " + pubKey.toString(16));
11
System.out.println("Public key (compressed): " +
12
compressPubKey(pubKey));
Copied!

ECDSA in Java: Sign Message

1
String msg = "Message for signing";
2
byte[] msgHash = Hash.sha3(msg.getBytes());
3
Sign.SignatureData signature =
4
Sign.signMessage(msgHash, keyPair, false);
5
6
System.out.println("Msg: " + msg);
7
System.out.println("Msg hash: " + Hex.toHexString(msgHash));
8
System.out.printf(
9
"Signature: [v = %d, r = %s, s = %s]\n",
10
signature.getV() - 27,
11
Hex.toHexString(signature.getR()),
12
Hex.toHexString(signature.getS()));
Copied!

ECDSA in Java: Verify Signature

1
BigInteger pubKeyRecovered =
2
Sign.signedMessageToKey(msg.getBytes(), signature);
3
System.out.println("Recovered public key: " +
4
pubKeyRecovered.toString(16));
5
6
boolean validSig = pubKey.equals(pubKeyRecovered);
7
System.out.println("Signature valid? " + validSig);
Copied!
Last modified 6d ago