openssl 通过公钥/私钥加解密文件

Openssl 加解密文件

命令行方式加解密文件

使用openssl 的命令行进行文件的加密与解密过程,主要有两种方式:

  1. openssl 指定加密/解密算法加密
  2. openssl 指定公钥/私钥文件加密

openssl 指定加密/解密算法加密

To Encrypt:

openssl enc -e -aes-256-cbc -in un_encrypted.data -out encrypted.data

To Decrypt:

openssl enc -d -aes-256-cbc -in encrypted.data -out un_encrypted.data

Note: 1. You will be prompted for a password when encrypting or decrypt.

openssl 指定公钥/私钥文件加密

The following commands are relevant when you work with RSA keys:

  • openssl genrsa: Generates an RSA private keys.
  • openssl rsa: Manage RSA private keys (includes generating a public key from it).
  • openssl rsautl: Encrypt and decrypt files with RSA keys.

Get the public key
Let the other party send you a certificate or their public key. If they send to a certificate you can extract the public key using this command:

openssl rsa -in certificate.pem -out publickey.pem -outform PEM -pubout

Generate the random password file
Use the following command to generate the random key:

openssl rand -base64 128 -out key.bin

Do this every time you encrypt a file. Use a new key every time!

Encrypt the file with the random key
Use the following command to encrypt the large file with the random key:

openssl enc -aes-256-cbc -salt -in largefile.pdf -out largefile.pdf.enc -pass file:./bin.key

The file size doesn’t grows that much:

 $ ls -larth
  -rw-r--r-- 1 user group  40M Nov  9 21:14 Linux-Voice-Issue-020.pdf
  -rw-r--r-- 1 user group  40M Nov  9 22:03 Linux-Voice-Issue-020.pdf.enc

It’s encrypted however:

$ file Linux-Voice-Issue-020.pdf
Linux-Voice-Issue-020.pdf: PDF document, version 1.4
$ file Linux-Voice-Issue-020.pdf.enc 
Linux-Voice-Issue-020.pdf.enc: data

Encrypt the random key with the public keyfile
Use the following command to encrypt the random keyfile with the other persons public key:

openssl rsautl -encrypt -inkey publickey.pem -pubin -in key.bin -out key.bin.enc

You can safely send the key.bin.enc and the largefile.pdf.enc to the other party.

You might want to sign the two files with your public key as well.

Decrypt the random key with our private key file
If you want to decrypt a file encrypted with this setup, use the following command with your privte key (beloning to the pubkey the random key was crypted to) to decrypt the random key:

openssl rsautl -decrypt -inkey privatekey.pem -in key.bin.enc -out key.bin

This will result in the decrypted random key we encrypted the file in.

Decrypt the large file with the random key
Once you have the random key, you can decrypt the encrypted file with the decrypted key:

openssl enc -d -aes-256-cbc -in largefile.pdf.enc -out largefile.pdf -pass file:./bin.key

This will result in the decrypted large file.

openssl 程序实现公钥/私钥加解密

生成私钥:
openssl genrsa -out pri_test.key 2048

生成公钥:
openssl rsa -in pri_test.key -pubout > pub_test.key

C代码如下所示。
在Linux下的编译:gcc openssl.c -lcrypto -lssl -o test

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#define OPENSSLKEY "pri_test.key"
#define PUBLICKEY "pub_test.key"
#define BUFFSIZE 1024
char* my_encrypt(char *str,char *path_key);//
char* my_decrypt(char *str,char *path_key);//
int main(void){
    char *source="123456789";
    char *ptr_en,*ptr_de;
    printf("source is    :%s\n",source);
    ptr_en=my_encrypt(source,PUBLICKEY);
    printf("after encrypt:%s\n",ptr_en);
    ptr_de=my_decrypt(ptr_en,OPENSSLKEY);
    printf("after decrypt:%s\n",ptr_de);
    if(ptr_en!=NULL){
        free(ptr_en);
    }   
    if(ptr_de!=NULL){
        free(ptr_de);
    }   
    return 0;
}
char *my_encrypt(char *str,char *path_key){
    char *p_en;
    RSA *p_rsa;
    FILE *file;
    int flen,rsa_len;
    if((file=fopen(path_key,"r"))==NULL){
        perror("open key file error");
        return NULL;    
    }   
    if((p_rsa=PEM_read_RSA_PUBKEY(file,NULL,NULL,NULL))==NULL){
   // if((p_rsa=PEM_read_RSAPublicKey(file,NULL,NULL,NULL))==NULL){
        ERR_print_errors_fp(stdout);
        return NULL;
    }   
    flen=strlen(str);
    rsa_len=RSA_size(p_rsa);
    p_en=(unsigned char *)malloc(rsa_len+1);
    memset(p_en,0,rsa_len+1);
    if(RSA_public_encrypt(rsa_len,(unsigned char *)str,(unsigned char*)p_en,p_rsa,RSA_NO_PADDING)<0){
        return NULL;
    }
    RSA_free(p_rsa);
    fclose(file);
    return p_en;
}
char *my_decrypt(char *str,char *path_key){
    char *p_de;
    RSA *p_rsa;
    FILE *file;
    int rsa_len;
    if((file=fopen(path_key,"r"))==NULL){
        perror("open key file error");
        return NULL;
    }
    if((p_rsa=PEM_read_RSAPrivateKey(file,NULL,NULL,NULL))==NULL){
        ERR_print_errors_fp(stdout);
        return NULL;
    }
    rsa_len=RSA_size(p_rsa);
    p_de=(unsigned char *)malloc(rsa_len+1);
    memset(p_de,0,rsa_len+1);
    if(RSA_private_decrypt(rsa_len,(unsigned char *)str,(unsigned char*)p_de,p_rsa,RSA_NO_PADDING)<0){
        return NULL;
    }
    RSA_free(p_rsa);
    fclose(file);
    return p_de;
}

参考链接:https://raymii.org/s/tutorials/Encrypt_and_decrypt_files_to_public_keys_via_the_OpenSSL_Command_Line.html

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
RSA是一种非对称加密算法,其公钥私钥是成对生成的。以下是RSA生成公钥私钥以及加解密的步骤: 1. 生成RSA公钥私钥: 首先需要随机生成两个大素数p和q,计算n = p * q,再选取一个整数e(一般为65537),计算d = e^-1 mod ((p-1) * (q-1))。 生成的公钥为(n, e),私钥为(n, d)。 2. RSA加密: 假设要将明文M加密为密文C,使用公钥(n, e)进行加密,计算C = M^e mod n。 3. RSA解密: 使用私钥(n, d)进行解密,计算M = C^d mod n。 以下是一个简单的RSA加解密的C语言实现示例: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/bio.h> #include <openssl/rsa.h> #include <openssl/pem.h> int main() { // 生成RSA公钥私钥 RSA *rsa = RSA_generate_key(2048, 65537, NULL, NULL); if (rsa == NULL) { printf("Failed to generate RSA key pair.\n"); return -1; } // 获取公钥私钥 BIO *pubBio = BIO_new(BIO_s_mem()); BIO *priBio = BIO_new(BIO_s_mem()); PEM_write_bio_RSAPublicKey(pubBio, rsa); PEM_write_bio_RSAPrivateKey(priBio, rsa, NULL, NULL, 0, NULL, NULL); // 获取公钥私钥字符串 char pubKey[1024] = {0}; char priKey[4096] = {0}; BIO_read(pubBio, pubKey, sizeof(pubKey)); BIO_read(priBio, priKey, sizeof(priKey)); // 输出公钥私钥 printf("Public Key:\n%s\n", pubKey); printf("Private Key:\n%s\n", priKey); // 加密明文 char *plaintext = "Hello World!"; int plaintextLen = strlen(plaintext) + 1; char ciphertext[4096] = {0}; int ciphertextLen = RSA_public_encrypt(plaintextLen, (unsigned char *)plaintext, (unsigned char *)ciphertext, rsa, RSA_PKCS1_PADDING); if (ciphertextLen == -1) { printf("Failed to encrypt plaintext.\n"); return -1; } // 输出密文 printf("Ciphertext:\n"); for (int i = 0; i < ciphertextLen; i++) { printf("%02x", ciphertext[i]); } printf("\n"); // 解密密文 char decrypted[4096] = {0}; int decryptedLen = RSA_private_decrypt(ciphertextLen, (unsigned char *)ciphertext, (unsigned char *)decrypted, rsa, RSA_PKCS1_PADDING); if (decryptedLen == -1) { printf("Failed to decrypt ciphertext.\n"); return -1; } // 输出解密后的明文 printf("Decrypted plaintext: %s\n", decrypted); // 释放资源 RSA_free(rsa); BIO_free_all(pubBio); BIO_free_all(priBio); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值