【发布时间】:2010-10-05 23:40:23
【问题描述】:
我试图了解 Java java.security.Signature 类的作用。如果我计算一个 SHA1 消息摘要,然后使用 RSA 对该摘要进行加密,我会得到与要求 Signature 类签署相同内容不同的结果:
// Generate new key
KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
String plaintext = "This is the message being signed";
// Compute signature
Signature instance = Signature.getInstance("SHA1withRSA");
instance.initSign(privateKey);
instance.update((plaintext).getBytes());
byte[] signature = instance.sign();
// Compute digest
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
byte[] digest = sha1.digest((plaintext).getBytes());
// Encrypt digest
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] cipherText = cipher.doFinal(digest);
// Display results
System.out.println("Input data: " + plaintext);
System.out.println("Digest: " + bytes2String(digest));
System.out.println("Cipher text: " + bytes2String(cipherText));
System.out.println("Signature: " + bytes2String(signature));
结果(例如):
输入数据:这是正在签名的消息
摘要:62b0a9ef15461c82766fb5bdaae9edbe4ac2e067
密文:057dc0d2f7f54acc95d3cf5cba9f944619394711003bdd12...
签名:7177c74bbbb871cc0af92e30d2808ebae146f25d3fd8ba1622...
我一定对 Signature 正在做的事情有一个根本性的误解 - 我已经对其进行了跟踪,它似乎正在对 MessageDigest 对象调用更新,其中正如我所料,算法设置为 SHA1,然后获取摘要,然后进行加密。是什么导致结果不同?
编辑:
Leonidas 让我检查签名方案是否应该按照我的想法去做。 RFC中定义了两种类型的签名:
first of these (PKCS1) 就是我上面描述的那个。它使用哈希函数创建摘要,然后使用私钥对结果进行加密。
second algorithm 使用随机盐值,更安全但不确定。如果重复使用相同的密钥,上面代码产生的签名不会改变,所以我认为它不可能是PSS。
编辑:
这是我使用的bytes2string 方法:
private static String bytes2String(byte[] bytes) {
StringBuilder string = new StringBuilder();
for (byte b : bytes) {
String hexString = Integer.toHexString(0x00FF & b);
string.append(hexString.length() == 1 ? "0" + hexString : hexString);
}
return string.toString();
}
【问题讨论】:
标签: java encryption cryptography rsa digital-signature