加密和解密字符串

加密和解密字符串

本文介绍了加密和解密字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以给我代码加密和解密C#中的字符串?

解决方案

EDIT 2013-Oct :虽然我已经编辑了这个答案,以解决缺点,但请参阅,以获得更强大的,通知解决方案。





原始答案



这是一个工作示例衍生自和。



EDIT 2012年4月:此答案经过编辑,可以预先为每个jbtule的建议提供IV,如下所示:





祝你好运!

  public class Crypto 
{

//虽然应用程序特定的盐不是
//基于密码的加密的最佳做法,但只要
//真的不常见,这可能是足够安全的。另外太多的工作要改变这个答案。
private static byte [] _salt = __To_Do __(在此添加应用程序特定的盐);

///< summary>
///使用AES加密给定的字符串。该字符串可以使用
/// DecryptStringAES()进行解密。 sharedSecret参数必须匹配。
///< / summary>
///< param name =plainText>要加密的文本。< / param>
///< param name =sharedSecret>用于生成加密密钥的密码< / param>
public static string EncryptStringAES(string plainText,string sharedSecret)
{
if(string.IsNullOrEmpty(plainText))
throw new ArgumentNullException(plainText);
if(string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException(sharedSecret);

string outStr = null; //加密字符串返回
RijndaelManaged aesAlg = null; // Rijndael用于加密数据的管理对象。

尝试
{
//从共享密钥和盐生成密钥
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret,_salt);

//创建一个RijndaelManaged对象
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

//创建解密器来执行流转换。
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key,aesAlg.IV);

//创建用于加密的流。
using(MemoryStream msEncrypt = new MemoryStream())
{
//前缀IV
msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length),0,sizeof (INT));
msEncrypt.Write(aesAlg.IV,0,aesAlg.IV.Length);
using(CryptoStream csEncrypt = new CryptoStream(msEncrypt,encryptor,CryptoStreamMode.Write))
{
using(StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//将所有数据写入流。
swEncrypt.Write(plainText);
}
}
outStr = Convert.ToBase64String(msEncrypt.ToArray());
}
}
finally
{
//清除RijndaelManaged对象。
if(aesAlg!= null)
aesAlg.Clear();
}

//从内存流返回加密的字节。
return outStr;
}

///< summary>
///解密给定的字符串。假设字符串使用
/// EncryptStringAES()加密,使用相同的sharedSecret。
///< / summary>
///< param name =cipherText>要解密的文本。< / param>
///< param name =sharedSecret>用于生成解密密钥的密码< / param>
public static string DecryptStringAES(string cipherText,string sharedSecret)
{
if(string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException(cipherText);
if(string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException(sharedSecret);

//声明RijndaelManaged对象
//用于解密数据。
RijndaelManaged aesAlg = null;

//声明用于保存
//解密文本的字符串。
string plaintext = null;

尝试
{
//从共享密钥和盐生成密钥
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret,_salt);

//创建用于解密的流。
byte [] bytes = Convert.FromBase64String(cipherText);
使用(MemoryStream msDecrypt = new MemoryStream(bytes))
{
//使用指定的键创建一个RijndaelManaged对象
//和IV。
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
//从加密流获取初始化向量
aesAlg.IV = ReadByteArray(msDecrypt);
//创建一个解密器来执行流转换。
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key,aesAlg.IV);
using(CryptoStream csDecrypt = new CryptoStream(msDecrypt,decryptor,CryptoStreamMode.Read))
{
using(StreamReader srDecrypt = new StreamReader(csDecrypt))

/ /从解密流
//读取解密的字节,并将它们放在字符串中。
plaintext = srDecrypt.ReadToEnd();
}
}
}
finally
{
//清除RijndaelManaged对象。
if(aesAlg!= null)
aesAlg.Clear();
}

返回明文;
}

private static byte [] ReadByteArray(Stream s)
{
byte [] rawLength = new byte [sizeof(int)];
如果(s.Read(rawLength,0,rawLength.Length)!= rawLength.Length)
{
抛出新的SystemException(Stream不包含正确格式的字节数组);
}

byte [] buffer = new byte [BitConverter.ToInt32(rawLength,0)];
if(s.Read(buffer,0,buffer.Length)!= buffer.Length)
{
throw new SystemException(没有正确读取字节数组);
}

返回缓冲区;
}
}


Can someone give me the code to encrypt and decrypt a string in C#?

解决方案

EDIT 2013-Oct: Although I've edited this answer over time to address shortcomings, please see jbtule's answer for a more robust, informed solution.

https://stackoverflow.com/a/10366194/188474

Original Answer:

Here's a working example derived from the "RijndaelManaged Class" documentation and the MCTS Training Kit.

EDIT 2012-April: This answer was edited to pre-pend the IV per jbtule's suggestion and as illustrated here:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged%28v=vs.95%29.aspx

Good luck!

public class Crypto
{

    //While an app specific salt is not the best practice for
    //password based encryption, it's probably safe enough as long as
    //it is truly uncommon. Also too much work to alter this answer otherwise.
    private static byte[] _salt = __To_Do__("Add a app specific salt here");

    /// <summary>
    /// Encrypt the given string using AES.  The string can be decrypted using
    /// DecryptStringAES().  The sharedSecret parameters must match.
    /// </summary>
    /// <param name="plainText">The text to encrypt.</param>
    /// <param name="sharedSecret">A password used to generate a key for encryption.</param>
    public static string EncryptStringAES(string plainText, string sharedSecret)
    {
        if (string.IsNullOrEmpty(plainText))
            throw new ArgumentNullException("plainText");
        if (string.IsNullOrEmpty(sharedSecret))
            throw new ArgumentNullException("sharedSecret");

        string outStr = null;                       // Encrypted string to return
        RijndaelManaged aesAlg = null;              // RijndaelManaged object used to encrypt the data.

        try
        {
            // generate the key from the shared secret and the salt
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

            // Create a RijndaelManaged object
            aesAlg = new RijndaelManaged();
            aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

            // Create a decryptor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                // prepend the IV
                msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                }
                outStr = Convert.ToBase64String(msEncrypt.ToArray());
            }
        }
        finally
        {
            // Clear the RijndaelManaged object.
            if (aesAlg != null)
                aesAlg.Clear();
        }

        // Return the encrypted bytes from the memory stream.
        return outStr;
    }

    /// <summary>
    /// Decrypt the given string.  Assumes the string was encrypted using
    /// EncryptStringAES(), using an identical sharedSecret.
    /// </summary>
    /// <param name="cipherText">The text to decrypt.</param>
    /// <param name="sharedSecret">A password used to generate a key for decryption.</param>
    public static string DecryptStringAES(string cipherText, string sharedSecret)
    {
        if (string.IsNullOrEmpty(cipherText))
            throw new ArgumentNullException("cipherText");
        if (string.IsNullOrEmpty(sharedSecret))
            throw new ArgumentNullException("sharedSecret");

        // Declare the RijndaelManaged object
        // used to decrypt the data.
        RijndaelManaged aesAlg = null;

        // Declare the string used to hold
        // the decrypted text.
        string plaintext = null;

        try
        {
            // generate the key from the shared secret and the salt
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

            // Create the streams used for decryption.
            byte[] bytes = Convert.FromBase64String(cipherText);
            using (MemoryStream msDecrypt = new MemoryStream(bytes))
            {
                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                // Get the initialization vector from the encrypted stream
                aesAlg.IV = ReadByteArray(msDecrypt);
                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                        // Read the decrypted bytes from the decrypting stream
                        // and place them in a string.
                        plaintext = srDecrypt.ReadToEnd();
                }
            }
        }
        finally
        {
            // Clear the RijndaelManaged object.
            if (aesAlg != null)
                aesAlg.Clear();
        }

        return plaintext;
    }

    private static byte[] ReadByteArray(Stream s)
    {
        byte[] rawLength = new byte[sizeof(int)];
        if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
        {
            throw new SystemException("Stream did not contain properly formatted byte array");
        }

        byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
        if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
        {
            throw new SystemException("Did not read byte array properly");
        }

        return buffer;
    }
}

这篇关于加密和解密字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 20:55