I want to implement my own signature function using RSA as a cipher algorithm and SHA-1 as a hash function, to do so I implemented those two function:
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;
}
}
Then when I use those function, I always obtain false as result which means that my functions are not working right :
byte[] message = "hello world".getBytes();
byte[] signature;
signature = mySign(message );
boolean bool = myCheckSignature(message , signature, thePublicKey);
System.out.println(bool);
While your requirement
as a whole is questionable (as mentioned in the comments to your question), your solution can be improved.
In particular there is an error in your
myCheckSignaturecode:(digest1 == digest2)checks whether you have the identical array object, not whether you have two arrays with equal contents.What you really want to do is
or more compactly
Arraysis a utility class in the packagejava.util.By the way, you do
getByteswithout explicitly selecting a character encoding may result in different results on different platforms or different Java versions. Something that should not happen in this context!