openssl对文件加解密

openssl对文件加解密


首先看是如何使用openssl命令行对文件加解密:

1.带密码的私钥文件生成:
openssl genpkey -algorithm RSA -out rsa.pem -pass pass:[email protected] -aes256

2.从私钥里提取公钥:
openssl pkey -in rsa.pem -out pub.pem -pubout

3.利用公钥加密文件:
openssl rsautl -encrypt -inkey pub.pem -pubin -in in.txt -out out.txt

4.利用私钥解密文件:
openssl rsautl -decrypt -inkey rsa.pem -in out.txt -out out1.txt

下面是C的demo:
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;

int main(int argc, char *argv[])
{
// 原始明文
unsigned char plain[256]=“1111111”;

// 用来存放密文
unsigned char encrypted[1024];

// 用来存放解密后的明文
unsigned char decrypted[1024];


// 公钥和私钥文件
const char* pub_key="pub.pem";
const char* priv_key="rsa.pem";

// -------------------------------------------------------
// 利用公钥加密明文的过程
// -------------------------------------------------------

// 打开公钥文件
FILE* pub_fp=fopen(pub_key,"r");
if(pub_fp==NULL){
    printf("failed to open pub_key file %s!\n", pub_key);
    return -1;
}

// 从文件中读取公钥
RSA* rsa1=PEM_read_RSA_PUBKEY(pub_fp, NULL, NULL, NULL);
if(rsa1==NULL){
    printf("unable to read public key!\n");
    return -1;
}

if(strlen((const char*)plain)>=RSA_size(rsa1)-41){
    printf("failed to encrypt\n");
    return -1;
}
fclose(pub_fp);

// 用公钥加密
int len=RSA_public_encrypt(strlen((const char*)plain), plain, encrypted, rsa1, RSA_PKCS1_PADDING);
if(len==-1 ){
    printf("failed to encrypt\n");
    return -1;
}

// 输出加密后的密文
FILE* fp=fopen("out.txt","w");
if(fp){
    fwrite(encrypted,len,1,fp);
    fclose(fp);
}
// -------------------------------------------------------
// 利用私钥解密密文的过程
// -------------------------------------------------------
// 打开私钥文件
FILE* priv_fp=fopen(priv_key,"r");
if(priv_fp==NULL){
    printf("failed to open priv_key file %s!\n", priv_key);
    return -1;
}

// 从文件中读取私钥
RSA *rsa2 = RSA_new();
char passwd[]="[email protected]";
OpenSSL_add_all_algorithms();
rsa2 = PEM_read_RSAPrivateKey(priv_fp, NULL, NULL, passwd);
//PEM_read_bio_RSAPrivateKey
if(rsa2==NULL){
    printf("unable to read private key!\n");
    return -1;
}


// 用私钥解密
len=RSA_private_decrypt(len, encrypted, decrypted, rsa2, RSA_PKCS1_PADDING);
if(len==-1){
    printf("failed to decrypt!\n");
    return -1;
}
fclose(priv_fp);


// 输出解密后的明文
decrypted[len]=0;
printf("%s\n",decrypted);
return 0;

}

你可能感兴趣的:(openssl,openssl,rsa,加密解密)