入力として3つのものを取るインターフェースを実装しています
X509 証明書
その証明書の秘密鍵で署名された signedHash
初期ハッシュ
次のアクションを実行する必要があります。
- このハッシュが提供された証明書を使用して署名されていることを確認します。
- 入力として提供された証明書の公開鍵を使用して署名付きハッシュを復号化し、提供されたハッシュと一致することを確認します。
デジタル署名を検証するために以下を実装しました:-
public static boolean verifySignedHash(String X509Certificate, String hash,
String signedHash) {
boolean isVerified = false;
ByteArrayInputStream inputStream = null;
ByteArrayOutputStream outputStream = null;
ByteArrayOutputStream byo = null;
try {
outputStream = new ByteArrayOutputStream();
byte[] data = Base64.decodeBase64(X509Certificate);
/* writing decoded X509 certificate to the ByteArrayOutputStream */
outputStream.write(data);
byte[] inp = outputStream.toByteArray();
inputStream = new ByteArrayInputStream(inp);
/* Getting the certificate from the Input */
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate certs = (X509Certificate) cf
.generateCertificate(inputStream);
/* import encoded public key */
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(certs
.getPublicKey().getEncoded());
/* Instantiating KeyFactory for accesing the Keys as Object */
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
/*
* using the KeyFactory object to generate a PublicKey from the key
* specification.
*/
publickKey = keyFactory.generatePublic(pubKeySpec);
byte[] signHash = Base64.decodeBase64(signedHash);
byo = new ByteArrayOutputStream();
byo.write(signHash);
byte[] signChar = byo.toByteArray();
ByteArrayInputStream byi = new ByteArrayInputStream(signChar);
/* Next, input the signature bytes from the file specified */
byte[] sigToVerify = new byte[byi.available()];
byi.read(sigToVerify);
byi.close();
/* Instantiating Signature */
Signature signature = Signature.getInstance(certs.getSigAlgName());
/* Initializing the Public Key in Signature */
signature.initVerify(publickKey);
/* Supply the Signature Object With the Data to be Verified */
BufferedInputStream bufin = new BufferedInputStream(byi);
byte[] buffer = new byte[1024];
int len;
while (bufin.available() != 0) {
len = bufin.read(buffer);
signature.update(buffer, 0, len);
};
bufin.close();
/* Verify the Signature */
isVerified = signature.verify(sigToVerify);
} catch (Exception e) {
System.err.println("Caught exception " + e.toString());
}
return isVerified;
}
結果を False として取得しています
**Am i Missing something or is this piece of code correct ?**
本当にありがとうございました。どうもありがとう。