暗号アルゴリズムとして RSA を使用し、ハッシュ関数として SHA-1 を使用して独自の署名関数を実装したいので、これら 2 つの関数を実装しました。
public byte[] mySign(byte[] aMessage){
try{
// get an instance of a cipher with RSA with ENCRYPT_MODE
// Init the signature with the private key
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, this.thePrivateKey);
// get an instance of the java.security.MessageDigest with sha1
MessageDigest meassDs = MessageDigest.getInstance("SHA-1");
// process the digest
meassDs.update(aMessage);
byte[] digest = meassDs.digest();
byte [] signature = cipher.doFinal(digest);
// return the encrypted digest
return signature;
}catch(Exception e){
System.out.println(e.getMessage()+"Signature error");
e.printStackTrace();
return null;
}
}
public boolean myCheckSignature(byte[] aMessage, byte[] aSignature, PublicKey aPK){
try{
// get an instance of a cipher with RSA with DECRYPT_MODE
// Init the signature with the public key
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, aPK);
// decrypt the signature
byte [] digest1 = cipher.doFinal(aSignature);
// get an instance of the java.security.MessageDigest with sha1
MessageDigest meassDs = MessageDigest.getInstance("SHA-1");
// process the digest
meassDs.update(aMessage);
byte[] digest2 = meassDs.digest();
// check if digest1 == digest2
if (digest1 == digest2)
return true;
else
return false;
}catch(Exception e){
System.out.println("Verify signature error");
e.printStackTrace();
return false;
}
}
次に、これらの関数を使用すると、結果として常に false が得られます。これは、関数が正しく機能していないことを意味します。
byte[] message = "hello world".getBytes();
byte[] signature;
signature = mySign(message );
boolean bool = myCheckSignature(message , signature, thePublicKey);
System.out.println(bool);