.net core 使用MD5加密解密字符串
程序员文章站
2022-05-06 12:34:31
调用加密 解密看效果 ......
/// <summary> /// 加密 /// </summary> /// <param name="text">要加密的文本</param> /// <param name="skey">秘钥</param> /// <returns></returns> public static string encrypt(string text, string skey="test") { descryptoserviceprovider des = new descryptoserviceprovider(); byte[] inputbytearray; inputbytearray = encoding.default.getbytes(text); des.key = asciiencoding.ascii.getbytes(md5hash(skey).substring(0,8)); des.iv = asciiencoding.ascii.getbytes(md5hash(skey).substring(0, 8)); system.io.memorystream ms = new system.io.memorystream(); cryptostream cs = new cryptostream(ms, des.createencryptor(), cryptostreammode.write); cs.write(inputbytearray, 0, inputbytearray.length); cs.flushfinalblock(); stringbuilder ret = new stringbuilder(); foreach (byte b in ms.toarray()) { ret.appendformat("{0:x2}", b); } md4j= ret.tostring(); return ret.tostring(); }
/// <summary> /// 解密 /// </summary> /// <param name="text"></param> /// <param name="skey"></param> /// <returns></returns> public static string decrypt(string text, string skey = "test") { descryptoserviceprovider des = new descryptoserviceprovider(); int len; len = text.length / 2; byte[] inputbytearray = new byte[len]; int x, i; for (x = 0; x < len; x++) { i = convert.toint32(text.substring(x * 2, 2), 16); inputbytearray[x] = (byte)i; } des.key = asciiencoding.ascii.getbytes(md5hash(skey).substring(0, 8)); des.iv = asciiencoding.ascii.getbytes(md5hash(skey).substring(0, 8)); system.io.memorystream ms = new system.io.memorystream(); cryptostream cs = new cryptostream(ms, des.createdecryptor(), cryptostreammode.write); cs.write(inputbytearray, 0, inputbytearray.length); cs.flushfinalblock(); return encoding.default.getstring(ms.toarray()); }
/// <summary> /// 32位md5加密 /// </summary> /// <param name="input"></param> /// <returns></returns> private static string md5hash(string input) { md5cryptoserviceprovider md5hasher = new md5cryptoserviceprovider(); byte[] data = md5hasher.computehash(encoding.default.getbytes(input)); stringbuilder sbuilder = new stringbuilder(); for (int i = 0; i < data.length; i++) { sbuilder.append(data[i].tostring("x2")); } return sbuilder.tostring(); }
调用加密 解密看效果
public static string md4j = ""; static void main(string[] args) { //加密 encrypt("123456"); decrypt(md4j); }
上一篇: NETCore调用AD域验证
下一篇: 记关于内存泄漏的理解与学习