首页 > 作文

C#加密知识整合 (AES,MD5,RSA,SHA256)

更新时间:2023-04-04 14:42:42 阅读: 评论:0

目录
aes 对称加密密钥必须是32字节md5 不可逆加密sha 256 不可逆加密rsa 非对称加密解密

aes 对称加密密钥必须是32字节

using system;using system.curity.cryptography;using system.text;namespace consoleapp1{    public class aes    {        /// <summary>        /// 获取密钥 必须是32字节        /// </summary>        private static string key        {            get { return @"abcdefghijklmnopqrstuvwxyz123456"; }        }        /// <summary>        /// aes加密        /// </summary>        /// <param name="plainstr">明文字符串</param>        /// <returns>密文</returns>        public static string aencrypt(string encryptstr)        {            byte[] keyarray = utf8encoding.utf8.getbytes(key);            byte[] toencryptarray = utf8encoding.utf8.getbytes(encryptstr);            rijndaelmanaged rdel = new rijndaelmanaged();            rdel.key = keyarray;            rdel.mode = ciphermode.ecb;            rdel.padding = paddingmode.pkcs7;            icryptotransform ctra见微知著的近义词nsform = rdel.createencryptor();            byte[] resultarray = ctransform.transformfinalblock(toencryptarray, 0, toencryptarray.length);            return convert.toba64string(resultarray, 0, resultarray.length);        }        public static string aesdencrypt(string encryptstr)        {            byte[] keyarray = utf8encoding.utf8.getbytes(key);            byte[] toencryptarray = convert.fromba64string(encryptstr);            rijndaelmanaged rdel = new rijndaelmanaged();            rdel.key = keyarray;            rdel.mode = ciphermode.ecb;            rdel.padding = paddingmode.pkcs7;            icryptotransform ctransform = rdel.createdecryptor();            byte[] resultarray = ctransform.transformfinalblock(toencryptarray, 0, toencryptarray.length);            return utf8encoding.utf8.getstring(resultarray);        }    }}

调用方式:

 /// aes 对称加密解密            string s = aes.aencrypt("202201131552测试数据");            console.writeline(s);            console.writeline(aes.aesdencrypt(s));            console.writeline("------------------------------------------------------");

md5 不可逆加密

using system;using system.curity.cryptography;namespace consoleapp1{    public class md5helper    {        public static string md5(string str)        {            try            {                md5cryptorviceprovider md5 = new md5cryptorviceprovider();                byte[] bytvalue, bythash;                bytvalue = system.text.encoding.utf8.getbytes(str);                bythash = md5.computehash(bytvalue);                md5.clear();                string stemp = "";                for (int i = 0; i < bythash.length; i++)                {                    stemp += bythash[i].tostring("x").padleft(2, '0');                }                str = stemp.tolower();            }            catch (exception e)            {                console.writeline(e.message);            }            return str;        }    }}

调用方式:

/// md5 不可逆加密            var md5 = md5helper.md5("123456");            console.writeline("------------------------------------------------------");

sha 256 不可逆加密

using system.curity.cryptography;using system.text;namespace consoleapp1{    public class sha256helper    {        /// <summary>        /// sha256加密        /// </summary>        /// <param name="data"></param>        /// <returns></returns>        public static string sha256encryptstring(string data)        {            byte[] bytes = encoding.utf8.getbytes(data);            byte[] hash = sha256managed.create().computehash(bytes);            stringbuilder builder = new stringbuilder();            for (int i = 0; i < hash.length; i++)            {                builder.append(hash[i].tostring("x2"));            }            return builder.tostring();        }    }}

调用方式:

///sha 256 不可逆加密            var sha256 = sha256helper.sha256encryptstring("1111");            console.writeline("------------------------------------------------------");

rsa 非对称加密解密

百度rsa密钥在线生成 /d/file/titlepic/ 填入公私钥到变量publickey, privatekey

using system;using system.io;using system.curity.cryptography;using system.text;namespace consoleapp1{public  class rsapkcs8helper{/// <summary>/// 签名/// </summary>/// <param name="content">待签名字符串</param>/// <param name="privatekey">私钥</param>/// <param name="input_chart">编码格式</param>/// <returns>签名后字符串</returns>public static string sign(string content, string privatekey, string input_chart){byte[] data = encoding.getencoding(input_chart).getbytes(content);rsacryptorviceprovider rsa = decodepemprivatekey(privatekey);            //md5 sh = new md5cryptorviceprovider();//这里也可以使用md5加密方式sha1 sh = new sha1cryptorviceprovider();byte[] signdata = rsa.signdata(data, sh);return convert.toba64string(signdata);}/// <summary>/// 验签/// </summary>/// <param name="content">待验签字符串</param>/// <param name="signedstring">签名</param>/// <param name="publickey">公钥</param>/// <param name="input_chart">编码格式</param>/// <returns>true(通过),fal(不通过)</returns>public static bool verify(string content, string signedstring, string publickey, string input_chart){bool result = fal;byte[] data = encoding.getencoding(input_chart).getbytes(content);byte[] data = convert.fromba64string(signedstring);rsaparameters parapub = convertfrompublickey(publickey);rsacryptorviceprovider rsapub = new rsacryptorviceprovider();rsapub.importparameters(parapub);            //md5 sh = new md5cryptorviceprovider();//这里可以使用md5加密方式sha1 sh = new sha1cryptorviceprovider();result = rsapub.verifydata(data, sh, data);return result;}/// <summary>/// 加密/// </summary>/// <param name="resdata">需要加密的字符串</param>/// <param name="publickey">公钥</param>/// <param name="input_chart">编码格式</param>/// <returns>明文</returns>public static string encryptdata(string resdata, string publickey, string input_chart){byte[] datatoencrypt = encoding.getencoding(input_chart).getbytes(resdata);string result = encrypt(datatoencrypt, publickey, input_chart);return result;}/// <summary>/// 解密/// </summary>/// <param name="resdata">加密字符串</param>/// <param name="privatekey">私钥</param>/// <param name="input_chart">编码格式</param>/// <returns>明文</returns>public static string decryptdata(string resdata, string privatekey, string input_chart){byte[] datatodecrypt = convert.fromba64string(resdata);string result = "";for (int j = 0; j < datatodecrypt.length / 128; j++){byte[] buf = new byte[128];for (int i = 0; i < 128; i++){buf[i] = datatodecrypt[i + 128 * j];}result += decrypt(buf, privatekey, input_chart);}return result;}#region 内部方法private static string encrypt(byte[] data, string publickey, string input_chart){rsacryptorviceprovider rsa = decodepempublickey(publickey);            //md5 sh = new md5cryptorviceprovider();//这里也可以使用md5加密方式sha1 sh = new sha1cryptorviceprovider();byte[] result = rsa.encrypt(data, fal);return convert.toba64string(result);}private static string decrypt(byte[] data, string privatekey, string input_chart){string result = "";rsacryptorviceprovider rsa = decodepemprivatekey(privatekey);            //md5 sh = new md5cryptorviceprovider();//这里也可以替换使用md5方式sha1 sh = new sha1cryptorviceprovider();byte[] source = rsa.decrypt(data, fal);char[] asciichars = new char[encoding.getencoding(input_chart).getcharcount(source, 0, source.length)];encoding.getencoding(input_chart).getchars(source, 0, source.length, asciichars, 0);result = new string(asciichars);//result = asciiencoding.ascii.getstring(source);return result;}private static rsacryptorviceprovider decodepempublickey(string pemstr){byte[] pkcs8publickkey;pkcs8publickkey = convert.fromba64string(pemstr);if (pkcs8publickkey != null){rsacryptorviceprovider rsa = decodersapublickey(pkcs8publickkey);return rsa;}elreturn null;}private static rsacryptorviceprovider decodepemprivatekey(string pemstr){byte[] pkcs8privatekey;pkcs8privatekey = convert.fromba64string(pemstr);if (pkcs8privatekey != null){rsacryptorviceprovider rsa = decodeprivatekeyinfo(pkcs8privatekey);return rsa;}elreturn null;}private static rsacryptorviceprovider decodeprivatekeyinfo(byte[] pkcs8){byte[] qoid = { 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00 };byte[] q = new byte[15];memorystream mem = new memorystream(pkcs8);int lenstream = (int)mem.length;bina40周年ryreader binr = new binaryreader(mem);    //wrap memory stream with binaryreader for easy readingbyte bt = 0;ushort twobytes = 0;try{twobytes = binr.readuint16();if (twobytes == 0x8130)    //data read as little endian order (actual data order for quence is 30 81)binr.readbyte();    //advance 1 byteel if (twobytes == 0x8230)binr.readint16();    //advance 2 bytelreturn null;bt = binr.readbyte();if (bt != 0x02)return null;twobytes = binr.readuint16();if (twobytes != 0x0001)return null;q = binr.readbytes(15);        //read the quence oidif (!comparebytearrays(q, qoid))    //make sure quence for oid is correctreturn null;bt = binr.readbyte();if (bt != 0x04)    //expect an octet stringreturn null;bt = binr.readbyte();        //read next byte, or next 2 bytes is  0x81 or 0x82; otherwi bt is the byte countif (bt == 0x81)binr.readbyte();elif (bt == 0x82)binr.readuint16();//------ at this stage, the remaining quence should be the rsa private keybyte[] rsaprivkey = binr.readbytes((int)(lenstream - mem.position));rsacryptorviceprovider rsacsp = decodersaprivatekey(rsaprivkey);return1992年农历表 rsacsp;}catch (exception){return null;}finally { binr.clo(); }}private static bool comparebytearrays(byte[] a, byte[] b){if (a.length != b.length)return fal;int i = 0;foreach (byte c in a){if (c != b[i])return fal;i++;}return true;}private static rsacryptorviceprovider decodersapublickey(byte[] publickey){// encoded oid quence for  pkcs #1 rsaencryption szoid_rsa_rsa = "1.2.840.113549.1.1.1"byte[] qoid = { 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00 };byte[] q = new byte[15];// ---------  t up stream to read the asn.1 encoded subjectpublickeyinfo blob  ------memorystream mem = new memorystream(publickey);binaryreader binr = new binaryreader(mem);    //wrap memory stream with binaryreader for easy readingbyte bt = 0;ushort twobytes = 0;try{twobytes = binr.readuint16();if (twobytes == 0x8130) //data read as little endian order (actual data order for quence is 30 81)b反比例函数性质inr.readbyte();    //advance 1 byteel if (twobytes == 0x8230)binr.readint16();   //advance 2 bytelreturn null;q = binr.readbytes(15);       //read the quence oidif (!comparebytearrays(q, qoid))    //make sure quence for oid is correctreturn null;twobytes = binr.readuint16();if (twobytes == 0x8103) //data read as little endian order (actual data order for bit string is 03 81)binr.readbyte();    //advance 1 byteel if (twobytes == 0x8203)binr.readint16();   //advance 2 bytelreturn null;bt = binr.readbyte();if (bt != 0x00)     //expect null byte nextreturn null;twobytes = binr.readuint16();if (twobytes == 0x8130) //data read as little endian order (actual data order for quence is 30 81)binr.readbyte();    //advance 1 byteel if (twobytes == 0x8230)binr.readint16();   //advance 2 bytelreturn null;twobytes = binr.readuint16();byte lowbyte = 0x00;byte highbyte = 0x00;if (twobytes == 0x8102) //data read as little endian order (actual data order for integer is 02 81)lowbyte = binr.readbyte();  // read next bytes which is bytes in modulul if (twobytes == 0x8202){highbyte = binr.readbyte(); //advance 2 byteslowbyte = binr.readbyte();}elreturn null;byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };   //rever byte order since asn.1 key us big endian orderint modsize = bitconverter.toint32(modint, 0);byte firstbyte = binr.readbyte();binr.bastream.ek(-1, ekorigin.current);if (firstbyte == 0x00){   //if first byte (highest order) of modulus is zero, don't include itbinr.readbyte();    //skip this null bytemodsize -= 1;   //reduce modulus buffer size by 1}byte[] modulus = binr.readbytes(modsize);   //read the modulus bytesif (binr.readbyte() != 0x02)            //expect an integer for the exponent datareturn null;int expbytes = (int)binr.readbyte();        // should only need one byte for actual exponent data (for all uful values)byte[] exponent = binr.readbytes(expbytes);// ------- create rsacryptorviceprovider instance and initialize with public key -----rsacryptorviceprovider rsa = new rsacryptorviceprovider();rsaparameters rsakeyinfo = new rsaparameters();rsakeyinfo.modulus = modulus;rsakeyinfo.exponent = exponent;rsa.importparameters(rsakeyinfo);return rsa;}catch (exception){return null;}finally { binr.clo(); }}private static rsacryptorviceprovider decodersaprivatekey(byte[] privkey){byte[] modulus, e, d, p, q, dp, dq, iq;// ---------  t up stream to decode the asn.1 encoded rsa private key  ------memorystream mem = new memorystream(privkey);binaryreader binr = new binaryreader(mem);    //wrap memory stream with binaryreader for easy readingbyte bt = 0;ushort twobytes = 0;int elems = 0;try{twobytes = binr.readuint16();if (twobytes == 0x8130)    //data read as little endian order (actual data order for quence is 30 81)binr.readbyte();    //advance 1 byteel if (twobytes == 0x8230)binr.readint16();    //advance 2 bytelreturn null;twobytes = binr.readuint16();if (twobytes != 0x0102)    //version numberreturn null;bt = binr.readbyte();if (bt != 0x00)return null;//------  all private key components are integer quences ----elems = getintegersize(binr);modulus = binr.readbytes(elems);elems = getintegersize(binr);e = binr.readbytes(elems);elems = getintegersize(binr);d = binr.readbytes(elems);elems = getintegersize(binr);p = binr.readbytes(elems);elems = getintegersize(binr);q = binr.readbytes(elems);elems = getintegersize(binr);dp = binr.readbytes(elems);elems = getintegersize(binr);dq = binr.readbytes(elems);elems = getintegersize(binr);iq = binr.readbytes(elems);// ------- create rsacryptorviceprovider instance and initialize with public key -----rsacryptorviceprovider rsa = new rsacryptorviceprovider();rsaparameters rsaparams = new rsaparameters();rsaparams.modulus = modulus;rsaparams.exponent = e;rsaparams.d = d;rsaparams.p = p;rsaparams.q = q;rsaparams.dp = dp;rsaparams.dq = dq;rsaparams.inverq = iq;rsa.importparameters(rsaparams);return rsa;}catch (exception){return null;}finally { binr.clo(); }}private static int getintegersize(binaryreader binr){byte bt = 0;byte lowbyte = 0x00;byte highbyte = 0x00;int count = 0;bt = binr.readbyte();if (bt != 0x02)        //expect integerreturn 0;bt = binr.readbyte();if (bt == 0x81)count = binr.readbyte();    // data size in next byteelif (bt == 0x82){highbyte = binr.readbyte();    // data size in next 2 byteslowbyte = binr.readbyte();byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };count = bitconverter.toint32(modint, 0);}el{count = bt;        // we already have the data size}while (binr.readbyte() == 0x00){    //remove high order zeros in datacount -= 1;}binr.bastream.ek(-1, ekorigin.current);        //last readbyte wasn't a removed zero, so back up a bytereturn count;}#endregion#region 解析.net 生成的pemprivate static rsaparameters convertfrompublickey(string pemfileconent){byte[] keydata = convert.fromba64string(pemfileconent);if (keydata.length < 162){throw new argumentexception("pem file content is incorrect.");}byte[] pemmodulus = new byte[128];byte[] pempublicexponent = new byte[3];array.copy(keydata, 29, pemmodulus, 0, 128);array.copy(keydata, 159, pempublicexponent, 0, 3);rsaparameters para = new rsaparameters();para.modulus = pemmodulus;para.exponent = pempublicexponent;return para;}private static rsaparameters convertfromprivatekey(string pemfileconent){byte[] keydata = convert.fromba64string(pemfileconent);if (keydata.length < 609){throw new argumentexception("pem file content is incorrect.");}int index = 11;byte[] pemmodulus = new byte[128];array.copy(keydata, index, pemmodulus, 0, 128);index += 128;index += 2;//141byte[] pempublicexponent = new byte[3];array.copy(keydata, index, pempublicexponent, 0, 3);index += 3;index += 4;//148byte[] pemprivateexponent = new byte[128];array.copy(keydata, index, pemprivateexponent, 0, 128);index += 128;index += ((int)keydata[index + 1] == 64 ? 2 : 3);//279byte[] pemprime1 = new byte[64];array.copy(keydata, index, pemprime1, 0, 64);index += 64;index += ((int)keydata[index + 1] == 64 ? 2 : 3);//346byte[] pemprime2 = new byte[64];array.copy(keydata, index, pemprime2, 0, 64);index += 64;index += ((int)keydata[index + 1] == 64 ? 2 : 3);//412/413byte[] pemexponent1 = new byte[64];array.copy(keydata, index, pemexponent1, 0, 64);index += 64;index += ((int)keydata[index + 1] == 64 ? 2 : 3);//479/480byte[] pemexponent2 = new byte[64];array.copy(keydata, index, pemexponent2, 0, 64);index += 64;index += ((int)keydata[index + 1] == 64 ? 2 : 3);//545/546byte[] pemcoefficient = new byte[64];array.copy(keydata, index, pemcoefficient, 0, 64);rsaparameters para = new rsaparameters();para.modulus = pemmodulus;para.exponent = pempublicexponent;para.d = pemprivateexponent;para.p = pemprime1;para.q = pemprime2;para.dp = pemexponent1;para.dq = pemexponent2;para.inverq = pemcoefficient;return para;}#endregion}}

调用方式:

string publickey = "";string privatekey = "";publickey = "migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqddla7of0h4g+waatofcdmldp4dbcc161jcsr0t+xlmsceiglfhtoh4+htcwspvkhwzto9shywwootqgpfl1lblg+rhbxtbmq1m+havvkscbbdz3xs6ngumssktw+q+9rytgor+lngsjhf7hnatj6qyv1ouyiiap4oi1slpmqdidwidaqab";privatekey = "miicdgibadanbgkqhkig9w0baqefaascamawggjcageaaogbammsds5/qfid5zoboguj2ysm/gnsjzxrulxkvs35euxiiskcuwfm6hj4e0jzkluqhdnm71kfjbaihooal+xutsud5gefe1syruz4dpvwsxxtsppfflqebqyyys3d5d72ti0aiv6u0zikcxdpmnpdk/whriihqniilwws8xamgpagmbaaecgybafoxmhahfh79+/iya42syfe77rtyuuirwuvkoqzi6zkjwjpcohqrn017kby66v5dflcjtwk+pmwagzhey3lt1bqtyvkcjzs6ob+nnimzsqbuaixkdcs9tddv+p40dffyatmihy/7vivet0fcfrzpmo0ku9+m5mc8s7qyvyio8mqjbap6a0uu/jpk3irho1b1o52antnnwk0q7mkwfp/oomexkksajh0ubrkm6kdtf9p41h361m4gdwl2wxkn8v792e8kcqqdepdulllt95pd721wavzea8cbtyn+nao++auutv8usz8zydsuqd5lr8dyh4izvyxwyl8zsf5w6xikwi2gueoexakea8dtljpaci++uipy1ya3nv1ncwosfo79mn1zro2jdromgkkn2mtj9apjvcuguzjfbmdeyt6mg5exjnycddm+rcqjacqo8cwigw8fir+fb字谜及答案/1ntsb/zjqmecxxih0h3on2zm3bapw/taq58+yechwbltfkuyyajdyesozaftbr70ptucwjatib2krfwcztma5eo07/r2lpspiqfkmefpskkx81ymcxtz/outsoo/b6o0k+w6gdwxb9/nismzigv4vbgfn6qnq==";//加密字符串string data = "202201131819gao";console.writeline("原始:" + data);//加密string encrypteddata = rsapkcs8helper.encryptdata(data, publickey, "utf-8");console.writeline("加密:" + encrypteddata);console.writeline("解密:" + rsapkcs8helper.decryptdata(encrypteddata, privatekey, "utf-8"));console.writeline("------------------------------------------------------");//解密string endata = "wi8eyavwoasyyjgwn8r9sxsvw18dmzmlsy4crwxotmqhbpce6iwgyozes4qorpdkdppphdepfmypqzps2bx84bvpohoejkkqs2te0heutk0rmx76ltufpr51slqe+tqmdbkyoajrb2olga1sqtc+udpza1tbofb5v/+5mb5o8=";string datamw = rsapkcs8helper.decryptdata(endata, privatekey, "utf-8");console.writeline("提前获知解密:" + datamw);

到此这篇关于c#对于加密的一点整合 (aes,md5,rsa,sha256)的文章就介绍到这了,更多相关c#加密内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!

本文发布于:2023-04-04 14:42:40,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/202063bcbc7d1628ee665fb53b346cf2.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:C#加密知识整合 (AES,MD5,RSA,SHA256).doc

本文 PDF 下载地址:C#加密知识整合 (AES,MD5,RSA,SHA256).pdf

标签:字符串   方式   密钥   明文
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图