部分代码来至 https://www.cnblogs.com/dj258/p/6049786.html
1using System; 2using System.Collections.Generic; 3using System.Linq; 4using System.Text; 5 6using Org.BouncyCastle.Asn1.Pkcs; 7using Org.BouncyCastle.Asn1.X509; 8using Org.BouncyCastle.Crypto.Generators; 9using Org.BouncyCastle.Crypto.Parameters; 10using Org.BouncyCastle.Math; 11using Org.BouncyCastle.Pkcs; 12using Org.BouncyCastle.Security; 13using Org.BouncyCastle.Crypto.Engines; 14using Org.BouncyCastle.X509; 15using Org.BouncyCastle.Crypto; 16using Org.BouncyCastle.Asn1; 17using Org.BouncyCastle.Crypto.Encodings; 18using System.IO; 19namespace Tool 20{ 21 public class RSATool 22 { 23 24 public RSATool() 25 { 26 27 } 28 /// <summary> 29 /// KEY 结构体 30 /// </summary> 31 public struct RSAKEY 32 { 33 /// <summary> 34 /// 公钥 35 /// </summary> 36 public string PublicKey 37 { 38 get; 39 set; 40 } 41 /// <summary> 42 /// 私钥 43 /// </summary> 44 public string PrivateKey 45 { 46 get; 47 set; 48 } 49 } 50 public RSAKEY GetKey() 51 { 52 //RSA密钥对的构造器 53 RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator(); 54 55 //RSA密钥构造器的参数 56 RsaKeyGenerationParameters param = new RsaKeyGenerationParameters( 57 Org.BouncyCastle.Math.BigInteger.ValueOf(3), 58 new Org.BouncyCastle.Security.SecureRandom(), 59 1024, //密钥长度 60 25); 61 //用参数初始化密钥构造器 62 keyGenerator.Init(param); 63 //产生密钥对 64 AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair(); 65 //获取公钥和密钥 66 AsymmetricKeyParameter publicKey = keyPair.Public; 67 AsymmetricKeyParameter privateKey = keyPair.Private; 68 69 SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); 70 PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey); 71 72 73 Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object(); 74 75 byte[] publicInfoByte = asn1ObjectPublic.GetEncoded("UTF-8"); 76 Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object(); 77 byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded("UTF-8"); 78 79 RSAKEY item = new RSAKEY() 80 { 81 PublicKey = Convert.ToBase64String(publicInfoByte), 82 PrivateKey = Convert.ToBase64String(privateInfoByte) 83 }; 84 return item; 85 } 86 private AsymmetricKeyParameter GetPublicKeyParameter(string s) 87 { 88 s = s.Replace("\r", "").Replace("\n", "").Replace(" ", ""); 89 byte[] publicInfoByte = Convert.FromBase64String(s); 90 Asn1Object pubKeyObj = Asn1Object.FromByteArray(publicInfoByte);//这里也可以从流中读取,从本地导入 91 AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(publicInfoByte); 92 return pubKey; 93 } 94 private AsymmetricKeyParameter GetPrivateKeyParameter(string s) 95 { 96 s = s.Replace("\r", "").Replace("\n", "").Replace(" ", ""); 97 byte[] privateInfoByte = Convert.FromBase64String(s); 98 // Asn1Object priKeyObj = Asn1Object.FromByteArray(privateInfoByte);//这里也可以从流中读取,从本地导入 99 // PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey); 100 AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(privateInfoByte); 101 return priKey; 102 } 103 public string EncryptByKey(string s, string key, bool isPublic) 104 { 105 //非对称加密算法,加解密用 106 IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine()); 107 //加密 108 try 109 { 110 engine.Init(true, isPublic ? GetPublicKeyParameter(key) : GetPrivateKeyParameter(key)); 111 byte[] byteData = System.Text.Encoding.UTF8.GetBytes(s); 112 113 int inputLen = byteData.Length; 114 MemoryStream ms = new MemoryStream(); 115 int offSet = 0; 116 byte[] cache; 117 int i = 0; 118 // 对数据分段加密 119 while (inputLen - offSet > 0) 120 { 121 if (inputLen - offSet > 117) 122 { 123 cache = engine.ProcessBlock(byteData, offSet, 117); 124 } 125 else 126 { 127 cache = engine.ProcessBlock(byteData, offSet, inputLen - offSet); 128 } 129 ms.Write(cache, 0, cache.Length); 130 i++; 131 offSet = i * 117; 132 } 133 byte[] encryptedData = ms.ToArray(); 134 135 //var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length); 136 return Convert.ToBase64String(encryptedData); 137 //Console.WriteLine("密文(base64编码):" + Convert.ToBase64String(testData) + Environment.NewLine); 138 } 139 catch (Exception ex) 140 { 141 return ex.Message; 142 143 } 144 } 145 /// <summary> 146 /// 解密 147 /// </summary> 148 /// <param name="s"></param> 149 /// <param name="key"></param> 150 /// <param name="isPublic"></param> 151 /// <returns></returns> 152 public string DecryptByPublicKey(string s, string key, bool isPublic) 153 { 154 s = s.Replace("\r", "").Replace("\n", "").Replace(" ", ""); 155 //非对称加密算法,加解密用 156 IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine()); 157 158 159 //加密 160 161 try 162 { 163 engine.Init(false, isPublic ? GetPublicKeyParameter(key) : GetPrivateKeyParameter(key)); 164 byte[] byteData = Convert.FromBase64String(s); 165 166 int inputLen = byteData.Length; 167 MemoryStream ms = new MemoryStream(); 168 int offSet = 0; 169 byte[] cache; 170 int i = 0; 171 // 对数据分段加密 172 while (inputLen - offSet > 0) 173 { 174 if (inputLen - offSet > 128) 175 { 176 cache = engine.ProcessBlock(byteData, offSet, 128); 177 } 178 else 179 { 180 cache = engine.ProcessBlock(byteData, offSet, inputLen - offSet); 181 } 182 ms.Write(cache, 0, cache.Length); 183 i++; 184 offSet = i * 128; 185 } 186 byte[] encryptedData = ms.ToArray(); 187 188 //var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length); 189 return Encoding.UTF8.GetString(ms.ToArray()); 190 //Console.WriteLine("密文(base64编码):" + Convert.ToBase64String(testData) + Environment.NewLine); 191 } 192 catch (Exception ex) 193 { 194 return ex.Message; 195 196 } 197 } 198 /// <summary> 199 /// 签名 200 /// </summary> 201 /// <param name="data">数据</param> 202 /// <param name="key">密匙</param> 203 /// <returns></returns> 204 public string SignByPrivateKey(string data, string key) 205 { 206 AsymmetricKeyParameter priKey = GetPrivateKeyParameter(key); 207 byte[] byteData = System.Text.Encoding.UTF8.GetBytes(data); 208 209 ISigner normalSig = SignerUtilities.GetSigner("SHA1WithRSA"); 210 normalSig.Init(true, priKey); 211 normalSig.BlockUpdate(byteData, 0, data.Length); 212 byte[] normalResult = normalSig.GenerateSignature(); //签名结果 213 return Convert.ToBase64String(normalResult); 214 //return System.Text.Encoding.UTF8.GetString(normalResult); 215 } 216 217 /// <summary> 218 /// 验签 219 /// </summary> 220 /// <param name="plainData">验证数据</param> 221 /// <param name="sign">签名</param> 222 /// <param name="key">公匙</param> 223 /// <returns></returns> 224 public bool ValidationPublicKey(string plainData, string sign, string key) 225 { 226 AsymmetricKeyParameter priKey = GetPublicKeyParameter(key); 227 228 byte[] signBytes = Convert.FromBase64String(sign); 229 byte[] plainBytes = Encoding.UTF8.GetBytes(plainData); 230 231 232 ISigner verifier = SignerUtilities.GetSigner("SHA1WithRSA"); 233 verifier.Init(false, priKey); 234 verifier.BlockUpdate(plainBytes, 0, plainBytes.Length); 235 236 return verifier.VerifySignature(signBytes); //验签结果 237 } 238 } 239}
亲测可用