DES 加密 解密

 

DES解密:

///

/// DES解密字符串

/// ECB模式:电子密本方式,这是JAVA封装的DES算法的默认模式,

/// 就是将数据按照8个字节一段进行DES加密或解密得到一段8个字节的密文或者明文,

/// 最后一段不足8个字节,则补足8个字节(注意:这里就涉及到数据补位了)进行计算,

/// 之后按照顺序将计算所得的数据连在一起即可,各段数据之间互不影响。

///

/// 待解密的字符串

/// 解密密钥,要求为8位,和加密密钥相同

/// 解密成功返回解密后的字符串,失败返源串

public string DecryptDES(string decryptString, string decryptKey)

{

if (string.IsNullOrEmpty(decryptString))

{

return decryptString;

}

byte[] inputByteArray = Convert.FromBase64String(decryptString);

using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())

{

des.Key = UTF8Encoding.UTF8.GetBytes(decryptKey);

des.IV = UTF8Encoding.UTF8.GetBytes(decryptKey);

des.Mode = System.Security.Cryptography.CipherMode.ECB;

System.IO.MemoryStream ms = new System.IO.MemoryStream();

using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))

{

cs.Write(inputByteArray, 0, inputByteArray.Length);

cs.FlushFinalBlock();

cs.Close();

}

string str = Encoding.UTF8.GetString(ms.ToArray());

ms.Close();

return str;

}

}

 

 //DES加密 ECB 
        public  string Encrypt(string encryptString, string sKey)
        {
            try
            {
                
                byte[] keyBytes = UTF8Encoding.UTF8.GetBytes(sKey);
                byte[] keyIV = UTF8Encoding.UTF8.GetBytes(sKey);
                byte[] encryptBytes = Encoding.UTF8.GetBytes(encryptString);

                DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();
                // 使用ECB方式
                desProvider.Mode = CipherMode.ECB; 
                MemoryStream memStream = new MemoryStream();
                //CreateEncryptor(keyBytes, keyIV)类似于OpenSSL中的密钥置换
                CryptoStream crypStream = new CryptoStream(memStream, desProvider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
                crypStream.Write(encryptBytes, 0, encryptBytes.Length);
                crypStream.FlushFinalBlock();
                string ret = string.Empty;
                // byte[] cipherBytes = memStream.ToArray();
                //foreach (byte b in memStream.ToArray())
                //{
                //    ret.AppendFormat("{0:X2}", b);
                //}
                ret= Convert.ToBase64String(memStream.ToArray());
                
                return ret.ToString();
               // return cipherBytes;
            }
            catch
            {
                return encryptString;
            }
        } 

你可能感兴趣的:(DES,c#,c#)