AES加密,解密方法

加密:

View Code
//加密,docPath:要加密的文件路径,strKey:秘钥
public static void Encrypt(string docPath, string strKey)
{
    //分组加密算法
    var fs = new FileStream(docPath, FileMode.Open);
    byte[] buffer = new byte[fs.Length];
    fs.Read(buffer, 0, buffer.Length);//得到需要加密的字节数组    
    //设置密钥,密钥向量,两个一样,都是16个byte
    var rDel = new RijndaelManaged();
    var key = Encoding.UTF8.GetBytes(strKey);
    rDel.Key = key;
    rDel.Mode = CipherMode.ECB;
    rDel.Padding = PaddingMode.PKCS7;
    ICryptoTransform cTransform = rDel.CreateEncryptor();
    byte[] cipherBytes = cTransform.TransformFinalBlock(buffer, 0, buffer.Length);
    var fsEncrypt = new FileStream(docPath + "ENC", FileMode.Create, FileAccess.Write);
    fsEncrypt.Write(cipherBytes, 0, cipherBytes.Length);
    fsEncrypt.Close();
    fsEncrypt.Dispose();
    fs.Close();
    fs.Dispose();
}

解密:

View Code
//解密,fileIn:解密的文件路径,fileOut:解密后的文件存放路径,strKey:秘钥
public static void Decrypt(string fileIn, string fileOut, string strKey)
{
    var fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read);
    var fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);
    var rDel = new RijndaelManaged();
    var key = Encoding.UTF8.GetBytes(strKey);
    rDel.Key = key;
    rDel.Mode = CipherMode.ECB;
    rDel.Padding = PaddingMode.PKCS7;
    var cs = new CryptoStream(fsOut, rDel.CreateDecryptor(), CryptoStreamMode.Write);
    var bufferLen = 4096;
    var buffer = new byte[bufferLen];
    int bytesRead;
    do
    {
        bytesRead = fsIn.Read(buffer, 0, bufferLen);
        cs.Write(buffer, 0, bytesRead);
    } while (bytesRead != 0);
    cs.Close();
    fsIn.Close();
    fsIn.Dispose();
    fsOut.Dispose();
}

 

posted @ 2013-03-28 22:06  瓜王  阅读(477)  评论(0编辑  收藏  举报