我需要从文件加载以下RSA公钥,以便与RSACryptoServiceProvider类一起使用。我怎么能这样做?
-----BEGIN PUBLIC KEY-----
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/syEKqEkMtQL0+d
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX+izR
KbGMRtur2TYklnyVkjeeHfAggo8vWQmWesnOG55vQYHbOOFoJbk0EkwEr5R/PbKm
byXPPN8zwnS5/XXXXXXXXXXXX
-----END PUBLIC KEY-----
此代码适用于我的pub键:http://www.jensign.com/opensslkey/
以下是我正在使用的代码
static string RSA(string input)
{
RSACryptoServiceProvider rsa = DecodeX509PublicKey(Convert.FromBase64String(GetKey()));
return (Convert.ToBase64String(rsa.Encrypt(Encoding.ASCII.GetBytes(input), false)));
}
static string GetKey()
{
return File.ReadAllText("master.pub").Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "");
//.Replace("\n", "");
}
private static bool CompareBytearrays(byte[] a, byte[] b)
{
if (a.Length != b.Length)
return false;
int i = 0;
foreach (byte c in a)
{
if (c != b[i])
return false;
i++;
}
return true;
}
public static RSACryptoServiceProvider DecodeX509PublicKey(byte[] x509key)
{
// encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
byte[] seq = new byte[15];
// --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------
MemoryStream mem = new MemoryStream(x509key);
BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
byte bt = 0;
ushort twobytes = 0;
try
{
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
return null;
seq = binr.ReadBytes(15); //read the Sequence OID
if (!CompareBytearrays(seq, SeqOID)) //make sure Sequence for OID is correct
return null;
twobytes = binr.ReadUInt16();
if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8203)
binr.ReadInt16(); //advance 2 bytes
else
return null;
bt = binr.ReadByte();
if (bt != 0x00) //expect null byte next
return null;
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
return null;
twobytes = binr.ReadUInt16();
byte lowbyte = 0x00;
byte highbyte = 0x00;
if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81)
lowbyte = binr.ReadByte(); // read next bytes which is bytes in modulus
else if (twobytes == 0x8202)
{
highbyte = binr.ReadByte(); //advance 2 bytes
lowbyte = binr.ReadByte();
}
else
return null;
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order
int modsize = BitConverter.ToInt32(modint, 0);
byte firstbyte = binr.ReadByte();
binr.BaseStream.Seek(-1, SeekOrigin.Current);
if (firstbyte == 0x00)
{ //if first byte (highest order) of modulus is zero, don't include it
binr.ReadByte(); //skip this null byte
modsize -= 1; //reduce modulus buffer size by 1
}
byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes
if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data
return null;
int expbytes = (int)binr.ReadByte(); // should only need one byte for actual exponent data (for all useful values)
byte[] exponent = binr.ReadBytes(expbytes);
// ------- create RSACryptoServiceProvider instance and initialize with public key -----
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAKeyInfo = new RSAParameters();
RSAKeyInfo.Modulus = modulus;
RSAKeyInfo.Exponent = exponent;
RSA.ImportParameters(RSAKeyInfo);
return RSA;
}
catch (Exception)
{
return null;
}
finally { binr.Close(); }
}
只需使用您要加密的文本调用“RSA”方法即可。
答案 0 :(得分:4)
如果您正在谈论X509证书:
FileStream fs = new FileStream("your_cert_file.crt", FileMode.Open);
byte[] certBytes = new byte[fs.Length];
fs.Read(certBytes, 0, (Int32)fs.Length);
fs.Close();
System.Security.Cryptography.X509Certificates.X509Certificate x509cert =
new X509Certificate(certBytes);
Console.WriteLine(x509cert.GetPublicKey());
Console.WriteLine(x509cert.GetPublicKeyString());
@hkproj在“7/16/2012 15:04:58 Z”完成评论后编辑:
环顾四周,我找到了“Reading PEM RSA Public Key Only using Bouncy Castle”。 我猜你想要的是这个:
using (StreamReader reader = File.OpenText(@"c:\RSA.txt"))
{
Org.BouncyCastle.OpenSsl.PemReader pr =
new Org.BouncyCastle.OpenSsl.PemReader(reader);
Org.BouncyCastle.Utilities.IO.Pem.PemObject po = pr.ReadPemObject();
Console.WriteLine("PemObject, Type: " + po.Type);
Console.WriteLine("PemObject, Length: " + po.Content.Length);
}
但是,对于您的文件,我收到错误:System.IO.IOException : base64 data appears to be truncated
。
将文件更改为:
-----BEGIN PUBLIC KEY-----
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/syEKqEkMtQL0+d
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX+izR
KbGMRtur2TYklnyVkjeeHfAggo8vWQmWesnOG55vQYHbOOFoJbk0EkwEr5R/PbKm
byXPPN8zwnS5/XXXXXXXXXXXXZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
-----END PUBLIC KEY-----
结果是:
PemObject, Type: PUBLIC KEY
PemObject, Length: 192
答案 1 :(得分:3)
您是在谈论存储在文件中的证书吗?
如果你有一个像这样的对象:
X509Certificate2 certificate;
您可以使用以下代码:
RSACryptoServiceProvider rsaprovider =
(RSACryptoServiceProvider)certificate.PublicKey.Key;
然后使用类RSACryptoServiceProvider(参见http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.aspx)。
要加载X509Certificate2,请使用其构造函数(请参阅http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2.aspx)。
这个程序对我来说很好用:
static void Main(string[] args)
{
try
{
X509Certificate2 certificate =
new X509Certificate2("<PFX Certificate Path", "<Certificate-Password>");
RSACryptoServiceProvider rsaprovider = (RSACryptoServiceProvider)certificate.PublicKey.Key;
}
catch(Exception e)
{
}
}
答案 2 :(得分:1)
从 .Net 5.0 开始,您可以像这样从字符串导入 RSA 公钥:
var rsaPublicKey = RSA.Create();
rsaPublicKey.ImportFromPem(publicKeyString);
如果您不知道如何将文件读取为字符串,请参阅
答案 3 :(得分:0)
na_values