2
回答
使用OpenSSL的AES_encrypt和AES_decrypt函数出问题
注册华为云得mate10,2.9折抢先购!>>>   

我做了两个接口,使用加密接口aes_encrypt_cli加密后,使用解密接口aes_decrypt_cli解密输出是乱码



下面是测试程序

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <openssl/aes.h>
#include <fcntl.h>

#define     NBUFF   4096

int main(int argc, char *argv[])
{
    AES_KEY     aes;
    unsigned char    key[AES_BLOCK_SIZE];
    unsigned char    in[NBUFF], out[NBUFF];
    unsigned char    iv[AES_BLOCK_SIZE];
    int     rfd, wfd, kfd, nread, n;
    unsigned char   c;

    if (argc != 4){
        printf("usage: a.out [ -e ] [ -d ] <infile> <outfile> \n");
        exit(EXIT_FAILURE);
    }
  
    rfd = open(argv[2], O_RDONLY, 0);
    wfd = open(argv[3], O_RDWR|O_CREAT, S_IRUSR|S_IWUSR);
    kfd = open("key", O_RDWR|O_CREAT, S_IRUSR|S_IWUSR);

    nread = read(rfd, in, NBUFF);

    while((c = getopt(argc, argv, "ed")) != -1){
        switch(c){
            case 'e':
                   if (create_key(key, AES_BLOCK_SIZE) < 0){
                           fprintf(stderr, "create key error:%s\n", strerror(errno));
                           exit(EXIT_FAILURE);
                 }
                if (AES_set_encrypt_key(key, 128, &aes) < 0){
                          fprintf(stderr, "AES_set_encrypt_key error\n");
                          exit(1);
                 }
                write(kfd, key, AES_BLOCK_SIZE);    //如果加密,将密钥写入key文件
                aes_encrypt_cli(in, out, &aes);
                write(wfd, out, strlen(out));
                break;
            case 'd':
                read(kfd, key, AES_BLOCK_SIZE);     //如果是解密,从key文件读出密钥
                if (AES_set_decrypt_key(key, 128, &aes) < 0){
                          fprintf(stderr, "AES_set_encrypt_key error\n");
                          exit(1);
                 }
                aes_decrypt_cli(in, out,  &aes);
                write(wfd, out, strlen(out));
                break;
        }
        break;
    }

    close(rfd);
    close(wfd);
    close(kfd);
    return 0;
}



举报
锋了
发帖于3年前 2回/4K+阅
顶部