[转]NET实现RSA AES DES 字符串 加密解密以及SHA1 MD5加密
表明来源
https://www.cnblogs.com/shanranlei/p/3630944.html#!comments
本文列举了 数据加密算法(Data Encryption Algorithm,DEA) 密码学中的高级加密标准(Advanced EncryptionStandard,AES)RSA公钥加密算法 的加密解密 .NET实现以及 安全哈希算法(Secure Hash Algorithm)和MD5的实现。
实现如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | #region MD5 /// <summary> /// MD5加密为32字符长度的16进制字符串 /// </summary> /// <paramname="input"></param> /// <returns></returns> public static stringEncryptByMD5( string input) { MD5 md5Hasher = MD5.Create(); byte [] data =md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(input)); StringBuilder sBuilder = newStringBuilder(); //将每个字节转为16进制 for ( int i = 0; i < data.Length;i++) { sBuilder.Append(data[i].ToString( "x2" )); } return sBuilder.ToString(); } #endregion |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #region SHA1 /// <summary> /// SHA1加密 /// </summary> /// <paramname="input"></param> /// <returns></returns> public static stringEncryptBySHA1( string input) { SHA1 sha = new SHA1CryptoServiceProvider(); byte [] bytes =Encoding.Unicode.GetBytes(input); byte [] result =sha.ComputeHash(bytes); returnBitConverter.ToString(result); } #endregion |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 | #region DES //DES默认密钥向量 private static byte [] DES_IV = { 0x12,0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; /// <summary> /// 加密方法 /// </summary> /// <paramname="input"></param> /// <paramname="key"></param> /// <returns></returns> public static stringEncryptByDES( string input, string key) { byte [] inputBytes =Encoding.UTF8.GetBytes(input); //Encoding.UTF8.GetBytes(input); byte [] keyBytes =ASCIIEncoding.UTF8.GetBytes(key); byte [] encryptBytes =EncryptByDES(inputBytes, keyBytes, keyBytes); //string result =Encoding.UTF8.GetString(encryptBytes); //无法解码,其加密结果中文出现乱码:d\"?e????(??uπ?W??-??,_?\nJn7 //原因:如果明文为中文,UTF8编码两个字节标识一个中文字符,但是加密后,两个字节密文,不一定还是中文字符。 using (DES des = newDESCryptoServiceProvider()) { using (MemoryStream ms = newMemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { using (StreamWriterwriter = new StreamWriter(cs)) { writer.Write(inputBytes); } } } } string result =Convert.ToBase64String(encryptBytes); return result; } /// <summary> /// DES加密 /// </summary> /// <paramname="inputBytes">输入byte数组</param> /// <param name="key">密钥,只能是英文字母或数字</param> /// <param name="IV">偏移向量</param> /// <returns></returns> public static byte []EncryptByDES( byte [] inputBytes, byte [] key, byte [] IV) { DES des = newDESCryptoServiceProvider(); //建立加密对象的密钥和偏移量 des.Key = key; des.IV = IV; string result = string .Empty; //1、如果通过CryptoStreamMode.Write方式进行加密,然后CryptoStreamMode.Read方式进行解密,解密成功。 using (MemoryStream ms = newMemoryStream()) { using (CryptoStream cs = newCryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(inputBytes, 0,inputBytes.Length); } return ms.ToArray(); } //2、如果通过CryptoStreamMode.Write方式进行加密,然后再用CryptoStreamMode.Write方式进行解密,可以得到正确结果 //3、如果通过CryptoStreamMode.Read方式进行加密,然后再用CryptoStreamMode.Read方式进行解密,无法解密,Error:要解密的数据的长度无效。 //4、如果通过CryptoStreamMode.Read方式进行加密,然后再用CryptoStreamMode.Write方式进行解密,无法解密,Error:要解密的数据的长度无效。 //using (MemoryStream ms = newMemoryStream(inputBytes)) //{ // using (CryptoStream cs = newCryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Read)) // { // using (StreamReader reader = newStreamReader(cs)) // { // result = reader.ReadToEnd(); // returnEncoding.UTF8.GetBytes(result); // } // } //} } /// <summary> /// 解密 /// </summary> /// <paramname="input"></param> /// <paramname="key"></param> /// <returns></returns> public static stringDecryptByDES( string input, string key) { //UTF8无法解密,Error:要解密的数据的长度无效。 //byte[] inputBytes =Encoding.UTF8.GetBytes(input);//UTF8乱码,见加密算法 byte [] inputBytes =Convert.FromBase64String(input); byte [] keyBytes =ASCIIEncoding.UTF8.GetBytes(key); byte [] resultBytes = DecryptByDES(inputBytes,keyBytes, keyBytes); string result =Encoding.UTF8.GetString(resultBytes); return result; } /// <summary> /// 解密方法 /// </summary> /// <param name="inputBytes"></param> /// <paramname="key"></param> /// <paramname="iv"></param> /// <returns></returns> public static byte []DecryptByDES( byte [] inputBytes, byte [] key, byte [] iv) { DESCryptoServiceProvider des = newDESCryptoServiceProvider(); //建立加密对象的密钥和偏移量,此值重要,不能修改 des.Key = key; des.IV = iv; //通过write方式解密 //using (MemoryStream ms = newMemoryStream()) //{ // using (CryptoStream cs = newCryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) // { // cs.Write(inputBytes, 0,inputBytes.Length); // } // return ms.ToArray(); //} //通过read方式解密 using (MemoryStream ms = newMemoryStream(inputBytes)) { using (CryptoStream cs = newCryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read)) { using (StreamReader reader = newStreamReader(cs)) { string result =reader.ReadToEnd(); returnEncoding.UTF8.GetBytes(result); } } } //错误写法,注意哪个是输出流的位置,如果范围ms,与原文不一致。 //using (MemoryStream ms = newMemoryStream(inputBytes)) //{ // using (CryptoStream cs = newCryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read)) // { // cs.Read(inputBytes, 0,inputBytes.Length); // } // return ms.ToArray(); //} } /// <summary> /// 加密字符串 /// </summary> /// <param name="input"></param> /// <paramname="sKey"></param> /// <returns></returns> public static stringEncryptString( string input, string sKey) { byte [] data =Encoding.UTF8.GetBytes(input); using (DESCryptoServiceProvider des= new DESCryptoServiceProvider()) { des.Key =ASCIIEncoding.ASCII.GetBytes(sKey); des.IV =ASCIIEncoding.ASCII.GetBytes(sKey); ICryptoTransform desencrypt = des.CreateEncryptor(); byte [] result =desencrypt.TransformFinalBlock(data, 0, data.Length); returnBitConverter.ToString(result); } } /// <summary> /// 解密字符串 /// </summary> /// <paramname="input"></param> /// <paramname="sKey"></param> /// <returns></returns> public static stringDecryptString( string input, string sKey) { string [] sInput =input.Split( "-" .ToCharArray()); byte [] data = new byte [sInput.Length]; for ( int i = 0; i <sInput.Length; i++) { data[i] = byte .Parse(sInput[i],NumberStyles.HexNumber); } using (DESCryptoServiceProvider des= new DESCryptoServiceProvider()) { des.Key =ASCIIEncoding.ASCII.GetBytes(sKey); des.IV =ASCIIEncoding.ASCII.GetBytes(sKey); ICryptoTransform desencrypt =des.CreateDecryptor(); byte [] result =desencrypt.TransformFinalBlock(data, 0, data.Length); returnEncoding.UTF8.GetString(result); } } #endregion |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | //AES默认密钥向量 public static readonly byte [] AES_IV ={ 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90,0xAB, 0xCD, 0xEF }; #region AES /// <summary> /// AES加密算法 /// </summary> /// <paramname="input">明文字符串</param> /// <param name="key">密钥</param> /// <returns>字符串</returns> public static stringEncryptByAES( string input, string key) { byte [] keyBytes =Encoding.UTF8.GetBytes(key.Substring(0, 32)); using (AesCryptoServiceProvideraesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = keyBytes; aesAlg.IV = AES_IV; ICryptoTransform encryptor =aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStreamcsEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriterswEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(input); } byte [] bytes =msEncrypt.ToArray(); //returnConvert.ToBase64String(bytes);//此方法不可用 returnBitConverter.ToString(bytes); } } } } /// <summary> /// AES解密 /// </summary> /// <paramname="input">密文字节数组</param> /// <param name="key">密钥</param> /// <returns>返回解密后的字符串</returns> public static stringDecryptByAES( string input, string key) { //byte[] inputBytes =Convert.FromBase64String(input); //Encoding.UTF8.GetBytes(input); string [] sInput =input.Split( "-" .ToCharArray()); byte [] inputBytes = newbyte[sInput.Length]; for ( int i = 0; i <sInput.Length; i++) { inputBytes[i] = byte .Parse(sInput[i], NumberStyles.HexNumber); } byte [] keyBytes =Encoding.UTF8.GetBytes(key.Substring(0, 32)); using (AesCryptoServiceProvideraesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = keyBytes; aesAlg.IV = AES_IV; ICryptoTransform decryptor =aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream(inputBytes)) { using (CryptoStreamcsEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReadersrEncrypt = new StreamReader(csEncrypt)) { returnsrEncrypt.ReadToEnd(); } } } } } /// <summary> /// AES加密 /// </summary> /// <param name="inputdata">输入的数据</param> /// <param name="iv">向量128位</param> /// <param name="strKey">加密密钥</param> /// <returns></returns> public static byte []EncryptByAES( byte [] inputdata, byte [] key, byte [] iv) { ////分组加密算法 //Aes aes = newAesCryptoServiceProvider(); ////设置密钥及密钥向量 //aes.Key = key; //aes.IV = iv; //using (MemoryStream ms = newMemoryStream()) //{ // using (CryptoStream cs = newCryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write)) // { // using (StreamWriter writer = newStreamWriter(cs)) // { // writer.Write(inputdata); // } // return ms.ToArray(); // } //} using (AesCryptoServiceProvideraesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = key; aesAlg.IV = iv; ICryptoTransform encryptor =aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStreamcsEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriterswEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(inputdata); } byte [] encrypted =msEncrypt.ToArray(); return encrypted; } } } } /// <summary> /// AES解密 /// </summary> /// <param name="inputdata">输入的数据</param> /// <param name="key">key</param> /// <param name="iv">向量128</param> /// <returns></returns> public static byte []DecryptByAES( byte [] inputBytes, byte [] key, byte [] iv) { Aes aes = newAesCryptoServiceProvider(); aes.Key = key; aes.IV = iv; byte [] decryptBytes; using (MemoryStream ms = newMemoryStream(inputBytes)) { using (CryptoStream cs = newCryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read)) { using (StreamReader reader= new StreamReader(cs)) { string result =reader.ReadToEnd(); decryptBytes =Encoding.UTF8.GetBytes(result); } } } return decryptBytes; } #endregion |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | #region RSA /// <summary> /// RSA加密 /// </summary> /// <paramname="plaintext">明文</param> /// <paramname="publicKey">公钥</param> /// <returns>密文字符串</returns> public static stringEncryptByRSA( string plaintext, string publicKey) { UnicodeEncoding ByteConverter = newUnicodeEncoding(); byte [] dataToEncrypt =ByteConverter.GetBytes(plaintext); using (RSACryptoServiceProvider RSA= new RSACryptoServiceProvider()) { RSA.FromXmlString(publicKey); byte [] encryptedData =RSA.Encrypt(dataToEncrypt, false ); return Convert.ToBase64String(encryptedData); } } /// <summary> /// RSA解密 /// </summary> /// <paramname="ciphertext">密文</param> /// <paramname="privateKey">私钥</param> /// <returns>明文字符串</returns> public static stringDecryptByRSA( string ciphertext, string privateKey) { UnicodeEncoding byteConverter = newUnicodeEncoding(); using (RSACryptoServiceProvider RSA= new RSACryptoServiceProvider()) { RSA.FromXmlString(privateKey); byte [] encryptedData =Convert.FromBase64String(ciphertext); byte [] decryptedData =RSA.Decrypt(encryptedData, false ); returnbyteConverter.GetString(decryptedData); } } //public static string signByRSA(stringplaintext, string privateKey) //{ // UnicodeEncoding ByteConverter = new UnicodeEncoding(); // byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext); // using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) // { // RSA.FromXmlString(privateKey); // byte[] encryptedData =RSA.SignData(dataToEncrypt,); // return Convert.ToBase64String(encryptedData); // } //} /// <summary> /// 数字签名 /// </summary> /// <paramname="plaintext">原文</param> /// <paramname="privateKey">私钥</param> /// <returns>签名</returns> public static stringHashAndSignString( string plaintext, string privateKey) { UnicodeEncoding ByteConverter = newUnicodeEncoding(); byte [] dataToEncrypt =ByteConverter.GetBytes(plaintext); using (RSACryptoServiceProviderRSAalg = new RSACryptoServiceProvider()) { RSAalg.FromXmlString(privateKey); //使用SHA1进行摘要算法,生成签名 byte [] encryptedData =RSAalg.SignData(dataToEncrypt, new SHA1CryptoServiceProvider()); returnConvert.ToBase64String(encryptedData); } } /// <summary> /// 验证签名 /// </summary> /// <paramname="plaintext">原文</param> /// <paramname="SignedData">签名</param> /// <paramname="publicKey">公钥</param> /// <returns></returns> public static bool VerifySigned(stringplaintext, string SignedData, string publicKey) { using (RSACryptoServiceProviderRSAalg = new RSACryptoServiceProvider()) { RSAalg.FromXmlString(publicKey); UnicodeEncoding ByteConverter = new UnicodeEncoding(); byte [] dataToVerifyBytes =ByteConverter.GetBytes(plaintext); byte [] signedDataBytes =Convert.FromBase64String(SignedData); returnRSAalg.VerifyData(dataToVerifyBytes, new SHA1CryptoServiceProvider(),signedDataBytes); } } /// <summary> /// 获取Key /// 键为公钥,值为私钥 /// </summary> /// <returns></returns> public static KeyValuePair< string , string > CreateRSAKey() { RSACryptoServiceProvider RSA = newRSACryptoServiceProvider(); string privateKey =RSA.ToXmlString( true ); string publicKey =RSA.ToXmlString( false ); return new KeyValuePair< string , string >(publicKey, privateKey); } #endregion |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #region other /// <summary> /// /// </summary> /// <param name="input"></param> /// <returns></returns> public static byte [] GetBytes(stringinput) { string [] sInput =input.Split( "-" .ToCharArray()); byte [] inputBytes = newbyte[sInput.Length]; for ( int i = 0; i <sInput.Length; i++) { inputBytes[i] = byte .Parse(sInput[i], NumberStyles.HexNumber); } return inputBytes; } #endregion |
咩咩咩
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构