AES256 암호화, 복호화

유니티 C# 2018. 11. 7. 11:12

암호화

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
private AES256Encrypt(string _Data)
{
    byte[] plainBytes = System.Text.Encoding.UTF8.GetBytes(_Data);
    System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
    {
    Mode = System.Security.Cryptography.CipherMode.CBC,
    Padding = System.Security.Cryptography.PaddingMode.PKCS7,
    KeySize = 256
    };
 
    MemoryStream memoryStream = new MemoryStream();
    System.Security.Cryptography.ICryptoTransform encryptor = rm.CreateEncryptor(
    System.Text.Encoding.UTF8.GetBytes("01234567890123456789012345678901".Substring(0, 256 / 8)),
    System.Text.Encoding.UTF8.GetBytes("01234567890123456789012345678901".Substring(0, 128 / 8)));
    System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, encryptor, System.Security.Cryptography.CryptoStreamMode.Write);
    cryptoStream.Write(plainBytes, 0, plainBytes.Length);
    cryptoStream.FlushFinalBlock();
    byte[] encryptBytes = memoryStream.ToArray();
    string encryptString = System.Convert.ToBase64String(encryptBytes);
    cryptoStream.Close();
    memoryStream.Close();
    return encryptString;
}
cs

 

복호화

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
private string AES256Decrypt()
{
    byte[] encryptBytes = System.Convert.FromBase64String(o);
    System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
    {
        Mode = System.Security.Cryptography.CipherMode.CBC,
        Padding = System.Security.Cryptography.PaddingMode.PKCS7,
        KeySize = 256
    };
 
    MemoryStream memoryStream = new MemoryStream(encryptBytes);
    System.Security.Cryptography.ICryptoTransform decryptor = rm.CreateDecryptor(
    System.Text.Encoding.UTF8.GetBytes("01234567890123456789012345678901".Substring(0, 256 / 8)),
    System.Text.Encoding.UTF8.GetBytes("01234567890123456789012345678901".Substring(0, 128 / 8)));
    System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read);
    byte[] plainBytes = new byte[encryptBytes.Length];
    int plainCount = cryptoStream.Read(plainBytes, 0, plainBytes.Length);
    string plainString = System.Text.Encoding.UTF8.GetString(plainBytes, 0, plainCount);
    cryptoStream.Close();
    memoryStream.Close();
    return plainString;
}
cs