.net core使用MD5加密解密字符串
程序员文章站
2024-02-24 22:29:52
本文实例为大家分享了.net core使用md5加密解密字符串的具体代码,供大家参考,具体内容如下
///
/// 加密...
本文实例为大家分享了.net core使用md5加密解密字符串的具体代码,供大家参考,具体内容如下
/// <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); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。