[转]OpenSSL RSA加解密 (.Net公钥加密/ Linux端私钥解密)
要求在.Net端生成公钥私钥对。
然后在.Net端使用RSA公钥加密;在Linux端使用RSA私钥解密。
最初的尝试是:.Net端使用RSACryptoServiceProvider; Linux端使用OpenSSL
搞了整整5个小时,有木有啊,有木有啊! .Net的RSA和OpenSSL对不上,有木有啊,有木有啊!
人都搞晕了就是对不上。最后解决方式换成了,.Net端使用 OpenSSL.Net.
.Net端代码
string publicKeyFile = context.Server.MapPath("~/App_Data/public.pem");
using( RSA rsa = RSA.FromPublicKey(BIO.File(publicKeyFile, "r")) )
{
buffer = rsa.PublicEncrypt( buffer, RSA.Padding.OAEP);
encryptedKey = Convert.ToBase64String(buffer);
}
Linux端代码
BIO *b64, *bmem;
// Base64解码
unsigned char *buffer = (unsigned char *)malloc(length);
memset(buffer, 0, length);
b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
bmem = BIO_new_mem_buf(szKey, length);
bmem = BIO_push(b64, bmem);
int len = BIO_read(bmem, buffer, length);
BIO_free_all(bmem);
// 加载私钥
BIO * key = NULL;
RSA * r = NULL;
key = BIO_new(BIO_s_file());
BIO_read_filename(key, "/val/XXX/private.pem" );
r = PEM_read_bio_RSAPrivateKey(key, NULL, NULL, NULL);
BIO_free_all(key);
unsigned char * plainText = (unsigned char *)malloc(len);
memset( plainText, 0, len);
// 解密
int ret = RSA_private_decrypt( RSA_size(r), buffer, plainText, r, RSA_PKCS1_OAEP_PADDING);
RSA_free(r);
free(plainText);
free(buffer);
-------------------------------------------------------------------------
转自:http://blog.csdn.net/wangjia184/article/details/6941242
其它参考: