|
| 1 | +package sample; |
| 2 | + |
| 3 | +import java.io.OutputStream; |
| 4 | +import java.io.FileOutputStream; |
| 5 | +import java.io.InputStream; |
| 6 | +import java.io.FileInputStream; |
| 7 | + |
| 8 | +import java.nio.file.Files; |
| 9 | +import java.nio.file.Paths; |
| 10 | +import java.nio.file.Path; |
| 11 | + |
| 12 | +import java.security.Key; |
| 13 | +import java.security.PrivateKey; |
| 14 | +import java.security.KeyPair; |
| 15 | +import java.security.KeyPairGenerator; |
| 16 | +import java.security.KeyFactory; |
| 17 | +import java.security.Signature; |
| 18 | +import java.security.PublicKey; |
| 19 | + |
| 20 | +import java.security.spec.PKCS8EncodedKeySpec; |
| 21 | +import java.security.spec.X509EncodedKeySpec; |
| 22 | + |
| 23 | +import java.util.Base64; |
| 24 | + |
| 25 | +public class sample4 |
| 26 | +{ |
| 27 | + static private Base64.Encoder encoder = Base64.getEncoder(); |
| 28 | + |
| 29 | + static private void writeBinary(OutputStream out,Key key) |
| 30 | + throws java.io.IOException |
| 31 | + { |
| 32 | + out.write(key.getEncoded()); |
| 33 | + } |
| 34 | + |
| 35 | + static public void main(String[] args) throws Exception |
| 36 | + { |
| 37 | + if ( args.length != 4 ) { |
| 38 | + System.err.println("verify digital signature."); |
| 39 | + System.err.println("usage: java algo pubKeyFile dataFile signFile"); |
| 40 | + System.exit(1); |
| 41 | + } |
| 42 | + |
| 43 | + int index = 0; |
| 44 | + String algo = args[index]; index++; |
| 45 | + String keyFile = args[index]; index++; |
| 46 | + String dataFile = args[index]; index++; |
| 47 | + String signFile = args[index]; index++; |
| 48 | + |
| 49 | + /* Read the public key bytes */ |
| 50 | + Path path = Paths.get(keyFile); |
| 51 | + byte[] bytes = Files.readAllBytes(path); |
| 52 | + |
| 53 | + /* Generate public key. */ |
| 54 | + X509EncodedKeySpec ks = new X509EncodedKeySpec(bytes); |
| 55 | + KeyFactory kf = KeyFactory.getInstance("RSA"); |
| 56 | + PublicKey pub = kf.generatePublic(ks); |
| 57 | + |
| 58 | + Signature sign = Signature.getInstance("SHA256withRSA"); |
| 59 | + sign.initVerify(pub); |
| 60 | + |
| 61 | + InputStream in = null; |
| 62 | + try { |
| 63 | + in = new FileInputStream(dataFile); |
| 64 | + byte[] buf = new byte[2048]; |
| 65 | + int len; |
| 66 | + while ((len = in.read(buf)) != -1) { |
| 67 | + sign.update(buf, 0, len); |
| 68 | + } |
| 69 | + } finally { |
| 70 | + if ( in != null ) in.close(); |
| 71 | + } |
| 72 | + |
| 73 | + /* Read the signature bytes */ |
| 74 | + path = Paths.get(signFile); |
| 75 | + bytes = Files.readAllBytes(path); |
| 76 | + System.out.println(dataFile + ": Signature " + |
| 77 | + (sign.verify(bytes) ? "OK" : "Not OK")); |
| 78 | + } |
| 79 | +} |
0 commit comments