Java 使用 X.509 公共证书加密和解密
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21786821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Encryption and Decryption with X.509 public certificate
提问by MatthiasLaug
I want to encrypt my post payload with an X.509 certificate and the inherited public key. So far I have this java code to perform the encryption
我想用 X.509 证书和继承的公钥加密我的帖子有效负载。到目前为止,我有这个java代码来执行加密
private String encrypt(String str) throws Exception {
ClassPathResource classPathResource = new ClassPathResource("testcert1.crt");
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate)certificateFactory.generateCertificate(classPathResource.getInputStream());
PublicKey pk = certificate.getPublicKey();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
cipher.init(Cipher.ENCRYPT_MODE, pk);
return Base64.encodeBase64String(cipher.doFinal(str.getBytes()));
}
which returns the base64 encoded string. From the endpoint I am always getting the result, that the certificate is not valid.
它返回 base64 编码的字符串。从端点我总是得到结果,即证书无效。
So I want to validate my encrypted string on the console using the openssl
command, but failing to do so.
所以我想使用openssl
命令在控制台上验证我的加密字符串,但没有这样做。
I can read out the certificate with: openssl x509 -in testcert1.crt -text -noout
我可以读出证书: openssl x509 -in testcert1.crt -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 0 (0x0)
Signature Algorithm: md5WithRSAEncryption
Issuer: C=xxx, ST=xxx, L=xxx, O=xxx, OU=xxx, CN=xxx
Validity
Not Before: Jul 24 11:40:39 2013 GMT
Not After : Jul 24 11:40:39 2015 GMT
Subject: C=xxx, ST=xxx, L=xxx, O=xxx, OU=xxx, CN=xxx
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
RSA Public Key: (4096 bit)
Modulus (4096 bit):
....
Exponent: 65537 (0x10001)
But I cannot figure out the command lines to encrypt/decrypt a text file using that certificate
但我无法弄清楚使用该证书加密/解密文本文件的命令行
回答by Guy Bouallet
As you are using asymmetric cryptography, if you encrypt using the public key of your certificate, you can only decrypt using the corresponding private key. Make sure you have that key and use it for decryption.
由于您使用的是非对称加密,如果您使用证书的公钥进行加密,则只能使用相应的私钥进行解密。确保您拥有该密钥并将其用于解密。
回答by Ernesto
You can validate your encrypted string using openssl with the following command:
您可以使用 openssl 和以下命令验证您的加密字符串:
echo -n 'string to encrypt' | openssl rsautl -encrypt -certin -inkey testcert1.crt | base64