【发布时间】:2016-04-16 22:48:35
【问题描述】:
我想使用 RSA 作为密码算法和 SHA-1 作为哈希函数来实现我自己的签名函数,为此我实现了这两个函数:
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);
【问题讨论】:
-
为什么不直接使用Signature class?
-
一般建议:始终使用完全限定的密码字符串。
Cipher.getInstance("RSA");可能会产生不同的密码,具体取决于默认的安全提供程序。现在,您应该使用 OAEP 而不是默认的 PKCS#1 v1.5 填充。所以你可能应该使用Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding"); -
我不是安全专家,但我知道 SHA-1 至少在创建证书时已被弃用。最好听从 caot 的建议,不要自己动手!
-
事实上,我正在研究一个项目,我必须实现一种方法来使用 java.security.Signature 的替代方法来创建签名。所以,我真的别无选择
标签: java rsa digital-signature sha1 java-security