涅磐重生

要么不做,要做就做到最好!

EVP加密解密编程

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

阅读更多
版权声明:有不正确的地方,还望各位指正指导,Thanks! https://blog.csdn.net/a544258023/article/details/51549674
文章标签: des cbc openssl
个人分类: C/C++
上一篇远程传输文件编程之FTP
下一篇scala的hbase api使用
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭