2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

javaで署名認証について回目1

Posted at

署名と認証の例(Java)

1.必要なjarファイル:commons-codec-1.11.jar、bcprov-ext-jdk15on-158.jar

2.署名について、サンプルソース

署名対象データ(「取引日時」(14バイト)、「端末識別番号」(13バイト)、「端末処理通番」(15バイト)を結合した文字列(42バイト))
String message = "20171201091011A004012345678012345678901234";

秘密鍵ファイルの読込
Security.addProvider(new BouncyCastleProvider());
※署名と認証を一緒に行うとき、一回だけ実行でいい
PemReader pemPriReader = new PemReader(new FileReader("./file/private-key.pem"));
PemObject objPri = pemPriReader.readPemObject();
byte[] privateKeyByte = objPri.getContent();

秘密鍵の対象を生成する
PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(privateKeyByte);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8);

署名対象データと秘密鍵対象で、署名を行う
Signature signer = Signature.getInstance("SHA256withRSA");
signer.initSign(rsaPrivateKey);
signer.update(message.getBytes("UTF-8"));
byte[] signByte = signer.sign();

生成した署名バイトに基づいて、16進形式に変換する
Hex.encodeHexString(signByte);

7154172627db05f2eb6c8d0f522bd6d1ae0551899944e5a06170abd40e86d49a9204d29e1b251898fc47c633236168aafccf07d6458179f2cceb606dc4c84a3f7f9767fc4b00d3c43feabbc11ef750ca6d85bd7084e74b6c9bdd5bc2f497dae392b9f833a3e52133df74213770da74d9e2a9b08cbe2cf50d5bf1fbcdc00f4bab59ea885aeaaeb8e7a400491ba87c6121c4273a9daf723b89df0e6c4d62823a97db89e6eadea6800a0b692d6d4c19a343b0d762d4dcfd63ce7f41b291619ce2fda299533268d795188cb0cdfbd1a3f1e13f5399cfd52087396cf1a20361629495507569da9472602c985f3d90d35e4838cb9228a52ed211635faa55c94ba0dfbf

3.認証について、サンプルソース

公開鍵ファイルの読込
PemReader pemPubReader = new PemReader(new FileReader("./file/public-key.pem"));
PemObject objPub = pemPubReader.readPemObject();
byte[] publicKeyByte = objPub.getContent();

公開鍵の対象を生成する
X509EncodedKeySpec x509 = new X509EncodedKeySpec(encodedByte);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyFactory.generatePublic(x509);

公開鍵対象で、認証を行う
Signature verifier = Signature.getInstance("SHA256withRSA");
verifier.initVerify(rsaPublicKey);
verifier.update(message.getBytes("UTF-8"));
byte[] messageByte = Hex.decodeHex(上記で署名付き電文(16進形式));
boolean result = verifier.verify(messageByte);

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?