C++如何将一行数据文件放入数组中进行加密? (AES)

标签 c++ encryption aes

我已经完成了我的 AES 加密程序,直到我使用以下代码在命令提示符下得到正确答案:

void main()
{
int a;

unsigned char CipherKey[16] = {0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C};
unsigned char PlainText[16] = {0x32, 0x43, 0xF6, 0xA8, 0x88, 0x5A, 0x30, 0x8D, 0x31, 0x31, 0x98, 0xA2, 0xE0, 0x37, 0x07, 0x34};


for(a=0;a<16;a++)
{
    Key[a] = CipherKey[a];
    input[a] = PlainText[a];
}

KeyExpansion();
Cipher();

cout << endl;
cout << "Encryted output text:" << endl;

for(a=0;a<16;a++) // For loop is used to print every character of the output array onto the console
{
    printf("%02x ",output[a]); // printf is used in order to print the encrypted text in hexidecimal
}

cout << endl;

但是,我现在需要从数据文件而不是程序本身中获取 CipherKey 和 PlainText 的数据 block 。我的数据文件 Input.dat 如下所示:

0x2B、0x7E、0x15、0x16、0x28、0xAE、0xD2、0xA6、0xAB、0xF7、0x15、0x88、0x09、0xCF、0x4F、0x3C

0x32、0x43、0xF6、0xA8、0x88、0x5A、0x30、0x8D、0x31、0x31、0x98、0xA2、0xE0、0x37、0x07、0x34

因此我需要从文件中获取这些信息并将其放入这些数组中:

unsigned char CipherKey[16];
unsigned char PlainText[16];

然后程序将正常使用这些数据来加密 PlainText,然后创建一个新的输出文件,其中存储了加密的文本(暂时不用担心这部分)

这是我的尝试:

void main()
{
int a;

unsigned char CipherKey[16]; 
unsigned char PlainText[16];

ifstream inFile;
ofstream outFile;

inFile.open("Input.dat"); // Opens input file with required info to place into arrays initialised above

for(a=0;a<16;a++)
{
    inFile >>  CipherKey[a]; // The first 16 unsigned chars in the file are placed in the array CipherKey[16]
    // i.e. 0x2B is placed in CipherKey[0], 0xAE is placed in CipherKey[5] etc
}

for(a=0;a<16;a++)
{
    inFile >>  PlainText[a]; // The last 16 unsigned chars in the file are placed in the array PlainText[16]
}

inFile.close();
    ...// Rest of code

答案应该是:39 25 84 1d 02 dc 09 fb dc 11 85 97 19 6a 0b 32 而我得到:60 a6 f1 d6 7a 14 32 1a 40 55 50 e8 0c fc 5f cc

我制作了一个小程序,它使用这种方法获取文件中的总和整数值,以查看这种方式是否可以与 AES 程序一起使用,看起来它可以。

这看起来像是我沿着正确的路线还是偏离了目标?

最佳答案

当使用输入流读取 char 时,它不是作为整数(十六进制或其他)读取,而是作为文本字符读取。

因此,通过执行 inFile >> Cipherkey[a],您将用 ascii 填充 CipherKey(好吧,从技术上讲,这取决于输入文件的编码和你的 c++ 编译器)文件前 16 个字节的代码:

例如,如果它以“0x2B”开头,则CipherKey 的前四个字符将为0x30 0x78 0x32 0x42

关于C++如何将一行数据文件放入数组中进行加密? (AES),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23256254/

相关文章:

c++ - IE8打开网站流程

java - 如何配置 REST 服务以使用 Spring Security 手动检查加密密码?

C#:AES 错误:填充无效且无法删除。相同的 key 和一切,帮助

如果仅使用长字符串,Java Android AES 解密结果将被截断

openssl - 使用openssl解密AES-GCM文件

c++ - std::stoi - 具有非数字字符的字符串被解析为整数而不抛出异常 (c++)

c++ - 计算 remove_if 中的删除(c++ STL)

以模板类为参数的C++模板函数

iOS iPhone iPad 限制 SSL/HTTPS 加密位

c - 不要正确加密 wincrypt