using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography; namespace HelloWord.RSA
{
/// <summary>
/// 类名:RSAFromPkcs8
/// 功能:RSA加密、解密、签名、验签 (支持1024位和2048位私钥)
/// 详细:该类对Java生成的密钥进行解密和签名以及验签专用类,不需要修改
/// 版本:3.0
/// 日期:2013-07-08
/// 说明:
/// 以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
/// </summary>
public sealed class RSAFromPkcs8
{
/**
* RSA最大解密密文大小
* 注意:这个和密钥长度有关系, 公式= 密钥长度 / 8
*/
private const int MAX_DECRYPT_BLOCK = 128; /// <summary>
/// 签名
/// </summary>
/// <param name="content">待签名字符串</param>
/// <param name="privateKey">私钥</param>
/// <param name="input_charset">编码格式</param>
/// <returns>签名后字符串</returns>
public static string sign(string content, string privateKey, string input_charset)
{
byte[] Data = Encoding.GetEncoding(input_charset).GetBytes(content);
RSACryptoServiceProvider rsa = DecodePemPrivateKey(privateKey);
SHA1 sh = new SHA1CryptoServiceProvider();
byte[] signData = rsa.SignData(Data, sh);
return Convert.ToBase64String(signData);
} /// <summary>
/// 验签
/// </summary>
/// <param name="content">待验签字符串</param>
/// <param name="signedString">签名</param>
/// <param name="publicKey">公钥</param>
/// <param name="input_charset">编码格式</param>
/// <returns>true(通过),false(不通过)</returns>
public static bool verify(string content, string signedString, string publicKey, string input_charset)
{
bool result = false;
byte[] Data = Encoding.GetEncoding(input_charset).GetBytes(content);
byte[] data = Convert.FromBase64String(signedString);
RSAParameters paraPub = ConvertFromPublicKey(publicKey);
RSACryptoServiceProvider rsaPub = new RSACryptoServiceProvider();
rsaPub.ImportParameters(paraPub);
SHA1 sh = new SHA1CryptoServiceProvider();
result = rsaPub.VerifyData(Data, sh, data);
return result;
} /// <summary>
/// 加密
/// </summary>
/// <param name="resData">需要加密的字符串</param>
/// <param name="publicKey">公钥</param>
/// <param name="input_charset">编码格式</param>
/// <returns>明文</returns>
public static string encryptData(string resData, string publicKey, string input_charset)
{
byte[] DataToEncrypt = Encoding.ASCII.GetBytes(resData);
string result = encrypt(DataToEncrypt, publicKey, input_charset);
return result;
} /// <summary>
/// 解密
/// </summary>
/// <param name="resData">加密字符串</param>
/// <param name="privateKey">私钥</param>
/// <param name="input_charset">编码格式</param>
/// <returns>明文</returns>
public static string decryptData(string resData, string privateKey, string input_charset)
{
byte[] DataToDecrypt = Convert.FromBase64String(resData);
string result = "";
for (int j = 0; j < DataToDecrypt.Length / MAX_DECRYPT_BLOCK; j++)
{
byte[] buf = new byte[MAX_DECRYPT_BLOCK];
for (int i = 0; i < MAX_DECRYPT_BLOCK; i++)
{ buf[i] = DataToDecrypt[i + MAX_DECRYPT_BLOCK * j];
}
result += decrypt(buf, privateKey, input_charset);
}
return result;
} #region 内部方法 private static string encrypt(byte[] data, string publicKey, string input_charset)
{
RSACryptoServiceProvider rsa = DecodePemPublicKey(publicKey);
SHA1 sh = new SHA1CryptoServiceProvider();
byte[] result = rsa.Encrypt(data, false); return Convert.ToBase64String(result);
} private static string decrypt(byte[] data, string privateKey, string input_charset)
{
string result = ""; RSACryptoServiceProvider rsa = DecodePemPrivateKey(privateKey);
//--- Edit for testing by lzyan ---
//RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
//RSAParameters paraPri = ConvertFromPrivateKey(privateKey);
//rsa.ImportParameters(paraPri);
//--- Edit End --- SHA1 sh = new SHA1CryptoServiceProvider();
byte[] source = rsa.Decrypt(data, false);
char[] asciiChars = new char[Encoding.GetEncoding(input_charset).GetCharCount(source, 0, source.Length)];
Encoding.GetEncoding(input_charset).GetChars(source, 0, source.Length, asciiChars, 0);
result = new string(asciiChars);
//result = ASCIIEncoding.ASCII.GetString(source);
return result;
} private static RSACryptoServiceProvider DecodePemPublicKey(String pemstr)
{
byte[] pkcs8publickkey;
pkcs8publickkey = Convert.FromBase64String(pemstr);
if (pkcs8publickkey != null)
{
RSACryptoServiceProvider rsa = DecodeRSAPublicKey(pkcs8publickkey);
return rsa;
}
else
return null;
} private static RSACryptoServiceProvider DecodePemPrivateKey(String pemstr)
{
byte[] pkcs8privatekey;
pkcs8privatekey = Convert.FromBase64String(pemstr);
if (pkcs8privatekey != null)
{
RSACryptoServiceProvider rsa = DecodePrivateKeyInfo(pkcs8privatekey);
return rsa;
}
else
return null;
} private static RSACryptoServiceProvider DecodePrivateKeyInfo(byte[] pkcs8)
{
byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
byte[] seq = new byte[15]; MemoryStream mem = new MemoryStream(pkcs8);
int lenstream = (int)mem.Length;
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; bt = binr.ReadByte();
if (bt != 0x02)
return null; twobytes = binr.ReadUInt16(); if (twobytes != 0x0001)
return null; seq = binr.ReadBytes(15); //read the Sequence OID
if (!CompareBytearrays(seq, SeqOID)) //make sure Sequence for OID is correct
return null; bt = binr.ReadByte();
if (bt != 0x04) //expect an Octet string
return null; bt = binr.ReadByte(); //read next byte, or next 2 bytes is 0x81 or 0x82; otherwise bt is the byte count
if (bt == 0x81)
binr.ReadByte();
else
if (bt == 0x82)
binr.ReadUInt16();
//------ at this stage, the remaining sequence should be the RSA private key byte[] rsaprivkey = binr.ReadBytes((int)(lenstream - mem.Position));
RSACryptoServiceProvider rsacsp = DecodeRSAPrivateKey(rsaprivkey);
return rsacsp;
} catch (Exception)
{
return null;
} finally { binr.Close(); } } 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;
} private static RSACryptoServiceProvider DecodeRSAPublicKey(byte[] publickey)
{
// 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(publickey);
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(); } } private static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
{
byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; // --------- Set up stream to decode the asn.1 encoded RSA private key ------
MemoryStream mem = new MemoryStream(privkey);
BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
byte bt = 0;
ushort twobytes = 0;
int elems = 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; twobytes = binr.ReadUInt16();
if (twobytes != 0x0102) //version number
return null;
bt = binr.ReadByte();
if (bt != 0x00)
return null; //------ all private key components are Integer sequences ----
elems = GetIntegerSize(binr);
MODULUS = binr.ReadBytes(elems); elems = GetIntegerSize(binr);
E = binr.ReadBytes(elems); elems = GetIntegerSize(binr);
D = binr.ReadBytes(elems); elems = GetIntegerSize(binr);
P = binr.ReadBytes(elems); elems = GetIntegerSize(binr);
Q = binr.ReadBytes(elems); elems = GetIntegerSize(binr);
DP = binr.ReadBytes(elems); elems = GetIntegerSize(binr);
DQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr);
IQ = binr.ReadBytes(elems); // ------- create RSACryptoServiceProvider instance and initialize with public key -----
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAparams = new RSAParameters();
RSAparams.Modulus = MODULUS;
RSAparams.Exponent = E;
RSAparams.D = D;
RSAparams.P = P;
RSAparams.Q = Q;
RSAparams.DP = DP;
RSAparams.DQ = DQ;
RSAparams.InverseQ = IQ;
RSA.ImportParameters(RSAparams);
return RSA;
}
catch (Exception)
{
return null;
}
finally { binr.Close(); }
} private static int GetIntegerSize(BinaryReader binr)
{
byte bt = 0;
byte lowbyte = 0x00;
byte highbyte = 0x00;
int count = 0;
bt = binr.ReadByte();
if (bt != 0x02) //expect integer
return 0;
bt = binr.ReadByte(); if (bt == 0x81)
count = binr.ReadByte(); // data size in next byte
else
if (bt == 0x82)
{
highbyte = binr.ReadByte(); // data size in next 2 bytes
lowbyte = binr.ReadByte();
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
count = BitConverter.ToInt32(modint, 0);
}
else
{
count = bt; // we already have the data size
} while (binr.ReadByte() == 0x00)
{ //remove high order zeros in data
count -= 1;
}
binr.BaseStream.Seek(-1, SeekOrigin.Current); //last ReadByte wasn't a removed zero, so back up a byte
return count;
} #endregion #region 解析.net 生成的Pem
private static RSAParameters ConvertFromPublicKey(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);
bool keySize1024 = (keyData.Length == 162);
bool keySize2048 = (keyData.Length == 294);
if (!(keySize1024 || keySize2048))
{
throw new ArgumentException("pem file content is incorrect, Only support the key size is 1024 or 2048");
}
byte[] pemModulus = (keySize1024 ? new byte[128] : new byte[256]);
byte[] pemPublicExponent = new byte[3];
Array.Copy(keyData, (keySize1024 ? 29 : 33), pemModulus, 0, (keySize1024 ? 128 : 256));
Array.Copy(keyData, (keySize1024 ? 159 : 291), pemPublicExponent, 0, 3);
RSAParameters para = new RSAParameters();
para.Modulus = pemModulus;
para.Exponent = pemPublicExponent;
return para;
} /// <summary>
/// 将pem格式私钥(1024 or 2048)转换为RSAParameters
/// </summary>
/// <param name="pemFileConent">pem私钥内容</param>
/// <returns>转换得到的RSAParamenters</returns>
private static RSAParameters ConvertFromPrivateKey(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); bool keySize1024 = (keyData.Length == 609 || keyData.Length == 610);
bool keySize2048 = (keyData.Length == 1190 || keyData.Length == 1192); if (!(keySize1024 || keySize2048))
{
throw new ArgumentException("pem file content is incorrect, Only support the key size is 1024 or 2048");
} int index = (keySize1024 ? 11 : 12);
byte[] pemModulus = (keySize1024 ? new byte[128] : new byte[256]);
Array.Copy(keyData, index, pemModulus, 0, pemModulus.Length); index += pemModulus.Length;
index += 2;
byte[] pemPublicExponent = new byte[3];
Array.Copy(keyData, index, pemPublicExponent, 0, 3); index += 3;
index += 4;
if ((int)keyData[index] == 0)
{
index++;
}
byte[] pemPrivateExponent = (keySize1024 ? new byte[128] : new byte[256]);
Array.Copy(keyData, index, pemPrivateExponent, 0, pemPrivateExponent.Length); index += pemPrivateExponent.Length;
index += (keySize1024 ? ((int)keyData[index + 1] == 64 ? 2 : 3) : ((int)keyData[index + 2] == 128 ? 3 : 4));
byte[] pemPrime1 = (keySize1024 ? new byte[64] : new byte[128]);
Array.Copy(keyData, index, pemPrime1, 0, pemPrime1.Length); index += pemPrime1.Length;
index += (keySize1024 ? ((int)keyData[index + 1] == 64 ? 2 : 3) : ((int)keyData[index + 2] == 128 ? 3 : 4));
byte[] pemPrime2 = (keySize1024 ? new byte[64] : new byte[128]);
Array.Copy(keyData, index, pemPrime2, 0, pemPrime2.Length); index += pemPrime2.Length;
index += (keySize1024 ? ((int)keyData[index + 1] == 64 ? 2 : 3) : ((int)keyData[index + 2] == 128 ? 3 : 4));
byte[] pemExponent1 = (keySize1024 ? new byte[64] : new byte[128]);
Array.Copy(keyData, index, pemExponent1, 0, pemExponent1.Length); index += pemExponent1.Length;
index += (keySize1024 ? ((int)keyData[index + 1] == 64 ? 2 : 3) : ((int)keyData[index + 2] == 128 ? 3 : 4));
byte[] pemExponent2 = (keySize1024 ? new byte[64] : new byte[128]);
Array.Copy(keyData, index, pemExponent2, 0, pemExponent2.Length); index += pemExponent2.Length;
index += (keySize1024 ? ((int)keyData[index + 1] == 64 ? 2 : 3) : ((int)keyData[index + 2] == 128 ? 3 : 4));
byte[] pemCoefficient = (keySize1024 ? new byte[64] : new byte[128]);
Array.Copy(keyData, index, pemCoefficient, 0, pemCoefficient.Length); RSAParameters para = new RSAParameters();
para.Modulus = pemModulus;
para.Exponent = pemPublicExponent;
para.D = pemPrivateExponent;
para.P = pemPrime1;
para.Q = pemPrime2;
para.DP = pemExponent1;
para.DQ = pemExponent2;
para.InverseQ = pemCoefficient;
return para;
}
#endregion //extract valid content from PEM file
public static string extractFromPemFile(string filePath)
{
string result = "";
string COMMENT_BEGIN_FLAG = "-----";
//=============
//从头到尾以流的方式读出文本文件, 该方法会一行一行读出文本
using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath, Encoding.UTF8))
{
string str;
StringBuilder sb = new StringBuilder();
while ((str = sr.ReadLine()) != null)
{
if (!str.StartsWith(COMMENT_BEGIN_FLAG))
{
sb.Append(str);
}
}
result = sb.ToString();
}
return result;
} //extract valid content from PEM format string
public static string extractFromPemFormat(string input)
{
string result = "";
string COMMENT_BEGIN_FLAG = "-----";
string[] splitFlagArray = { "\r", "\n" };
string[] itemArray = input.Split(splitFlagArray, StringSplitOptions.RemoveEmptyEntries);
StringBuilder sb = new StringBuilder();
foreach (string item in itemArray)
{
if (!item.StartsWith(COMMENT_BEGIN_FLAG))
{
sb.Append(item);
}
}
result = sb.ToString();
return result;
} }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSCMDemo;
using CSCMDemo2;
using HelloWord.RSA;
using Ctrip.Cryptography;
using com.ctrip.sec.crypto; namespace HelloWord
{
class Program
{
static string UTF8 = "utf-8"; static void Main(string[] args)
{ //-- custom use ---
//testRSAFromPkcs1();
//testRSAFromPkcs8();
//testRSAFromPkcs8_file();
testRSAFromPkcs8_SOA(); //--- use provided dll ---
//testRsaWithSslcode(); } //test RSA sign
static void testRSAFromPkcs1()
{
string data = "abc";
string privateKeyPem = "../../RSA/private.key";
string sign = RSAFromPkcs1.RSASign(data, privateKeyPem);
Console.WriteLine("sign=" + sign); // 窗口暂停,等待按键
Console.ReadKey();
} //test RSA(pkcs#8)
static void testRSAFromPkcs8()
{
string data = "abc";
string privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKc6LdHBVOIHQtMJXSc9+KBWrJE49sED9CTPbUMTE3eueXOJDu+PBzUQn2f7Ef+j8E1z+PrKyVgx1U8MsE5moFSJocfbDT4NZK0BlU3nVmxh1x4tiHXFz1bA2DAWTtjUwTS5WOA6IqrWeGc8497ca8O+xLcT7ZKo03z419xoJ5jxAgMBAAECgYAIMPjDmIiNSQIqwjLc7dOUgj2SIEv99ZdrVWAqjYmoYbrmc0ujy/0nY6wOdNiGp11PyryvoQIVBUPhZMnrqgOnOOxPlWMDHMd6aFMfmDPqSQL5IEK982x56OCl8Z8fRe3wRZn3sT2DR1FvEJvlAFatLOzoQsLOz/ot26bjJyD8vQJBANyyjb0MZqHfuSKUT2t5VxHPsf5Xs7DleMmERqz5X4Iaj5HBUGl9Rv051Ta3oiADUM45MYkvDiOeyjhY9X6m6AcCQQDB+gxJl7qFU2pjnFhpPf/RqLzF0yri6SeXVUgcrUxj08f5+WsZdB0UaCa2+PW6R9Ln1IWl7ptD2MvekHIZYwlHAkBN0Dq/VBb/rgT1lzslVqQHaKaGWd/GWDItQxE0PbyZ/8ltB67VctFLyU9OupJUHTcpburzRn8CuiLsmRj9rdWTAkAgEov9jwzUBprMpYkovYuSyueLfgLVSd+18e/ebfj3eIjUGB1RNBWqzh24mylmB4IjusvuR6l8algrEI8NC4b5AkAlvT4xJhAASeFVxLEMWUm4uDkif9g1ruUs0J7EUHsFxffXIdAR8WXK9Nf3DdLsRLVvYka4z7VtOcucddiu1Xy/";
string sign = RSAFromPkcs8.sign(data, privateKey, UTF8);
Console.WriteLine("data=" + data);
Console.WriteLine("====================");
Console.WriteLine("sign=" + sign);
Console.WriteLine("===================="); string publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnOi3RwVTiB0LTCV0nPfigVqyROPbBA/Qkz21DExN3rnlziQ7vjwc1EJ9n+xH/o/BNc/j6yslYMdVPDLBOZqBUiaHH2w0+DWStAZVN51ZsYdceLYh1xc9WwNgwFk7Y1ME0uVjgOiKq1nhnPOPe3GvDvsS3E+2SqNN8+NfcaCeY8QIDAQAB";
bool verifyResult = RSAFromPkcs8.verify(data, sign, publicKey, UTF8);
Console.WriteLine("verifyResult=" + verifyResult); // 窗口暂停,等待按键
Console.ReadKey();
} //test RSA(pkcs#8) from file
static void testRSAFromPkcs8_file()
{
string data = "abc"; string privateKeyPem = "../../RSA/private_pkcs8.key";
string privateKey = RSAFromPkcs8.extractFromPemFile(privateKeyPem);
string sign = RSAFromPkcs8.sign(data, privateKey, UTF8);
Console.WriteLine("data=" + data);
Console.WriteLine("====================");
Console.WriteLine("sign=" + sign);
Console.WriteLine("===================="); string publicKeyPem = "../../RSA/public.key";
string publicKey = RSAFromPkcs8.extractFromPemFile(publicKeyPem);
bool verifyResult = RSAFromPkcs8.verify(data, sign, publicKey, UTF8);
Console.WriteLine("verifyResult=" + verifyResult); // 窗口暂停,等待按键
Console.ReadKey();
} //test RSA(pkcs#8) via SOA
static void testRSAFromPkcs8_SOA()
{
// 准备测试sslcode 1024 2048
string publicSslCode = "KI00000000001530"; //==> 返回的公钥是java格式的 //OH00000000000119, KI00000000001530, UE00000000001532 //AX00000000001436 [bad]
string privateSslCode = "UL00000000001531"; //==> 返回的私钥是java格式的 //JY00000000000120, UL00000000001531, ZT00000000001533 //SO00000000001437 // 准备测试字符串
string data = "abc"; Demo2 demo = new Demo2();
string privateKey = demo.GetSign(privateSslCode);
privateKey = RSAFromPkcs8.extractFromPemFormat(privateKey);
string sign = RSAFromPkcs8.sign(data, privateKey, UTF8);
Console.WriteLine("data=" + data);
Console.WriteLine("====================");
Console.WriteLine("sign=" + sign);
Console.WriteLine("===================="); string publicKey = demo.GetSign(publicSslCode);
publicKey = RSAFromPkcs8.extractFromPemFormat(publicKey);
bool verifyResult = RSAFromPkcs8.verify(data, sign, publicKey, UTF8);
Console.WriteLine("verifyResult=" + verifyResult);
Console.WriteLine("===================="); //--------------
string encData = RSAFromPkcs8.encryptData(data, publicKey, UTF8);
Console.WriteLine("encData=" + encData);
string decData = RSAFromPkcs8.decryptData(encData, privateKey, UTF8);
Console.WriteLine("decData=" + decData);
Console.WriteLine("===================="); // 窗口暂停,等待按键
Console.ReadKey();
} }
}

转自:

http://blog.csdn.net/zzzili/article/details/73739797

C#使用SHA1加密类(RSAFromPkcs8)支持1024位和2048位私钥的更多相关文章

  1. [Swift通天遁地]七、数据与安全-(19)使用Swift实现原生的SHA1加密

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...

  2. c#RSA的SHA1加密与AES加密、解密

    前言:公司项目对接了一个对数据保密性要求较高的java公司.api接口逻辑是这样的:他们提供 SHA1私钥 与 AES的秘钥.我们需要将 传递查询参数 通过SHA1 私钥加密再转换成 十六进制 字符串 ...

  3. oc ios 中文字符串 进行 sha1加密 错误?

    我在网上找到了一个oc版加密的工具类,但是加密中文就出现大问题 const char *cstr = [self cStringUsingEncoding:encoding]; NSData *dat ...

  4. 各种加密解密函数(URL加密解密、sha1加密解密、des加密解密)

    原文:各种加密解密函数(URL加密解密.sha1加密解密.des加密解密) 普通hash函数如md5.sha1.base64等都是不可逆函数.虽然我们利用php可以利用这些函数写出可逆函数来.但是跨语 ...

  5. 一个比较强大的HTTP请求类,支持文本参数和文件参数。

    一个 http 请求类 ,支持文件上传,从淘宝 top sdk 里面扣出来的,蛮好用的,做个记录而已. 调用代码: Dictionary<string, string> textParas ...

  6. ZIP解压缩文件的工具类【支持多级文件夹|全】

    ZIP解压缩文件的工具类[支持多级文件夹|全] 作者:Vashon 网上有非常多的加压缩演示样例代码.可是都仅仅是支持一级文件夹的操作.假设存在多级文件夹的话就不行了. 本解压缩工具类经过多次检查及重 ...

  7. ZIP解压缩文件的工具类【支持多级目录|全】

    ZIP解压缩文件的工具类[支持多级目录|全] 作者:Vashon 网上有很多的加压缩示例代码,但是都只是支持一级目录的操作,如果存在多级目录的话就不行了.本解压缩工具类经过多次检查及重构,最终分享给大 ...

  8. hashlib —— Python 的 md5 和 sha1 加密

    python的md5和sha1加密 0. md5 与 sha1 MD5 的全称是 Message-Digest Algorithm 5(信息-摘要算法).128 位长度.目前 MD5 是一种不可逆算法 ...

  9. php加密类

    1.需求 了解php加密类的使用 2.例子 参考ci的3.1.2的新版加密类,一个不传参,用默认加密算法,加密模式的例子 //0.加载加密类 $this->load->library('e ...

随机推荐

  1. tree - 列出树状目录结构

    tree - list contents of directories in a tree-like format. 树状显示目录结构 常用格式: tree [option] [directory] ...

  2. golang静态编译

    golang 的编译(不涉及 cgo 编译的前提下)默认使用了静态编译,不依赖任何动态链接库. 这样可以任意部署到各种运行环境,不用担心依赖库的版本问题.只是体积大一点而已,存储时占用了一点磁盘,运行 ...

  3. uiautomator2+python自动化测试1-环境准备

    前言 uiautomator是Google提供的用来做安卓自动化测试的一个Java库.功能很强,可以对第三方App进行测试,获取屏幕上任意一个APP的任意一个控件属性,并对其进行任意操作,但有两个缺点 ...

  4. 微信小程序~事件绑定和冒泡

    [1]事件绑定和冒泡 事件绑定的写法同组件的属性,以 key.value 的形式. key 以bind或catch开头,然后跟上事件的类型,如bindtap.catchtouchstart.自基础库版 ...

  5. Eclipse搭建maven web项目

    最近在做做一个小实验,搭建ssm框架,要求使用maven来统一管理jar包,接下来就看如何建立maven项目,首先必须有要有相应的开发环境:JDK和maven,以及配置tomcat. 开发环境搭建可以 ...

  6. windows——快速得到某一目录下所有文件的名称

    前言 其实用的是windows上dir命令,能快速得到某一目录下的所有文件名称,天天那么忙都没时间写博客(┬_┬) 步骤 打开cmd并cd到某目录下 C:\Users\Administrator.KI ...

  7. SpringCloud过滤filter

    目录 配置文件 application.yml eureka: client: service-url: defaultZone: http://localhost:8001/eureka serve ...

  8. Mscordacwks.dll/SOS.dll 调试归档

    找到个好东西 为什么要归档 此存档提供帮助,并可能提供对以下问题的答案 是否可以使WinDBG在符号存储中找到mscordacwks.dll?, Windbg需要不同版本的mscordacwks.dl ...

  9. CSPS_109

    T1 状压+位运算解决 T2 打完暴力后感到了迷茫.. 不过看这张表里1的数目占了一半之多,应该合法情况挺多的 拿出了从未用过的srand(time(0)); 结果撞上正解了(笑)(rp--) 现在$ ...

  10. codevs 2780 ZZWYYQWZHZ

    2780 ZZWYYQWZHZ  时间限制: 1 s  空间限制: 32000 KB  题目等级: 青铜 Bronze       题目描述 Description 可爱的小管在玩吹泡泡.忽然,他想到 ...