
해당 함수를 사용하여 AES-256-GCM 암호화된 데이터를 복호화하려면, 다음과 같은 조건을 만족해야 합니다.
1. nonce는 암호화 시 사용한 nonce와 동일해야 합니다.
2. ciphertext는 암호화 시 생성된 ciphertext와 동일해야 합니다.
3. plaintext는 암호화 시 사용한 plaintext와 동일해야 합니다.
위 코드에서 문제는 nonce, ciphertext, plaintext를 모두 randombytes 함수를 사용하여 생성하기 때문입니다. 암호화 시 사용한 nonce, ciphertext, plaintext는 모두 고유한 값이어야 하므로, randombytes 함수를 사용하여 생성한 값은 암호화 시 사용한 값과 동일하지 않습니다.
해결 방법은 다음과 같습니다.
1. nonce를 암호화 시 사용한 nonce와 동일한 값을 사용해야 합니다.
2. ciphertext를 암호화 시 생성된 ciphertext와 동일한 값을 사용해야 합니다.
3. plaintext를 암호화 시 사용한 plaintext와 동일한 값을 사용해야 합니다.
위 코드를 수정하여 다음과 같이 작성할 수 있습니다.
#hostingforum.kr
c
#include
int main() {
unsigned char nonce[crypto_aead_aes256gcm_NPUBBYTES];
unsigned char ciphertext[crypto_aead_aes256gcm_NPUBBYTES + crypto_aead_aes256gcm_ABYTES];
unsigned char plaintext[crypto_aead_aes256gcm_NPUBBYTES + crypto_aead_aes256gcm_ABYTES];
// nonce를 생성합니다.
randombytes(nonce, crypto_aead_aes256gcm_NPUBBYTES);
// plaintext를 생성합니다.
randombytes(plaintext, crypto_aead_aes256gcm_NPUBBYTES + crypto_aead_aes256gcm_ABYTES);
// ciphertext를 생성합니다.
unsigned char tag[crypto_aead_aes256gcm_ABYTES];
if (sodium_crypto_aead_aes256gcm_encrypt(NULL, NULL, 0, nonce, plaintext, crypto_aead_aes256gcm_NPUBBYTES + crypto_aead_aes256gcm_ABYTES, tag, ciphertext) != 0) {
printf("암호화 실패n");
return 1;
}
// ciphertext를 복호화합니다.
if (sodium_crypto_aead_aes256gcm_decrypt(plaintext, ciphertext, crypto_aead_aes256gcm_ABYTES, nonce, NULL, 0) != 0) {
printf("복호화 실패n");
}
return 0;
}
위 코드에서, nonce를 암호화 시 사용한 nonce와 동일한 값을 사용하고, ciphertext를 암호화 시 생성된 ciphertext와 동일한 값을 사용합니다. plaintext를 암호화 시 사용한 plaintext와 동일한 값을 사용하여 ciphertext를 생성한 후, ciphertext를 복호화합니다.
2025-07-08 15:57