TripleDESCryptoServiceProvider CryptoStream
程序员文章站
2022-04-11 08:35:05
using System.Security.Cryptography; static void Main(string[] args) { string rawString = "Make every second count."; string encryptedString = Encrypt3 ......
using system.security.cryptography; static void main(string[] args) { string rawstring = "make every second count."; string encryptedstring = encrypt3des(rawstring); string decryptedstring = decrypt3des(encryptedstring); console.writeline($"raw:{rawstring}\nencrypted:{encryptedstring}\ndecrypted:{decryptedstring}"); console.readline(); } public static string encrypt3des(string rawstring, string encryptkey = "serenityserenityserenityserenity", string encryptiv = "04d4da042de=") { using (symmetricalgorithm tripledesprovider = new tripledescryptoserviceprovider()) { try { tripledesprovider.key = convert.frombase64string(encryptkey); tripledesprovider.iv = convert.frombase64string(encryptiv); tripledesprovider.mode = system.security.cryptography.ciphermode.cbc; tripledesprovider.padding = system.security.cryptography.paddingmode.pkcs7; using (icryptotransform ct = tripledesprovider.createencryptor(tripledesprovider.key, tripledesprovider.iv)) { byte[] bytes = encoding.utf8.getbytes(rawstring); using (memorystream ms = new memorystream()) { using (cryptostream cs = new cryptostream(ms, ct, cryptostreammode.write)) { cs.write(bytes, 0, bytes.length); cs.flushfinalblock(); cs.close(); string result = convert.tobase64string(ms.toarray()); return result; } } } } catch (exception ex) { throw; } } } public static string decrypt3des(string rawstring, string encryptkey = "serenityserenityserenityserenity", string encryptiv = "04d4da042de=") { using (symmetricalgorithm tripledesprovider = new tripledescryptoserviceprovider()) { try { tripledesprovider.key = convert.frombase64string(encryptkey); tripledesprovider.iv = convert.frombase64string(encryptiv); tripledesprovider.mode = system.security.cryptography.ciphermode.cbc; tripledesprovider.padding = system.security.cryptography.paddingmode.pkcs7; using (icryptotransform ct = tripledesprovider.createdecryptor(tripledesprovider.key, tripledesprovider.iv)) { byte[] bytes = convert.frombase64string(rawstring); using (memorystream ms = new memorystream()) { using (cryptostream cs = new cryptostream(ms, ct, cryptostreammode.write)) { cs.write(bytes, 0, bytes.length); cs.flushfinalblock(); cs.close(); string result = encoding.utf8.getstring(ms.toarray()); return result; } } } } catch (exception ex) { throw; } } }
上一篇: 小程序导航栏跟随滑动