-
-
Notifications
You must be signed in to change notification settings - Fork 642
Tutorial for interoperability with java signing
Kenji Urushima edited this page Sep 9, 2017
·
6 revisions
TOP | DOWNLOADS | TUTORIALS | API REFERENCE | DEMOS
This tutorial shows you how to verify a Java generated signature by jsrsasign.
Here is a sample Java code which loads PKCS#8 DER binary RSA private key, sign a string "aaa" by the private key with "SHA1withRSA" algorithm, then write a resulted signature value to a file as binary.
/*
* TSign.java
*/
import java.lang.*;
import java.io.*;
import java.security.*;
import java.security.spec.*;
public class TSign {
public TSign() {
try {
byte[] prvKeyBytes = loadBytes("z1.prv.p8p.der"); // PKCS#8 private key
KeyFactory kf = KeyFactory.getInstance("RSA");
KeySpec keySpec = new PKCS8EncodedKeySpec(prvKeyBytes);
PrivateKey prvKey = kf.generatePrivate(keySpec);
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initSign(prvKey);
sig.update("aaa".getBytes());
byte[] sigBytes = sig.sign();
System.out.println(sigBytes);
saveBytes(sigBytes, "TSign.sig.bin");
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static byte[] loadBytes(String fileName) {
try {
FileInputStream fis = new FileInputStream(fileName);
byte[] data = new byte[fis.available()];
fis.read(data);
fis.close();
return data;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
private static void saveBytes(byte[] data, String fileName) {
try {
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(data);
fos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
TSign t = new TSign();
}
}
Here is another sample jsrsasign JavaScript program to verify signature. This script loads PKCS#8 PEM RSA public key and a binary signature value file, then verifies the signature value.
#!/usr/bin/env node
var rs = require("jsrsasign");
var rsu = require("jsrsasign-util");
var hSig = rsu.readFileHexByBin("TSign.sig.bin");
var pubpem = rsu.readFile("z1.pub.p8.pem");
var pubkey = rs.KEYUTIL.getKey(pubpem);
var sig = new rs.KJUR.crypto.Signature({alg: "SHA1withRSA"});
sig.init(pubkey);
sig.updateString("aaa");
var result = sig.verify(hSig);
console.log(result);
You'll see how easy to verify a signature with jsrsasign. KEYUTIL.getKey method provides very easy way to load a key. This program can load PKCS#8 public key as well as a PKCS#5 public key or a X.509 certificate by the same code.