Signature and Authentication Example (Java)
Sample source for signature
Data to be signed (character string (42 bytes) that combines "transaction date and time" (14 bytes), "terminal identification number" (13 bytes), "terminal processing serial number" (15 bytes)) String message = "20171201091011A004012345678012345678901234";
Reading the private key file Security.addProvider(new BouncyCastleProvider());
Generate a private key target
PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(privateKeyByte);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8);
Sign with the data to be signed and the private key target
Signature signer = Signature.getInstance("SHA256withRSA");
signer.initSign(rsaPrivateKey);
signer.update(message.getBytes("UTF-8"));
byte[] signByte = signer.sign();
Convert to hexadecimal format based on the generated signature bytes
Hex.encodeHexString(signByte);
↓
7154172627db05f2eb6c8d0f522bd6d1ae0551899944e5a06170abd40e86d49a9204d29e1b251898fc47c633236168aafccf07d6458179f2cceb606dc4c84a3f7f9767fc4b00d3c43feabbc11ef750ca6d85bd7084e74b6c9bdd5bc2f497dae392b9f833a3e52133df74213770da74d9e2a9b08cbe2cf50d5bf1fbcdc00f4bab59ea885aeaaeb8e7a400491ba87c6121c4273a9daf723b89df0e6c4d62823a97db89e6eadea6800a0b692d6d4c19a343b0d762d4dcfd63ce7f41b291619ce2fda299533268d795188cb0cdfbd1a3f1e13f5399cfd52087396cf1a20361629495507569da9472602c985f3d90d35e4838cb9228a52ed211635faa55c94ba0dfbf
Read public key file
PemReader pemPubReader = new PemReader(new FileReader("./file/public-key.pem"));
PemObject objPub = pemPubReader.readPemObject();
byte[] publicKeyByte = objPub.getContent();
Generate a public key target
X509EncodedKeySpec x509 = new X509EncodedKeySpec(encodedByte);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyFactory.generatePublic(x509);
Authenticate with public key target
Signature verifier = Signature.getInstance("SHA256withRSA");
verifier.initVerify(rsaPublicKey);
verifier.update(message.getBytes("UTF-8"));
byte [] messageByte = Hex.decodeHex (Signed message above (hexadecimal format));
boolean result = verifier.verify(messageByte);
Recommended Posts