我想在 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
生成的哈希文件以(stdin)=
我手动删除的内容开始(首先忘了提及,谢谢mata)。
签名哈希:
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;
}
}
不幸的是结果不一样,所以我想我一定做错了什么,但我不知道是什么。你们有人可以帮我找到错误吗?