为什么我使用OpenSSL和Java生成的RSA-SHA256签名不同?
我想在Java中生成RSA-SHA256签名,但我无法让它生成与控制台上的OpenSSL相同的签名。
这就是我对OpenSSL所做的(遵循本教程):
生成密钥对:
openssl genrsa -out private.pem 1024
提取公钥:
openssl rsa -in private.pem -out public.pem -outform PEM -pubout
创建数据哈希:
echo 'data to sign' > data.txt
openssl dgst -sha256 < data.txt > hash
生成的哈希文件以我手动删除的内容开头(首先忘记提及它,谢谢mata)。(stdin)=
签名哈希:
openssl rsautl -sign -inkey private.pem -keyform PEM -in hash > signature
为了在Java中重现结果,我首先将私钥从PEM转换为DER:
openssl pkcs8 -topk8 -inform PEM -outform DER -in private.pem -nocrypt > private.der
现在我写了这个Java类来生成相同的签名:
public class RSATest {
public static void main(String[] args) throws IOException,
NoSuchAlgorithmException, InvalidKeySpecException,
InvalidKeyException, SignatureException {
byte[] encodedPrivateKey = readFile("private.der");
byte[] content = readFile("data.txt");
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory
.generatePrivate(keySpec);
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey);
signature.update(content);
byte[] signatureBytes = signature.sign();
FileOutputStream fos = new FileOutputStream("signature-java");
fos.write(signatureBytes);
fos.close();
}
private static byte[] readFile(String filename) throws IOException {
File file = new File(filename);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file));
byte[] bytes = new byte[(int) file.length()];
bis.read(bytes);
bis.close();
return bytes;
}
}
不幸的是,结果不一样,所以我认为我一定做错了什么,但我不知道是什么。你们中的某个人可以帮助我找到错误吗?