首页 > 开发 > 综合 > 正文

一个可以用来加密/解密的类

2024-07-21 02:24:33
字体:
来源:转载
供稿:网友
  • 本文来源于网页设计爱好者web开发社区http://www.html.org.cn收集整理,欢迎访问。
  • 可以用来加/解密数据库用户、密码等

    using system;
    using system.io;
    using system.text;
    using system.security.cryptography;

    namespace common
    {
    /// <summary>
    /// securityservice 的摘要说明。
    /// </summary>
    public class securityservice
    {
    static protected byte[] bytekey = {125, 14, 45, 67, 112, 79, 77, 99, 37, 104, 13, 9, 118, 51, 87, 108};
    static protected byte[] byteiv = {86, 19, 79, 15, 72, 58, 117, 45};
    static public string symmetricencrypt(string splaintext)
    {
    byte[] byteplaintext;
    memorystream encryptedstream;
    icryptotransform encryptor;
    cryptostream thecryptostream;
    if(splaintext=="") return "";
    byteplaintext = encoding.ascii.getbytes(splaintext);
    encryptedstream = new memorystream(splaintext.length);
    encryptor = getencryptor();
    thecryptostream = new cryptostream(encryptedstream, encryptor, cryptostreammode.write);
    thecryptostream.write(byteplaintext, 0, byteplaintext.length);
    thecryptostream.flushfinalblock();
    thecryptostream.close();

    return convert.tobase64string(encryptedstream.toarray());

    }//end function

    static public string symmetricdecrypt(string sencryptedtext)
    {
    byte[] byteencrypted;
    memorystream plaintextstream;
    icryptotransform decryptor;
    cryptostream thecryptostream;

    if (sencryptedtext == "") return "";

    byteencrypted = convert.frombase64string(sencryptedtext.trim());
    plaintextstream = new memorystream(sencryptedtext.length);
    decryptor = getdecryptor();
    thecryptostream = new cryptostream(plaintextstream, decryptor, cryptostreammode.write);

    thecryptostream.write(byteencrypted, 0, byteencrypted.length);
    thecryptostream.flushfinalblock();
    thecryptostream.close();

    return encoding.ascii.getstring(plaintextstream.toarray());

    }//end function

    static private icryptotransform getencryptor()
    {
    rc2cryptoserviceprovider cryptoprovider = new rc2cryptoserviceprovider();
    cryptoprovider.mode = ciphermode.cbc;
    return cryptoprovider.createencryptor(bytekey, byteiv);

    }//end function

    static private icryptotransform getdecryptor()
    {
    rc2cryptoserviceprovider cryptoprovider = new rc2cryptoserviceprovider();
    cryptoprovider.mode = ciphermode.cbc;
    return cryptoprovider.createdecryptor(bytekey, byteiv);

    }//end function
    }
    }



    发表评论 共有条评论
    用户名: 密码:
    验证码: 匿名发表