关闭

EVP加密解密编程

标签: descbcopenssl
196人阅读 评论(0) 收藏 举报
分类:

EVP加密解密方式很多,本文采用DES + cbc模式进行


test.c

#include <openssl/des.h>
#include <openssl/evp.h>

//加密
int DesEncrypt(const unsigned char *key,
                                   const unsigned char *iv,
                                   unsigned char *inbuf, int inlen,
                                   unsigned char *outbuf, int *outlen)
{
    EVP_CIPHER_CTX ctx;

    EVP_CIPHER_CTX_init(&ctx);
    EVP_EncryptInit_ex(&ctx, EVP_des_cbc(), NULL, key, iv);

    if (!EVP_EncryptUpdate(&ctx, outbuf, outlen, inbuf, inlen))
    {
        return 1;
    }

    /* Buffer passed to EVP_EncryptFinal() must be after data just
     * encrypted to avoid overwriting it.*/
    int tmplen = 0;

    if (!EVP_EncryptFinal_ex(&ctx, outbuf + *outlen, &tmplen))
    {
        return 0;
    }

    *outlen += tmplen;
    EVP_CIPHER_CTX_cleanup(&ctx);
    return 1;
}

//解密
int DesDecrypt(const unsigned char *key,
                                   const unsigned char *iv,
                                   unsigned char *inbuf, int inlen,
                                   unsigned char *outbuf, int *outlen)
{
    EVP_CIPHER_CTX ctx;

    EVP_CIPHER_CTX_init(&ctx);
    EVP_DecryptInit_ex(&ctx, EVP_des_cbc(), NULL, key, iv);

    if (!EVP_DecryptUpdate(&ctx, outbuf, outlen, inbuf, inlen))
    {
        return 0;
    }

    int tmplen = 0;

    //if (!EVP_DecryptFinal_ex(&ctx, outbuf + *outlen, &tmplen))
    //{
    //    return 0;
    //}

    *outlen += tmplen;
    EVP_CIPHER_CTX_cleanup(&ctx);
    return 1;
}

int main()
{
    char key[]="wj14mrIW";
    char iv[]="OXztOtqc";

    char inbuf[128]="1234";
    char outbuf[128]={0};
    char tmpbuf[128]={0};
    int outLen = 0;
 int tmpLen = 0;
    //加密内容
    DesEncrypt(key,iv,inbuf,strlen(inbuf),outbuf,&outLen);
    printf("outbuf=%s,outLen=%d\n",outbuf,outLen);
 //解密内容
    DesDecrypt(key,iv,outbuf,strlen(outbuf),tmpbuf,&tmpLen);
    printf("tmpbuf=%s,tmpLen=%d\n",tmpbuf,tmpLen);
}
编译:gcc test.c -o test -lssl -lcrypto

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:8857次
    • 积分:318
    • 等级:
    • 排名:千里之外
    • 原创:22篇
    • 转载:0篇
    • 译文:0篇
    • 评论:16条
    文章分类
    最新评论