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

C#常用字符串加密解密方法封装代码

程序员文章站 2024-02-22 20:05:28
复制代码 代码如下://方法一//须添加对system.web的引用//using system.web.security;/// /// s...

复制代码 代码如下:

//方法一
//须添加对system.web的引用
//using system.web.security;
/// <summary>
/// sha1加密字符串
/// </summary>
/// <param name="source">源字符串</param>
/// <returns>加密后的字符串</returns>
public string sha1(string source)
{
    return formsauthentication.hashpasswordforstoringinconfigfile(source, "sha1");
}
/// <summary>
/// md5加密字符串
/// </summary>
/// <param name="source">源字符串</param>
/// <returns>加密后的字符串</returns>
public string md5(string source)
{
    return formsauthentication.hashpasswordforstoringinconfigfile(source, "md5");;
}


//方法二(可逆加密解密):
//using system.security.cryptography;
public string encode(string data)
{
    byte[] bykey = system.text.asciiencoding.ascii.getbytes(key_64);
    byte[] byiv = system.text.asciiencoding.ascii.getbytes(iv_64);
    descryptoserviceprovider cryptoprovider = new descryptoserviceprovider();
    int i = cryptoprovider.keysize;
    memorystream ms = new memorystream();
    cryptostream cst = new cryptostream(ms, cryptoprovider.createencryptor(bykey, byiv), cryptostreammode.write);
    streamwriter sw = new streamwriter(cst);
    sw.write(data);
    sw.flush();
    cst.flushfinalblock();
    sw.flush();
    return convert.tobase64string(ms.getbuffer(), 0, (int)ms.length);
}
public string decode(string data)
{
    byte[] bykey = system.text.asciiencoding.ascii.getbytes(key_64);
    byte[] byiv = system.text.asciiencoding.ascii.getbytes(iv_64);
    byte[] byenc;
    try
    {
        byenc = convert.frombase64string(data);
    }
    catch
    {
        return null;
    }
    descryptoserviceprovider cryptoprovider = new descryptoserviceprovider();
    memorystream ms = new memorystream(byenc);
    cryptostream cst = new cryptostream(ms, cryptoprovider.createdecryptor(bykey, byiv), cryptostreammode.read);
    streamreader sr = new streamreader(cst);


//方法三(md5不可逆):
//using system.security.cryptography;
//md5不可逆加密
//32位加密
public string getmd5_32(string s, string _input_charset)
{
    md5 md5 = new md5cryptoserviceprovider();
    byte[] t = md5.computehash(encoding.getencoding(_input_charset).getbytes(s));
    stringbuilder sb = new stringbuilder(32);
    for (int i = 0; i < t.length; i++)
    {
        sb.append(t[i].tostring("x").padleft(2, '0'));
    }
    return sb.tostring();
}
//16位加密
public static string getmd5_16(string convertstring)
{
    md5cryptoserviceprovider md5 = new md5cryptoserviceprovider();
    string t2 = bitconverter.tostring(md5.computehash(utf8encoding.default.getbytes(convertstring)), 4, 8);
    t2 = t2.replace("-", "");
    return t2;
}


//方法四(对称加密):
//using system.io;
//using system.security.cryptography;
private symmetricalgorithm mobjcryptoservice;
private string key;
/// <summary>  
/// 对称加密类的构造函数  
/// </summary>  
public symmetricmethod()
{
    mobjcryptoservice = new rijndaelmanaged();
    key = "guz(%&hj7x89h$yubi0456ftmat5&fvhufcy76*h%(hilj$lhj!y6&(*jkp87jh7";
}
/// <summary>  
/// 获得密钥  
/// </summary>  
/// <returns>密钥</returns>  
private byte[] getlegalkey()
{
    string stemp = key;
    mobjcryptoservice.generatekey();
    byte[] byttemp = mobjcryptoservice.key;
    int keylength = byttemp.length;
    if (stemp.length > keylength)
        stemp = stemp.substring(0, keylength);
    else if (stemp.length < keylength)
        stemp = stemp.padright(keylength, ' ');
    return asciiencoding.ascii.getbytes(stemp);
}
/// <summary>  
/// 获得初始向量iv  
/// </summary>  
/// <returns>初试向量iv</returns>  
private byte[] getlegaliv()
{
    string stemp = "e4ghj*ghg7!rnifb&95guy86gfghub#er57hbh(u%g6hj($jhwk7&!hg4ui%$hjk";
    mobjcryptoservice.generateiv();
    byte[] byttemp = mobjcryptoservice.iv;
    int ivlength = byttemp.length;
    if (stemp.length > ivlength)
        stemp = stemp.substring(0, ivlength);
    else if (stemp.length < ivlength)
        stemp = stemp.padright(ivlength, ' ');
    return asciiencoding.ascii.getbytes(stemp);
}
/// <summary>  
/// 加密方法  
/// </summary>  
/// <param name="source">待加密的串</param>  
/// <returns>经过加密的串</returns>  
public string encrypto(string source)
{
    byte[] bytin = utf8encoding.utf8.getbytes(source);
    memorystream ms = new memorystream();
    mobjcryptoservice.key = getlegalkey();
    mobjcryptoservice.iv = getlegaliv();
    icryptotransform encrypto = mobjcryptoservice.createencryptor();
    cryptostream cs = new cryptostream(ms, encrypto, cryptostreammode.write);
    cs.write(bytin, 0, bytin.length);
    cs.flushfinalblock();
    ms.close();
    byte[] bytout = ms.toarray();
    return convert.tobase64string(bytout);
}
/// <summary>  
/// 解密方法  
/// </summary>  
/// <param name="source">待解密的串</param>  
/// <returns>经过解密的串</returns>  
public string decrypto(string source)
{
    byte[] bytin = convert.frombase64string(source);
    memorystream ms = new memorystream(bytin, 0, bytin.length);
    mobjcryptoservice.key = getlegalkey();
    mobjcryptoservice.iv = getlegaliv();
    icryptotransform encrypto = mobjcryptoservice.createdecryptor();
    cryptostream cs = new cryptostream(ms, encrypto, cryptostreammode.read);
    streamreader sr = new streamreader(cs);
    return sr.readtoend();
}

//方法五:
//using system.io;
//using system.security.cryptography;
//using system.text;
//默认密钥向量
private static byte[] keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
/**//**//**//// <summary>
/// des加密字符串 keleyi.com
/// </summary>
/// <param name="encryptstring">待加密的字符串</param>
/// <param name="encryptkey">加密密钥,要求为8位</param>
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
public static string encryptdes(string encryptstring, string encryptkey)
{
    try
    {
        byte[] rgbkey = encoding.utf8.getbytes(encryptkey.substring(0, 8));
        byte[] rgbiv = keys;
        byte[] inputbytearray = encoding.utf8.getbytes(encryptstring);
        descryptoserviceprovider dcsp = new descryptoserviceprovider();
        memorystream mstream = new memorystream();
        cryptostream cstream = new cryptostream(mstream, dcsp.createencryptor(rgbkey, rgbiv), cryptostreammode.write);
        cstream.write(inputbytearray, 0, inputbytearray.length);
        cstream.flushfinalblock();
        return convert.tobase64string(mstream.toarray());
    }
    catch
    {
        return encryptstring;
    }
}
/**//**//**//// <summary>
/// des解密字符串 keleyi.com
/// </summary>
/// <param name="decryptstring">待解密的字符串</param>
/// <param name="decryptkey">解密密钥,要求为8位,和加密密钥相同</param>
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
public static string decryptdes(string decryptstring, string decryptkey)
{
    try
    {
        byte[] rgbkey = encoding.utf8.getbytes(decryptkey);
        byte[] rgbiv = keys;
        byte[] inputbytearray = convert.frombase64string(decryptstring);
        descryptoserviceprovider dcsp = new descryptoserviceprovider();
        memorystream mstream = new memorystream();
        cryptostream cstream = new cryptostream(mstream, dcsp.createdecryptor(rgbkey, rgbiv), cryptostreammode.write);
        cstream.write(inputbytearray, 0, inputbytearray.length);
        cstream.flushfinalblock();
        return encoding.utf8.getstring(mstream.toarray());
    }
    catch
    {
        return decryptstring;
    }
}


//方法六(文件加密):
//using system.io;
//using system.security.cryptography;
//using system.text;
//加密文件
private static void encryptdata(string inname, string outname, byte[] deskey, byte[] desiv)
{
    //create the file streams to handle the input and output files.
    filestream fin = new filestream(inname, filemode.open, fileaccess.read);
    filestream fout = new filestream(outname, filemode.openorcreate, fileaccess.write);
    fout.setlength(0);
    //create variables to help with read and write.
    byte[] bin = new byte[100]; //this is intermediate storage for the encryption.
    long rdlen = 0;              //this is the total number of bytes written.
    long totlen = fin.length;    //this is the total length of the input file.
    int len;                     //this is the number of bytes to be written at a time.
    des des = new descryptoserviceprovider();
    cryptostream encstream = new cryptostream(fout, des.createencryptor(deskey, desiv), cryptostreammode.write);
    //read from the input file, then encrypt and write to the output file.
    while (rdlen < totlen)
    {
        len = fin.read(bin, 0, 100);
        encstream.write(bin, 0, len);
        rdlen = rdlen + len;
    }
    encstream.close();
    fout.close();
    fin.close();
}
//解密文件
private static void decryptdata(string inname, string outname, byte[] deskey, byte[] desiv)
{
    //create the file streams to handle the input and output files.
    filestream fin = new filestream(inname, filemode.open, fileaccess.read);
    filestream fout = new filestream(outname, filemode.openorcreate, fileaccess.write);
    fout.setlength(0);
    //create variables to help with read and write.
    byte[] bin = new byte[100]; //this is intermediate storage for the encryption.
    long rdlen = 0;              //this is the total number of bytes written.
    long totlen = fin.length;    //this is the total length of the input file.
    int len;                     //this is the number of bytes to be written at a time.
    des des = new descryptoserviceprovider();
    cryptostream encstream = new cryptostream(fout, des.createdecryptor(deskey, desiv), cryptostreammode.write);
    //read from the input file, then encrypt and write to the output file.
    while (rdlen < totlen)
    {
        len = fin.read(bin, 0, 100);
        encstream.write(bin, 0, len);
        rdlen = rdlen + len;
    }
    encstream.close();
    fout.close();
    fin.close();
    return sr.readtoend();
}