Encrypted string에 말하는 문서가 using AES256
있습니다. 두 가지 값을 가진 내 문서에 따르면 10002:1486703720424 AND HashKey: hpIw4SgN)TxJdoQj=GKo)p83$uHePgoF
결과가 생성 1ltQFLRGNif73uCNzi0YEvBqLKiRgx6fWsk5e/GcTQc=
되지만 결과 를 생성하려고 할 때 6SKbqJAxbBrg4eU7r/B8gJoJEPg+KjMvGL5L7bfykUU=
내 코드에서 생성 됩니다. 내가 뭘 잘못하고 있는지 말씀해 주시겠습니까? 암호화를하는 것은 이번이 처음이므로 실수를 찾기 위해 약간 혼란 스럽습니다.
string getHashKey1 = EncryptText("10002:1486703720424", "hpIw4SgN)TxJdoQj=GKo)p83$uHePgoF");
public string EncryptText(string input, string password)
{
string result = "";
try
{
// Get the bytes of the string
byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(input);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
// Hash the password with SHA256
passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes);
result = Convert.ToBase64String(bytesEncrypted);
}
catch (Exception ex)
{
ErrorLog errLog = new ErrorLog();
errLog.LogsWrite(ex, Path.GetDirectoryName(Application.ExecutablePath));
}
return result;
}
public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
byte[] encryptedBytes = null;
try
{
// Set your salt here, change it to meet your flavor:
// The salt bytes must be at least 8 bytes.
byte[] saltBytes = new byte[] { 1, 2, 23, 234, 37, 48, 134, 63, 248, 4 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
}
catch (Exception ex)
{
ErrorLog errLog = new ErrorLog();
errLog.LogsWrite(ex, Path.GetDirectoryName(Application.ExecutablePath));
}
return encryptedBytes;
}
발견 ... ECB를 암호 모드로 사용하고 있으므로 IV가 없습니다. 이 "보안"에 대해서는 언급하지 않겠습니다. 패딩은 PKCS7 (AES의 기본값) 인 것 같습니다. 암호는 "있는 그대로"사용되며 단순히 UTF8 (또는 ASCII)로 인코딩됩니다 (따라서 길이는 32 바이트 여야 함).
public static string EncryptText(string input, string password)
{
// Get the bytes of the string
byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(input);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes);
string result = Convert.ToBase64String(bytesEncrypted);
return result;
}
public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
using (MemoryStream ms = new MemoryStream())
{
using (Aes aes = Aes.Create())
{
aes.Key = passwordBytes;
aes.Mode = CipherMode.ECB;
// "zero" IV
aes.IV = new byte[16];
using (var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
}
byte[] encryptedBytes = ms.ToArray();
return encryptedBytes;
}
}
@LukePark는 OP에는 유용하지만 더 큰 세상에서는 쓸모없는이 답변에 대해 올바르게 정리했습니다. 올바른 단어를 굵게 표시하겠습니다 . 이런 이유로 나는 A. Goutam에 주어진 사양의 "잘못된"사항과 "올바른"사양이 항상 포함해야하는 사항을 설명 할 것입니다.
암호화 사양에는 항상 사용 된 알고리즘 (예 : AES), 키 크기 (AES256이라고 말하면 256 비트), 블록 모드 (CBC, ECB 등)가 포함되어야합니다. 많은 블록 모드 (예 : CBC)에는 IV 벡터가 필요합니다. ECB는 다른 블록 모드보다 보안 수준이 낮습니다 (예 : https://crypto.stackexchange.com/questions/225/should-i-use-ecb-or-cbc-encryption-mode-for-my-block-cipher 참조). ). IV가 필요한 경우 사양에이를 포함해야합니다 (또는 생성 방법을 설명). 사양에는 사용해야하는 패딩이 포함되어야합니다. 는 Padding.None
데이터가 정확하게 암호화 블록으로 세분 될 수있는 암호화 할 경우에만 사용되어야한다 (따라서, 예를 들어, AES와, PaddingMode.None
데이터가 16, 32, 64, 96 인 경우에만 좋다 ... 바이트).PaddingMode.Zeros
텍스트에만 적합합니다 (텍스트 '\0'
끝에 추가되므로 사용하지 않겠습니다 ). 다른 패딩 모드는 좋습니다.
예를 들어 문자열이기 때문에 키는 "있는 그대로"사용되지 않는 경우가 많습니다. 사양에는 문자열 키에서 암호화 키를 파생시키는 방법이 포함되어야합니다. SHA256
열쇠는 약한 해결책입니다. 일반적으로 좋은 솔루션은와 같은 강력한 키 파생 함수를 사용하는 것 Rfc2898DeriveBytes
입니다. 이 함수를 사용하는 경우 사양에는 반복 횟수 및 사용 Rfc2898DeriveBytes
또는 유사한 함수에 대한 기타 정보가 포함되어야합니다 . 키 (텍스트 인 경우 암호화 할 데이터)에 어떤 인코딩을 사용해야하는지 명확하게 포함해야합니다 ( UTF8
항상 좋은 생각입니다).
좋은 사양에는 몇 가지 테스트 케이스가 포함되어야한다고 덧붙일 것입니다. 적어도 하나의 테스트 케이스는 암호화 블록보다 길이가 작아야하고 적어도 하나의 테스트 케이스 는 암호화 블록보다 길이가 길지만 두 개의 암호화 블록보다 작아야합니다 (또는> 2 및 <3 ... 일부 완전한 블록과 하나 불완전 블록). 이런 식으로 당신은 둘 다 테스트 PaddingMode
하고 있습니다 CipherMode
(해야 / 반드시 : 암호화 블록과 불완전한 블록보다 큰 것을 테스트함으로써 이미 모든 것을 테스트하고 있습니다)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다