Cryptography Examples

Sharing a Signed Message Example in Java

Prerequisities

keytool -genkeypair -alias alice-key-pair -keyalg RSA -keysize 2048 -sigalg SHA256withRSA \
-keystore alice.p12 -storetype pkcs12 -storepass i-am-alice -keypass i-am-alice \
-dname "CN=CN OU=OU, O=O, L=L, ST=ON, C=CA" -noprompt -validity 36500
keytool -export -keystore alice.p12 -alias alice-key-pair -file alice.cert -storepass i-am-alice
keytool -importcert -file alice.cert -keystore bob.p12 -alias "alice-cert" -storepass i-am-bob -noprompt

Java Application

Directory Layout

.
├── App.java
├── alice.cert
├── alice.p12
└── bob.p12

App.java

import java.io.*;
import java.security.*;
import java.security.cert.Certificate;

import static java.nio.charset.StandardCharsets.UTF_8;

public class App {
    public static void main(String[] args) throws Exception {
        SignedMessage alicesMessage = new Alice().signedMessage();
        Bob bob = new Bob();
        boolean isAuthentic = bob.receive(alicesMessage);
        System.out.println(isAuthentic);
    }
}

class SignedMessage {
    String msg;
    byte[] sign;
}

class Alice {
    SignedMessage signedMessage() throws Exception {
        try (InputStream is = new FileInputStream("alice.p12")) {
            KeyStore keyStore = KeyStore.getInstance("pkcs12");
            keyStore.load(is, "i-am-alice".toCharArray());

            Key privateKey = keyStore.getKey("alice-key-pair", "i-am-alice".toCharArray());

            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign((PrivateKey) privateKey);

            String msg = "My Secret Message";
            signature.update(msg.getBytes(UTF_8));
            byte[] sign = signature.sign();
            
            SignedMessage signedMessage = new SignedMessage();
            signedMessage.msg = msg;
            signedMessage.sign = sign;
            return signedMessage;
        }
    }
}

/**
 * Bob has access to his keystore, where Alice 's certificate is loaded.
 * Bob does not have access to Alice 's keystore, private key or any of her passwords.
 */
class Bob {
    public boolean receive(SignedMessage signedMessage) throws Exception {
        try (InputStream is = new FileInputStream("bob.p12")) {
            KeyStore keyStore = KeyStore.getInstance("pkcs12");
            keyStore.load(is, "i-am-bob".toCharArray());

            Certificate certificate = keyStore.getCertificate("alice-cert");

            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initVerify(certificate);
            signature.update(signedMessage.msg.getBytes(UTF_8));

            return signature.verify(signedMessage.sign);
        }
    }
}

Sample Execution

javac -d target App.java
mv *.p12 ./target/
mv *.cert ./target/
cd target
java App
SignedMessage alicesMessage = new Alice().signedMessage();
alicesMessage.msg = alicesMessage.msg + "-modified";