.NET使用OpenSSL生成的pem密钥文件【做电子商务的朋友可能需要】
NET要使用OpenSSL生成的pem密钥文件,网上资料很少(http://www.faqs.org/rfcs/rfc1421.html,RFC1421文件又老长老长),仅有的资料还是有错误的,所以今天干了件体力活,把PEM密钥文件610个字节一个个看过来,终于搞清了它的格式。using System;
using System.Text;
using System.Security.Cryptography;
using System.Web;
using System.IO;
namespace Thinhunan.Cnblogs.Com.RSAUtility
{
public class PemConverter
{
/// <summary>
/// 将pem格式公钥转换为RSAParameters
/// </summary>
/// <param name="pemFileConent">pem公钥内容</param>
/// <returns>转换得到的RSAParamenters</returns>
public static RSAParameters ConvertFromPemPublicKey(string pemFileConent)
{
if (string.IsNullOrEmpty(pemFileConent))
{
throw new ArgumentNullException("pemFileConent", "This arg cann't be empty.");
}
pemFileConent = pemFileConent.Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "").Replace("\n", "").Replace("\r", "");
byte[] keyData = Convert.FromBase64String(pemFileConent);
if (keyData.Length < 162)
{
throw new ArgumentException("pem file content is incorrect.");
}
byte[] pemModulus = new byte[128];
byte[] pemPublicExponent = new byte[3];
Array.Copy(keyData, 29, pemModulus, 0, 128);
Array.Copy(keyData, 159, pemPublicExponent, 0, 3);
RSAParameters para = new RSAParameters();
para.Modulus = pemModulus;
para.Exponent = pemPublicExponent;
return para;
}
/// <summary>
/// 将pem格式私钥转换为RSAParameters
/// </summary>
/// <param name="pemFileConent">pem私钥内容</param>
/// <returns>转换得到的RSAParamenters</returns>
public static RSAParameters ConvertFromPemPrivateKey(string pemFileConent)
{
if (string.IsNullOrEmpty(pemFileConent))
{
throw new ArgumentNullException("pemFileConent", "This arg cann't be empty.");
}
pemFileConent = pemFileConent.Replace("-----BEGIN RSA PRIVATE KEY-----", "").Replace("-----END RSA PRIVATE KEY-----", "").Replace("\n", "").Replace("\r","");
byte[] keyData = Convert.FromBase64String(pemFileConent);
if (keyData.Length < 609)
{
throw new ArgumentException("pem file content is incorrect.");
}
int index = 11;
byte[] pemModulus = new byte[128];
Array.Copy(keyData, index, pemModulus, 0, 128);
index += 128;
index += 2;//141
byte[] pemPublicExponent = new byte[3];
Array.Copy(keyData, index, pemPublicExponent, 0, 3);
index += 3;
index += 4;//148
byte[] pemPrivateExponent = new byte[128];
Array.Copy(keyData, index , pemPrivateExponent, 0, 128);
index += 128;
index += ((int)keyData[index+1] == 64?2: 3);//279
byte[] pemPrime1 = new byte[64];
Array.Copy(keyData, index, pemPrime1, 0, 64);
index += 64;
index += ((int)keyData[index + 1] == 64 ? 2 : 3);//346
byte[] pemPrime2 = new byte[64];
Array.Copy(keyData, index , pemPrime2, 0, 64);
index += 64;
index += ((int)keyData[index + 1] == 64 ? 2 : 3);//412/413
byte[] pemExponent1 = new byte[64];
Array.Copy(keyData,index, pemExponent1, 0, 64);
index += 64;
index += ((int)keyData[
补充:Web开发 , ASP.Net ,