AES_encrypt/AES_decrypt仅返回消息的一部分 [英] AES_encrypt/AES_decrypt only returns part of a message
问题描述
我不知道为什么下面的代码将返回"Hello native!Th"而不是"Hello native!这是从jni加载!\ n",有人会提示吗?
I don't know why the following code will return "Hello native! Th" not "Hello native! This is from jni load!\n", may someone tip it?
#include "helloJNI.h"
#include "openssl/aes.h"
#define LEN 1024
jstring jni_text(JNIEnv *env, jclass clz)
{
AES_KEY aesKey;
int result;
const char origin[] = "Hello native! This is from jni load!\n";
char out[LEN];
char outout[LEN];
memset(out, '\0', sizeof(out));
memset(outout, '\0', sizeof(outout));
result = AES_set_encrypt_key((const unsigned char *)"abc123", 256, &aesKey);
LOGE("encypt key result %d\n", result); /* is 0 */
AES_encrypt((const unsigned char *)origin, (unsigned char *)out, &aesKey);
LOGE("after encrypt, chars is %s\n", out);
result = AES_set_decrypt_key((const unsigned char *)"abc123", 256, &aesKey);
LOGE("decrypt key result %d\n", result); /* is 0 */
AES_decrypt(out, outout, &aesKey);
LOGE("after decrypt, chars is %s\n", outout);
return (*env)->NewStringUTF(env, outout); /* return "Hello native! Th" */
}
推荐答案
AES_encrypt((const unsigned char *)origin, (unsigned char *)out, &aesKey);
AES_encrypt
在16字节块上运行. AES的块大小为16.
AES_encrypt
operates on 16-byte blocks. 16 is the block size of AES.
有效地,您将邮件截断了.
Effectively, you truncated your message.
AES_decrypt(pout, outout, &aesKey);
在这里,您只解密了16个字节.缓冲区的其余部分回填为0.0用作ASCII-Z终止符.
Here, you only decrypted 16 byes. The remainder of the buffer was back filled with 0. The 0 served as the ASCII-Z terminator.
您正在以ECB模式有效地操作密码. ECB模式可能是您需要的错误模式.仅当使用一条密钥加密一条消息时,ECB模式才是安全的.否则,攻击者将得知同一封邮件已被加密两次.
You are effectively operating the cipher in ECB mode. ECB mode is probably the wrong mode for your needs. ECB mode is only secure if one message is encrypted under one key. Otherwise, the attacker learns the same message was encrypted twice.
此外,它唯一安全的 if 消息小于块大小.如果消息大于块大小,则ECB模式可能会泄漏信息.
Additionally, its only secure if the message is smaller than the block size. If the message is larger than the block size, then ECB mode can leak information.
您可能应该使用CBC模式.您还应该使用EVP_*
函数而不是AES_encrypt
和AES_decrypt
.请参阅OpenSSL Wiki上的 EVP对称加密和解密.
You should probably use CBC mode. You should also use the EVP_*
functions instead rather than AES_encrypt
and AES_decrypt
. See EVP Symmetric Encryption and Decryption on the OpenSSL wiki.
如果仅加密数据,则缺乏完整性和真实性保证.因此,密文具有延展性,这通常是一件坏事.在这种情况下,最好使用EAX,CCM或GCM之类的模式.为此,请参见 EVP身份验证的加密和解密.
If you are only encrypting the data, then you lack integrity and authenticity assurances. So the cipher text is malleable, which is usually a bad thing. In this case, it would be better to use a mode like EAX, CCM or GCM. For that, see EVP Authenticated Encryption and Decryption.
这篇关于AES_encrypt/AES_decrypt仅返回消息的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!