Skip to content

Instantly share code, notes, and snippets.

@ianibo
Created October 4, 2017 16:00
Show Gist options
  • Save ianibo/7859196ae620e6b63678716e6418fa7c to your computer and use it in GitHub Desktop.
Save ianibo/7859196ae620e6b63678716e6418fa7c to your computer and use it in GitHub Desktop.
Sign and validate some bytes using public and private key strings read from ~/.ssh
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.io.*;
import java.nio.*;
import java.security.*;
import java.security.spec.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import sun.misc.BASE64Encoder;
// https://stackoverflow.com/questions/7224626/how-to-sign-string-with-private-key
PrivateKey priv_key = getPriv('/home/ibbo/.ssh/id_pkcs8_key')
PublicKey pub_key = getPub('/home/ibbo/.ssh/id_pkcs8_key.pub')
byte[] data = "test".getBytes("UTF8");
// Sign the data
Signature sig = Signature.getInstance("SHA1WithRSA");
sig.initSign(priv_key);
sig.update(data);
byte[] signatureBytes = sig.sign();
System.out.println("Singature:" + new BASE64Encoder().encode(signatureBytes));
// Verify the signature
sig.initVerify(pub_key);
sig.update(data);
System.out.println(sig.verify(signatureBytes));
KeyPair getKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
return kpg.genKeyPair();
}
// Load a private key from the specified file
// Had to convert my openssh key using openssl pkcs8 -topk8 -inform PEM -outform DER -in id_rsa -nocrypt > id_pkcs8_key
PrivateKey getPriv(String filename) throws Exception {
byte[] keyBytes = Files.readAllBytes(Paths.get(filename));
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
// Load public key from file
// Fiddle with openssl rsa -in id_pkcs8_key -pubout -outform DER -out id_pkcs8_key.pub
PublicKey getPub(String filename) throws Exception {
byte[] keyBytes = Files.readAllBytes(Paths.get(filename));
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment