Some questions about chacha20poly1305 #1320
-
This is my encryption and decryption code. Why can't it be decrypted normally? Can anyone please help me? This problem has been tormenting me for a week. This is the parameter passed in if (sodium_init() == -1) {
}
//encrypt
const char *nativeMes = env->GetStringUTFChars(message, nullptr);
const char *nativekey = env->GetStringUTFChars(keys, nullptr);
unsigned char nonce[crypto_aead_xchacha20poly1305_ietf_NPUBBYTES];
unsigned char key[crypto_aead_xchacha20poly1305_ietf_KEYBYTES];
unsigned char ciphertext[strlen(nativeMes) + crypto_aead_xchacha20poly1305_ietf_ABYTES];
unsigned long long ciphertext_len;
memcpy(key, nativekey, crypto_aead_xchacha20poly1305_ietf_KEYBYTES);
int adlen = 9;
unsigned char ad[10] = "123456789";
crypto_aead_xchacha20poly1305_ietf_keygen(key);
randombytes_buf(nonce, sizeof nonce);
crypto_aead_xchacha20poly1305_ietf_encrypt(ciphertext, &ciphertext_len,
reinterpret_cast<const unsigned char *>(nativeMes),
strlen(nativeMes),
ad, adlen,
NULL, nonce, key);
env->ReleaseStringUTFChars(keys, nativekey);
LOGE("ciphertext: %s|\n", ciphertext);
LOGE("ciphertext_len: %llu|\n", ciphertext_len);
char ans[(ciphertext_len) * 2 + 1];
sodium_bin2hex(ans, sizeof ans, ciphertext, ciphertext_len);
LOGE("Ans: %s|\n", ans);
LOGE("Ans_Len: %zu|\n", strlen(ans));
LOGE("ans_len: %zu|\n", sizeof(ans));
//decrypt
//randombytes_buf(nonce, sizeof nonce);
unsigned char que[strlen(ans) / 2];
sodium_hex2bin(que, sizeof(ans), ans, strlen(ans), NULL, NULL, NULL);
LOGE("Ans-1: %s|\n", que);
LOGE("ans-1_len: %zu|\n", sizeof(que));
//It seems that the data before and after the conversion are consistent here.However, the following decryption fails to output the expected results.
unsigned char decrypted[strlen(nativeMes)];
unsigned long long decrypted_len;
if (crypto_aead_xchacha20poly1305_ietf_decrypt(decrypted, &decrypted_len,
NULL,
que, strlen(ans) / 2 + 1,
ad,
adlen,
nonce, key) != 0) {
/* message forged! */
LOGE("Ans-2: %s|\n", decrypted);
LOGE("Ans-2_Len: %llu|\n", decrypted_len);
LOGE("ans-2_len: %zu|\n", sizeof(decrypted));
} else {
LOGE("Ans-22: %s|\n", decrypted);
LOGE("Ans-22_Len: %llu|\n", decrypted_len);
LOGE("ans-22_len: %zu|\n", sizeof(decrypted));
}
env->ReleaseStringUTFChars(message, nativeMes); |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
That code is hard to follow, but just one thing that looks odd: char ans[(ciphertext_len) * 2 + 1]; Looks like you're trying to recover strlen(ans) / 2 + 1 Shouldn't that be |
Beta Was this translation helpful? Give feedback.
-
Check what |
Beta Was this translation helpful? Give feedback.
Check what
sizeof()
actually does and that it returns what you expect :)