欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-16 12:50:11
目录aes 对称加密密钥必须是32字节md5 不可逆加密sha 256 不可逆加密rsa 非对称加密解密aes 对称加密密钥必须是32字节using system;using system.secur...

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

using system;
using system.security.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 aesencrypt(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 ctransform = rdel.createencryptor();
            byte[] resultarray = ctransform.transformfinalblock(toencryptarray, 0, toencryptarray.length);
            return convert.tobase64string(resultarray, 0, resultarray.length);
        }
        public static string aesdencrypt(string encryptstr)
        {
            byte[] keyarray = utf8encoding.utf8.getbytes(key);
            byte[] toencryptarray = convert.frombase64string(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.aesencrypt("202201131552测试数据");
            console.writeline(s);
            console.writeline(aes.aesdencrypt(s));
            console.writeline("------------------------------------------------------");

md5 不可逆加密

using system;
using system.security.cryptography;
namespace consoleapp1
{
    public class md5helper
    {
        public static string md5(string str)
        {
            try
            {
                md5cryptoserviceprovider md5 = new md5cryptoserviceprovider();
                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.security.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密钥在线生成 http://web.chacuo.net/netrsakeypair/ 填入公私钥到变量publickey, privatekey

using system;
using system.io;
using system.security.cryptography;
using system.text;
namespace consoleapp1
{
    public  class rsapkcs8helper
    {
        /// <summary>
        /// 签名
        /// </summary>
        /// <param name="content">待签名字符串</param>
        /// <param name="privatekey">私钥</param>
        /// <param name="input_charset">编码格式</param>
        /// <returns>签名后字符串</returns>
        public static string sign(string content, string privatekey, string input_charset)
        {
            byte[] data = encoding.getencoding(input_charset).getbytes(content);
            rsacryptoserviceprovider rsa = decodepemprivatekey(privatekey);            //md5 sh = new md5cryptoserviceprovider();//这里也可以使用md5加密方式
            sha1 sh = new sha1cryptoserviceprovider();
            byte[] signdata = rsa.signdata(data, sh);
            return convert.tobase64string(signdata);
        }
        /// <summary>
        /// 验签
        /// </summary>
        /// <param name="content">待验签字符串</param>
        /// <param name="signedstring">签名</param>
        /// <param name="publickey">公钥</param>
        /// <param name="input_charset">编码格式</param>
        /// <returns>true(通过),false(不通过)</returns>
        public static bool verify(string content, string signedstring, string publickey, string input_charset)
        {
            bool result = false;
            byte[] data = encoding.getencoding(input_charset).getbytes(content);
            byte[] data = convert.frombase64string(signedstring);
            rsaparameters parapub = convertfrompublickey(publickey);
            rsacryptoserviceprovider rsapub = new rsacryptoserviceprovider();
            rsapub.importparameters(parapub);            //md5 sh = new md5cryptoserviceprovider();//这里可以使用md5加密方式
            sha1 sh = new sha1cryptoserviceprovider();
            result = rsapub.verifydata(data, sh, data);
            return result;
        }
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="resdata">需要加密的字符串</param>
        /// <param name="publickey">公钥</param>
        /// <param name="input_charset">编码格式</param>
        /// <returns>明文</returns>
        public static string encryptdata(string resdata, string publickey, string input_charset)
        {
            byte[] datatoencrypt = encoding.getencoding(input_charset).getbytes(resdata);
            string result = encrypt(datatoencrypt, publickey, input_charset);
            return result;
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="resdata">加密字符串</param>
        /// <param name="privatekey">私钥</param>
        /// <param name="input_charset">编码格式</param>
        /// <returns>明文</returns>
        public static string decryptdata(string resdata, string privatekey, string input_charset)
        {
            byte[] datatodecrypt = convert.frombase64string(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_charset);
            }
            return result;
        }
        #region 内部方法
        private static string encrypt(byte[] data, string publickey, string input_charset)
        {
            rsacryptoserviceprovider rsa = decodepempublickey(publickey);            //md5 sh = new md5cryptoserviceprovider();//这里也可以使用md5加密方式
            sha1 sh = new sha1cryptoserviceprovider();
            byte[] result = rsa.encrypt(data, false);
            return convert.tobase64string(result);
        }
        private static string decrypt(byte[] data, string privatekey, string input_charset)
        {
            string result = "";
            rsacryptoserviceprovider rsa = decodepemprivatekey(privatekey);            //md5 sh = new md5cryptoserviceprovider();//这里也可以替换使用md5方式
            sha1 sh = new sha1cryptoserviceprovider();
            byte[] source = rsa.decrypt(data, false);
            char[] asciichars = new char[encoding.getencoding(input_charset).getcharcount(source, 0, source.length)];
            encoding.getencoding(input_charset).getchars(source, 0, source.length, asciichars, 0);
            result = new string(asciichars);
            //result = asciiencoding.ascii.getstring(source);
            return result;
        }
        private static rsacryptoserviceprovider decodepempublickey(string pemstr)
        {
            byte[] pkcs8publickkey;
            pkcs8publickkey = convert.frombase64string(pemstr);
            if (pkcs8publickkey != null)
            {
                rsacryptoserviceprovider rsa = decodersapublickey(pkcs8publickkey);
                return rsa;
            }
            else
                return null;
        }
        private static rsacryptoserviceprovider decodepemprivatekey(string pemstr)
        {
            byte[] pkcs8privatekey;
            pkcs8privatekey = convert.frombase64string(pemstr);
            if (pkcs8privatekey != null)
            {
                rsacryptoserviceprovider rsa = decodeprivatekeyinfo(pkcs8privatekey);
                return rsa;
            }
            else
                return null;
        }
        private static rsacryptoserviceprovider decodeprivatekeyinfo(byte[] pkcs8)
        {
            byte[] seqoid = { 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00 };
            byte[] seq = new byte[15];
            memorystream mem = new memorystream(pkcs8);
            int lenstream = (int)mem.length;
            binaryreader binr = new binaryreader(mem);    //wrap memory stream with binaryreader for easy reading
            byte bt = 0;
            ushort twobytes = 0;
            try
            {
                twobytes = binr.readuint16();
                if (twobytes == 0x8130)    //data read as little endian order (actual data order for sequence is 30 81)
                    binr.readbyte();    //advance 1 byte
                else if (twobytes == 0x8230)
                    binr.readint16();    //advance 2 bytes
                else
                    return null;
                bt = binr.readbyte();
                if (bt != 0x02)
                    return null;
                twobytes = binr.readuint16();
                if (twobytes != 0x0001)
                    return null;
                seq = binr.readbytes(15);        //read the sequence oid
                if (!comparebytearrays(seq, seqoid))    //make sure sequence for oid is correct
                    return null;
                bt = binr.readbyte();
                if (bt != 0x04)    //expect an octet string
                    return null;
                bt = binr.readbyte();        //read next byte, or next 2 bytes is  0x81 or 0x82; otherwise bt is the byte count
                if (bt == 0x81)
                    binr.readbyte();
                else
                    if (bt == 0x82)
                    binr.readuint16();
                //------ at this stage, the remaining sequence should be the rsa private key
                byte[] rsaprivkey = binr.readbytes((int)(lenstream - mem.position));
                rsacryptoserviceprovider rsacsp = decodersaprivatekey(rsaprivkey);
                return rsacsp;
            }
            catch (exception)
            {
                return null;
            }
            finally { binr.close(); }
        }
        private static bool comparebytearrays(byte[] a, byte[] b)
        {
            if (a.length != b.length)
                return false;
            int i = 0;
            foreach (byte c in a)
            {
                if (c != b[i])
                    return false;
                i++;
            }
            return true;
        }
        private static rsacryptoserviceprovider decodersapublickey(byte[] publickey)
        {
            // encoded oid sequence for  pkcs #1 rsaencryption szoid_rsa_rsa = "1.2.840.113549.1.1.1"
            byte[] seqoid = { 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00 };
            byte[] seq = new byte[15];
            // ---------  set 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 reading
            byte bt = 0;
            ushort twobytes = 0;
            try
            {
                twobytes = binr.readuint16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for sequence is 30 81)
                    binr.readbyte();    //advance 1 byte
                else if (twobytes == 0x8230)
                    binr.readint16();   //advance 2 bytes
                else
                    return null;
                seq = binr.readbytes(15);       //read the sequence oid
                if (!comparebytearrays(seq, seqoid))    //make sure sequence for oid is correct
                    return 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 byte
                else if (twobytes == 0x8203)
                    binr.readint16();   //advance 2 bytes
                else
                    return null;
                bt = binr.readbyte();
                if (bt != 0x00)     //expect null byte next
                    return null;
                twobytes = binr.readuint16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for sequence is 30 81)
                    binr.readbyte();    //advance 1 byte
                else if (twobytes == 0x8230)
                    binr.readint16();   //advance 2 bytes
                else
                    return 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 modulus
                else if (twobytes == 0x8202)
                {
                    highbyte = binr.readbyte(); //advance 2 bytes
                    lowbyte = binr.readbyte();
                }
                else
                    return null;
                byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };   //reverse byte order since asn.1 key uses big endian order
                int modsize = bitconverter.toint32(modint, 0);
                byte firstbyte = binr.readbyte();
                binr.basestream.seek(-1, seekorigin.current);
                if (firstbyte == 0x00)
                {   //if first byte (highest order) of modulus is zero, don't include it
                    binr.readbyte();    //skip this null byte
                    modsize -= 1;   //reduce modulus buffer size by 1
                }
                byte[] modulus = binr.readbytes(modsize);   //read the modulus bytes
                if (binr.readbyte() != 0x02)            //expect an integer for the exponent data
                    return null;
                int expbytes = (int)binr.readbyte();        // should only need one byte for actual exponent data (for all useful values)
                byte[] exponent = binr.readbytes(expbytes);
                // ------- create rsacryptoserviceprovider instance and initialize with public key -----
                rsacryptoserviceprovider rsa = new rsacryptoserviceprovider();
                rsaparameters rsakeyinfo = new rsaparameters();
                rsakeyinfo.modulus = modulus;
                rsakeyinfo.exponent = exponent;
                rsa.importparameters(rsakeyinfo);
                return rsa;
            }
            catch (exception)
            {
                return null;
            }
            finally { binr.close(); }
        }
        private static rsacryptoserviceprovider decodersaprivatekey(byte[] privkey)
        {
            byte[] modulus, e, d, p, q, dp, dq, iq;
            // ---------  set 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 reading
            byte 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 sequence is 30 81)
                    binr.readbyte();    //advance 1 byte
                else if (twobytes == 0x8230)
                    binr.readint16();    //advance 2 bytes
                else
                    return null;
                twobytes = binr.readuint16();
                if (twobytes != 0x0102)    //version number
                    return null;
                bt = binr.readbyte();
                if (bt != 0x00)
                    return null;
                //------  all private key components are integer sequences ----
                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 rsacryptoserviceprovider instance and initialize with public key -----
                rsacryptoserviceprovider rsa = new rsacryptoserviceprovider();
                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.inverseq = iq;
                rsa.importparameters(rsaparams);
                return rsa;
            }
            catch (exception)
            {
                return null;
            }
            finally { binr.close(); }
        }
        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 integer
                return 0;
            bt = binr.readbyte();
            if (bt == 0x81)
                count = binr.readbyte();    // data size in next byte
            else
                if (bt == 0x82)
            {
                highbyte = binr.readbyte();    // data size in next 2 bytes
                lowbyte = binr.readbyte();
                byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
                count = bitconverter.toint32(modint, 0);
            }
            else
            {
                count = bt;        // we already have the data size
            }
            while (binr.readbyte() == 0x00)
            {    //remove high order zeros in data
                count -= 1;
            }
            binr.basestream.seek(-1, seekorigin.current);        //last readbyte wasn't a removed zero, so back up a byte
            return count;
        }
        #endregion
        #region 解析.net 生成的pem
        private static rsaparameters convertfrompublickey(string pemfileconent)
        {
            byte[] keydata = convert.frombase64string(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.frombase64string(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;//141
            byte[] pempublicexponent = new byte[3];
            array.copy(keydata, index, pempublicexponent, 0, 3);
            index += 3;
            index += 4;//148
            byte[] pemprivateexponent = new byte[128];
            array.copy(keydata, index, pemprivateexponent, 0, 128);
            index += 128;
            index += ((int)keydata[index + 1] == 64 ? 2 : 3);//279
            byte[] pemprime1 = new byte[64];
            array.copy(keydata, index, pemprime1, 0, 64);
            index += 64;
            index += ((int)keydata[index + 1] == 64 ? 2 : 3);//346
            byte[] pemprime2 = new byte[64];
            array.copy(keydata, index, pemprime2, 0, 64);
            index += 64;
            index += ((int)keydata[index + 1] == 64 ? 2 : 3);//412/413
            byte[] pemexponent1 = new byte[64];
            array.copy(keydata, index, pemexponent1, 0, 64);
            index += 64;
            index += ((int)keydata[index + 1] == 64 ? 2 : 3);//479/480
            byte[] pemexponent2 = new byte[64];
            array.copy(keydata, index, pemexponent2, 0, 64);
            index += 64;
            index += ((int)keydata[index + 1] == 64 ? 2 : 3);//545/546
            byte[] 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.inverseq = pemcoefficient;
            return para;
        }
        #endregion
    }
}

调用方式:

string publickey = "";
            string privatekey = "";
            publickey = "migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqddla7of0h4g+waatofcdmldp4dbcc161jcsr0t+xlmsceiglfhtoh4+htcwspvkhwzto9shywwootqgpfl1lblg+rhbxtbmq1m+havvkscbbdz3xs6ngumssktw+q+9rytgor+lngsjhf7hnatj6qyv1ouyiiap4oi1slpmqdidwidaqab";
            privatekey = "miicdgibadanbgkqhkig9w0baqefaascamawggjcageaaogbammsds5/qfid5zoboguj2ysm/gnsjzxrulxkvs35euxiiskcuwfm6hj4e0jzkluqhdnm71kfjbaihooal+xutsud5gefe1syruz4dpvwsxxtsppfflqebqyyys3d5d72ti0aiv6u0zikcxsedpmnpdk/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+tqsemdbkyoajrb2olga1sqtc+udpza1tbofb5v/+5mb5o8=";
            string datamw = rsapkcs8helper.decryptdata(endata, privatekey, "utf-8");
            console.writeline("提前获知解密:" + datamw);

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