나는 C#으로 암호화 및 C++로 해독 싶지만 어떤 인코딩 문제가 있습니다암호화 C# 암호 해독 AES CBC 256
예를 들어 변수 :
키 : g OtIPaL 버전-vS5UAnJbPqsDZSf, yJ1 IVString을 : g OtIPaL 버전-VS5
내 C# 코드 :
public static string EncryptString(string message, string KeyString, string IVString)
{
byte[] Key = UTF8Encoding.UTF8.GetBytes(KeyString.Substring(0,32));
byte[] IV = UTF8Encoding.UTF8.GetBytes(IVString);
string encrypted = null;
RijndaelManaged rj = new RijndaelManaged();
rj.Key = Key;
rj.IV = IV;
rj.Mode = CipherMode.CBC;
rj.Padding = PaddingMode.PKCS7;
try
{
MemoryStream ms = new MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, rj.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(message);
sw.Close();
}
cs.Close();
}
byte[] encoded = ms.ToArray();
encrypted = Convert.ToBase64String(encoded);
ms.Close();
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine("A file error occurred: {0}", e.Message);
return null;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: {0}", e.Message);
}
finally
{
rj.Clear();
}
return encrypted;
}
,
암호화를 시도 할 때 키에 ASCII 문자가 아닌 바이트 수가 있습니다. 문자열의 길이보다 깁니다.
어떻게 인코딩합니까? C++에서는 EVP (기본 패딩은 PKCS7 임)를 사용합니다. 해당 문자열에서 32 문자이 없기 때문에
static string decryptEX(string KS, string ctext)
{
EVP_CIPHER_CTX* ctx;
ctx = EVP_CIPHER_CTX_new();
string IV = KS.substr(0, 16);
int rc = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (byte*)&KS[0], (byte*)&IV[0]);
std::string rtext;
rtext.resize(ctext.size());
int out_len1 = (int)rtext.size();
rc = EVP_DecryptUpdate(ctx, (byte*)&rtext[0], &out_len1, (const byte*)&ctext[0], (int)ctext.size());
int out_len2 = (int)rtext.size() - out_len1;
rc = EVP_DecryptFinal_ex(ctx, (byte*)&rtext[0] + out_len1, &out_len2);
try
{
rtext.resize(out_len1 + out_len2);
}
catch (exception e)
{
}
return rtext;
}
문자열이 포함 된 null 값을 운반하는 매우 행복하지 경향을, 0x00 바이트는 키와 IV 모두에 나타날 수 있으므로 텍스트 표현이 필요한 경우 일반적으로 Base64를 사용해야합니다. 동일한 메시지가 같은 방식으로 암호화되기 때문에 키에 고정 IV가 없어야합니다. IV가 대개 메시지와 함께 전송되기 때문에 실제로는 키와 바이트를 (의도적으로) 공유해서는 안됩니다. – bartonjs