/// <summary> /// Export RSA private key /// </summary> /// <param name="rsa"></param> /// <param name="type"></param> /// <param name="usePemFormat">Only valid if the private key type is PKCS#1 and PKCS#8.</param> /// <returns></returns> public static string ExportPrivateKey(this RSA rsa, RSAKeyType type, bool usePemFormat = false) { var key = string.Empty; switch (type) { case RSAKeyType.Pkcs1: key = Convert.ToBase64String(rsa.ExportRSAPrivateKey()); break; case RSAKeyType.Pkcs8: key = Convert.ToBase64String(rsa.ExportPkcs8PrivateKey()); break; case RSAKeyType.Xml: key = rsa.ExportXmlPrivateKey(); break; } if (usePemFormat && type != RSAKeyType.Xml) { key = PemFormatUtil.GetPrivateKeyFormat(type, key); } return(key); }
/// <summary> /// Export RSA private key /// </summary> /// <param name="rsa"></param> /// <param name="type"></param> /// <param name="privateKey"></param> /// <param name="isPem">Only valid if the private key type is PKCS#1 and PKCS#8.</param> /// <returns></returns> public static void ImportPrivateKey(this RSA rsa, RSAKeyType type, string privateKey, bool isPem = false) { if (isPem) { privateKey = PemFormatUtil.RemoveFormat(privateKey); } switch (type) { case RSAKeyType.Pkcs1: rsa.ImportRSAPrivateKey(Convert.FromBase64String(privateKey), out _); break; case RSAKeyType.Pkcs8: rsa.ImportPkcs8PrivateKey(Convert.FromBase64String(privateKey), out _); break; case RSAKeyType.Xml: rsa.ImportXmlPrivateKey(privateKey); break; default: throw new ArgumentOutOfRangeException(nameof(type), type, null); } }
/// <summary> /// 从本地文件中读取用来签发 Token 的 RSA Key /// </summary> /// <param name="keyType">钥匙类型:公钥 私钥</param> /// <returns>钥匙参数</returns> private RSAParameters LoadFromFile(RSAKeyType keyType) { string fileName = keyType == RSAKeyType.PrivateKey ? "key.private.json" : "key.public.json"; string fullPath = Path.Combine(_basePath, fileName); return(JsonConvert.DeserializeObject <RSAParameters>(File.ReadAllText(fullPath))); }
public static string GetPublicKeyFormat(RSAKeyType type, string publicKey) { return(type switch { RSAKeyType.Pkcs1 => GetPkcs1PublicKeyFormat(publicKey), RSAKeyType.Pkcs8 => GetPkcs8PublicKeyFormat(publicKey), _ => throw new Exception($"Public key type {type.ToString()} does not support pem formatting.") });
/// <summary> /// 初始化一个<see cref="AbsAsymmetricProvider"/>类型的实例 /// </summary> public AbsAsymmetricProvider(OutType outType = OutType.Hex, RSAKeyType keyType = RSAKeyType.Xml, Encoding encoding = null) { OutType = outType; if (encoding == null) { encoding = Encoding.UTF8; } Encoding = encoding; KeyType = keyType; }
/// <summary> /// 使用指定私钥解密字符串 /// </summary> /// <param name="value">要解密的密文字符串</param> /// <param name="privateKey">私钥</param> /// <param name="encoding">编码类型</param> /// <param name="outType">输出类型</param> /// <param name="keyType">密钥类型</param> /// <returns></returns> public static string Decrypt(string value, string privateKey, Encoding encoding = null, OutType outType = OutType.Base64, RSAKeyType keyType = RSAKeyType.Xml) { if (encoding == null) { encoding = Encoding.UTF8; } var result = Decrypt(value.GetEncryptBytes(outType), privateKey, keyType); return(encoding.GetString(result)); }
public static string GetPrivateKeyFormat(RSAKeyType type, string privateKey) { switch (type) { case RSAKeyType.Pkcs1: return(GetPkcs1PrivateKeyFormat(privateKey)); case RSAKeyType.Pkcs8: return(GetPkcs8PrivateKeyFormat(privateKey)); default: throw new Exception($"Private key type {type.ToString()} does not support pem formatting."); } }
public RSAKey(RSAParameters p, RSAKeyType type, string name) { Type = type; Name = name; P = null; Q = null; E = p.Exponent; N = p.Modulus; if (type == RSAKeyType.Private) { P = p.P; Q = p.Q; } }
/// <summary> /// Export RSA public key /// </summary> /// <param name="rsa"></param> /// <param name="type"></param> /// <param name="usePemFormat">Only valid if the public key type is PKCS#1 and PKCS#8.</param> /// <returns></returns> public static string ExportPublicKey(this RSA rsa, RSAKeyType type, bool usePemFormat = false) { var key = type switch { RSAKeyType.Pkcs1 => Convert.ToBase64String(rsa.ExportRSAPublicKey()), RSAKeyType.Pkcs8 => Convert.ToBase64String(rsa.ExportPkcs8PublicKey()), RSAKeyType.Xml => rsa.ExportXmlPublicKey(), _ => string.Empty }; if (usePemFormat && type != RSAKeyType.Xml) { key = PemFormatUtil.GetPublicKeyFormat(type, key); } return(key); }
/// <summary> /// 创建 RSA 密钥 /// </summary> /// <param name="size">密钥长度类型,默认为<see cref="RSAKeySizeType.L2048"/></param> /// <param name="keyType">密钥类型,默认为<see cref="RSAKeyType.Xml"/></param> /// <returns></returns> public static RSAKey CreateKey(RSAKeySizeType size = RSAKeySizeType.L2048, RSAKeyType keyType = RSAKeyType.Xml) { using (var rsa = new RSACryptoServiceProvider((int)size)) { var publicKey = keyType == RSAKeyType.Json ? rsa.ToJsonString(false) : rsa.ToExtXmlString(false); var privateKey = keyType == RSAKeyType.Json ? rsa.ToJsonString(true) : rsa.ToExtXmlString(true); return(new RSAKey() { PublickKey = publicKey, PrivateKey = privateKey, Exponent = rsa.ExportParameters(false).Exponent.ToHexString(), Modulus = rsa.ExportParameters(false).Modulus.ToHexString() }); } }
/// <summary> /// 使用指定公钥加密字符串 /// </summary> /// <param name="value">要加密的明文字符串</param> /// <param name="publicKey">公钥</param> /// <param name="encoding">编码类型</param> /// <param name="outType">输出类型</param> /// <param name="keyType">密钥类型</param> /// <returns></returns> public static string Encrypt(string value, string publicKey, Encoding encoding = null, OutType outType = OutType.Base64, RSAKeyType keyType = RSAKeyType.Xml) { if (encoding == null) { encoding = Encoding.UTF8; } var result = Encrypt(encoding.GetBytes(value), publicKey, keyType); if (outType == OutType.Base64) { return(Convert.ToBase64String(result)); } return(result.ToHexString()); }
/// <summary> /// 根据字符串类型的private Key获取RSAParameters,如果是public key,可以使用Chilkat /// </summary> /// <param name="privateKey"></param> /// <returns></returns> public static RSAParameters GetPrivateKey(string privateKey, RSAKeyType keyType) { if (privateKey.Contains("\n")) { StringBuilder buffer = new StringBuilder(); string[] arr = privateKey.Split('\n').Select(m => m.Trim()).Where(m => m.Length > 0).ToArray(); foreach (var line in arr) { if (line.StartsWith("-----")) { continue; } buffer.Append(line); } privateKey = buffer.ToString(); } return(getRSAPrivateKey(Convert.FromBase64String(privateKey), keyType)); }
/// <summary> /// 使用指定密钥对明文进行签名,返回明文签名的字符串 /// </summary> /// <param name="source">要签名的明文字符串</param> /// <param name="privateKey">私钥</param> /// <param name="encoding">编码类型</param> /// <param name="outType">输出类型</param> /// <param name="rsaType">算法类型</param> /// <param name="keyType">密钥类型</param> /// <returns></returns> public static string SignData(string source, string privateKey, Encoding encoding = null, OutType outType = OutType.Base64, RSAType rsaType = RSAType.RSA, RSAKeyType keyType = RSAKeyType.Xml) { if (encoding == null) { encoding = Encoding.UTF8; } var result = SignData(encoding.GetBytes(source), privateKey, rsaType, keyType); if (outType == OutType.Base64) { return(Convert.ToBase64String(result)); } return(result.ToHexString()); }
public static Rsa Create(ReadOnlySpan <Byte> key, RSAKeyType type = DefaultRSAKeyType, RSAParameters?parameters = null) { Rsa rsa = parameters is null?Rsa.Create() : Rsa.Create(parameters.Value); if (rsa is null) { throw new FactoryException("Unknown exception"); } Int32 size = key.Length * 8; try { rsa.KeySize = size; } catch (CryptographicException) { throw new ArgumentException($@"Invalid key size: {size}", nameof(key)); } switch (type) { case RSAKeyType.RSA: rsa.ImportRSAPrivateKey(key); break; case RSAKeyType.Pkcs8: rsa.ImportPkcs8PrivateKey(key); break; case RSAKeyType.RSAPublic: rsa.ImportRSAPublicKey(key); break; case RSAKeyType.SubjectPublic: rsa.ImportSubjectPublicKeyInfo(key); break; default: throw new NotSupportedException(); } return(rsa); }
/// <summary> /// Export RSA public key /// </summary> /// <param name="rsa"></param> /// <param name="type"></param> /// <param name="publicKey"></param> /// <param name="isPem">Only valid if the private key type is PKCS#1 and PKCS#8.</param> /// <returns></returns> public static void ImportPublicKey(this RSA rsa, RSAKeyType type, string publicKey, bool isPem = false) { if (isPem) { publicKey = PemFormatUtil.RemoveFormat(publicKey); } switch (type) { case RSAKeyType.Pkcs1: case RSAKeyType.Pkcs8: rsa.ImportRSAPublicKey(Convert.FromBase64String(publicKey), out _); break; case RSAKeyType.Xml: rsa.ImportXmlPublicKey(publicKey); break; } }
/// <summary> /// 使用指定私钥解密字节数组 /// </summary> /// <param name="sourceBytes">要解密的密文字节数组</param> /// <param name="privateKey">私钥</param> /// <param name="keyType">密钥类型</param> /// <returns></returns> public static byte[] Decrypt(byte[] sourceBytes, string privateKey, RSAKeyType keyType = RSAKeyType.Xml) { using (var rsa = RSA.Create()) { if (keyType == RSAKeyType.Xml) { rsa.FromExtXmlString(privateKey); } else if (keyType == RSAKeyType.Base64) { rsa.FromBase64StringByPrivateKey(privateKey); } else { rsa.FromJsonString(privateKey); } return(rsa.Decrypt(sourceBytes, RSAEncryptionPadding.Pkcs1)); } }
/// <summary> /// 使用指定私钥对明文进行签名,返回明文签名的字节数组 /// </summary> /// <param name="source">要签名的明文字节数组</param> /// <param name="privateKey">私钥</param> /// <param name="rsaType">算法类型</param> /// <param name="keyType">密钥类型</param> /// <returns></returns> public static byte[] SignData(byte[] source, string privateKey, RSAType rsaType = RSAType.RSA, RSAKeyType keyType = RSAKeyType.Xml) { using (var rsa = RSA.Create()) { if (keyType == RSAKeyType.Xml) { rsa.FromExtXmlString(privateKey); } else if (keyType == RSAKeyType.Base64) { rsa.FromBase64StringByPrivateKey(privateKey); } else { rsa.FromJsonString(privateKey); } return(rsa.SignData(source, rsaType == RSAType.RSA ? HashAlgorithmName.SHA1 : HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)); } }
/// <summary> /// 从 xml 或 json 字符串中获取RSA实例 /// </summary> /// <param name="rsaKey">rsa密钥</param> /// <param name="keyType">密钥类型,默认为<see cref="RSAKeyType.Xml"/></param> /// <returns></returns> public static RSA RsaFromString(string rsaKey, RSAKeyType keyType = RSAKeyType.Xml) { if (string.IsNullOrWhiteSpace(rsaKey)) { throw new ArgumentNullException(nameof(keyType)); } var rsa = RSA.Create(); if (keyType == RSAKeyType.Xml) { rsa.FromExtXmlString(rsaKey); } else if (keyType == RSAKeyType.Base64) { rsa.FromBase64StringByPrivateKey(rsaKey); } else { rsa.FromJsonString(rsaKey); } return(rsa); }
public static bool VerifyData(byte[] source, byte[] signData, string publicKey, RSAKeyType type = RSAKeyType.Base64) { var rsa = new RSACryptoServiceProvider(); if (type == RSAKeyType.Base64) { rsa.FromBase64StringByPublicKey(publicKey); } return(rsa.VerifyData(source, new SHA1CryptoServiceProvider(), signData)); }
public static RSAKey CreateKey(string privateKey, string publicKey, RSAKeySizeType size = RSAKeySizeType.L2048, RSAKeyType type = RSAKeyType.Base64) { using (var rsa = new RSACryptoServiceProvider((int)size)) { return(new RSAKey() { PrivateKey = privateKey, PublicKey = publicKey }); } }
public static bool VerifyData(string source, string signData, string publicKey, Encoding encoding = null, RSAOutType outType = RSAOutType.Base64, RSAKeyType type = RSAKeyType.Base64) { if (encoding == null) { encoding = Encoding.UTF8; } byte[] sourceBytes = encoding.GetBytes(source); byte[] signBytes; if (outType == RSAOutType.Base64) { signBytes = Convert.FromBase64String(signData); } else { signBytes = Convert.FromBase64String(signData); } return(VerifyData(sourceBytes, signBytes, publicKey, type)); }
public static byte[] SignData(byte[] source, string privateKey, RSAPrivateKeyFormat format = RSAPrivateKeyFormat.PKCS8, RSAKeyType type = RSAKeyType.Base64) { var rsa = new RSACryptoServiceProvider(); if (format == RSAPrivateKeyFormat.PKCS8) { rsa = RSAExtensions.DecodePemPrivateKey(privateKey); } else { if (type == RSAKeyType.Base64) { rsa.FromBase64StringByPrivateKey(privateKey); } } SHA1 sh = new SHA1CryptoServiceProvider(); return(rsa.SignData(source, sh)); }
/// <summary> /// 生成RSA密钥对 /// </summary> /// <param name="type"></param> /// <param name="size"></param> /// <param name="isPem"></param> /// <returns></returns> public static (string PrivateKey, string PublicKey) GenerateKeyPair(RSAKeyType type = RSAKeyType.Pkcs1, int size = 1024, bool isPem = false) { using var rsa = System.Security.Cryptography.RSA.Create(size); return(rsa.ExportPrivateKey(type, isPem), rsa.ExportPublicKey(type, isPem)); }
public static String Encrypt(String text, ReadOnlySpan <Byte> key, RSAKeyType type = DefaultRSAKeyType, RSAParameters?parameters = null) { using Rsa rsa = Create(key, type, parameters); return(Encrypt(text, rsa)); }
static RSAParameters getRSAPrivateKey(byte[] privkey, RSAKeyType keyType) { if (keyType == RSAKeyType.PKCS8) { privkey = pkcs8ToPkcs1(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 { throw new Exception("转换私钥失败"); } twobytes = binr.ReadUInt16(); if (twobytes != 0x0102) //version number { throw new Exception("转换私钥失败"); } bt = binr.ReadByte(); if (bt != 0x00) { throw new Exception("转换私钥失败"); } //------ 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); 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; return(RSAparams); } catch (Exception ex) { throw ex; } finally { binr.Dispose(); } }
/// <summary> /// 公钥加密 /// </summary> /// <param name="data"></param> /// <param name="type"></param> /// <param name="publicKey"></param> /// <param name="isPem"></param> /// <param name="padding"></param> /// <returns></returns> public static byte[] EncryptWithPublicKey(byte[] data, RSAKeyType type, string publicKey, bool isPem = false, RSAEncryptionPadding padding = null) { using var rsa = System.Security.Cryptography.RSA.Create(); rsa.ImportPublicKey(type, publicKey, isPem); return(Encrypt(rsa, data, padding)); }
/// <summary> /// 私钥解密 /// </summary> /// <param name="encryptedData"></param> /// <param name="type"></param> /// <param name="privateKey"></param> /// <param name="isPem"></param> /// <param name="padding"></param> /// <returns></returns> public static byte[] Decrypt(byte[] encryptedData, RSAKeyType type, string privateKey, bool isPem = false, RSAEncryptionPadding padding = null) { using var rsa = System.Security.Cryptography.RSA.Create(); rsa.ImportPrivateKey(type, privateKey, isPem); return(Decrypt(rsa, encryptedData, padding)); }
/// <summary> /// 初始化一个<see cref="SM2Encryption"/>类型的实例 /// </summary> public SM2Encryption(OutType outType = OutType.Hex, RSAKeyType keyType = RSAKeyType.Xml, Encoding encoding = null) : base(outType, keyType, encoding) { }
/// <summary> /// 使用指定公钥验证解密得到的明文是否符合签名 /// </summary> /// <param name="source">解密得到的明文</param> /// <param name="signData">明文签名字符串</param> /// <param name="publicKey">公钥</param> /// <param name="encoding">编码类型</param> /// <param name="outType">输出类型</param> /// <param name="rsaType">算法类型</param> /// <param name="keyType">密钥类型</param> /// <returns></returns> public static bool VerifyData(string source, string signData, string publicKey, Encoding encoding = null, OutType outType = OutType.Base64, RSAType rsaType = RSAType.RSA, RSAKeyType keyType = RSAKeyType.Xml) { if (encoding == null) { encoding = Encoding.UTF8; } byte[] sourceBytes = encoding.GetBytes(source); byte[] signBytes = signData.GetEncryptBytes(outType); return(VerifyData(sourceBytes, signBytes, publicKey, rsaType, keyType)); }
public static System.Security.Cryptography.RSA CreateRsaFromPrivateKey(string privateKey, RSAKeyType keytype = RSAKeyType.PKCS1) { var privateKeyBits = System.Convert.FromBase64String(privateKey); if (keytype == RSAKeyType.PKCS8) { privateKeyBits = pkcs8ToPkcs1(privateKeyBits); } var rsa = System.Security.Cryptography.RSA.Create(); var RSAparams = new RSAParameters(); using (var binr = new BinaryReader(new MemoryStream(privateKeyBits))) { byte bt = 0; ushort twobytes = 0; twobytes = binr.ReadUInt16(); if (twobytes == 0x8130) { binr.ReadByte(); } else if (twobytes == 0x8230) { binr.ReadInt16(); } else { throw new Exception("Unexpected value read binr.ReadUInt16()"); } twobytes = binr.ReadUInt16(); if (twobytes != 0x0102) { throw new Exception("Unexpected version"); } bt = binr.ReadByte(); if (bt != 0x00) { throw new Exception("Unexpected value read binr.ReadByte()"); } RSAparams.Modulus = binr.ReadBytes(GetIntegerSize(binr)); RSAparams.Exponent = binr.ReadBytes(GetIntegerSize(binr)); RSAparams.D = binr.ReadBytes(GetIntegerSize(binr)); RSAparams.P = binr.ReadBytes(GetIntegerSize(binr)); RSAparams.Q = binr.ReadBytes(GetIntegerSize(binr)); RSAparams.DP = binr.ReadBytes(GetIntegerSize(binr)); RSAparams.DQ = binr.ReadBytes(GetIntegerSize(binr)); RSAparams.InverseQ = binr.ReadBytes(GetIntegerSize(binr)); } rsa.ImportParameters(RSAparams); return(rsa); }