生成私钥:
openssl genrsa -out private.pem 1024
转换私钥成pkcs8,java要用到:
[code language=”bash”]
openssl pkcs8 -topk8 -inform pem -in private.pem -outform pem -nocrypt -out private-pkcs8.pem
[/code]
生成公钥:
openssl rsa -in private.pem -pubout -out public.pem
公钥加密:
echo -n "123" | openssl rsautl -encrypt -inkey private_pub.pem -pubin | openssl enc -base64 -A
私钥解密:
echo -n "gfWIcAPqKv4l26lYw+ufpUUDi0k9nFrbnWTFodmLwqYXClN9olO2SYsE2ff/UcbbKgkZzLmVNagVq1aKVy2vvROTpmzs6ELb3QSjYuiUJpDGx5ts64Jl0P+Iz/ZkZFRkdGG19NlI1rSd48rAsmhQ5WvHeG3bo034sMRQVvQHV4o=" | openssl enc -d -base64 -A | openssl rsautl -decrypt -inkey private.pem
私钥签名:
echo -n "123" | openssl rsautl -sign -inkey private.pem | openssl enc -base64 -A
公钥验证:
echo -n "Jbi4tNJ3VWJAH4wNRzd/Xve48Y5oYKS2n1Otv9D+wXPwsK7SOu3Tn8lHZBPZiT/GRIO8NByXxNoHxh73Kyb3mUPg5VUp1OL8VoL+adcMS+9f8zW9IPQ0Ht98o3LD3cGXg2c/cBAmXZC+0Iv67HJX44ClYSjrzs5kAdZhIjMnnvo=" | openssl enc -d -base64 -A | openssl rsautl -verify -pubin -inkey public.pem
因为rsa加解密是基于二进制数据的,所以上面使用了base64转码,使其输出为字符串。
附:转换成iOS可用的der证书
[code language=”bash”]
//Create a certificate signing request with the private key
openssl req -new -key rsaPrivate.pem -out rsaCertReq.csr
//Create a self-signed certificate with the private key and signing request
openssl x509 -req -days 3650 -in rsaCertReq.csr -signkey rsaPrivate.pem -out rsaCert.crt
//Convert the certificate to DER format: the certificate contains the public key
openssl x509 -outform der -in rsaCert.crt -out rsaCert.der
//Export the private key and certificate to p12 file
openssl pkcs12 -export -out rsaPrivate.p12 -inkey rsaPrivate.pem -in rsaCert.crt
[/code]