使用openssl实现ras-密钥创建-加密-解密(c语言)

一、下载安装过程
openssl下载安装过程
二、使用介绍
1-使用指令实现
/*******************************************************************************************
**1.openssl genrsa -out test.key 1024 —>生成一个密钥
在这里插入图片描述

**2.openssl rsa -in test.key -pubout -out test_pub.key —>提取密钥中的公钥
在这里插入图片描述
**3.openssl rsautl -encrypt -in hello -inkey test_pub.key -pubin -out hello.en
** —>-in指定要加密的文件,-inkey指定密钥,-pubin表明是用纯公钥文件加密,-out为加密后的文件。
在这里插入图片描述

**4.openssl rsautl -decrypt -in hello.en -inkey test.key -out hello.de
** —>-in指定被加密的文件,-inkey指定私钥文件,-out为解密后的文件。
在这里插入图片描述

********************************************************************************************/

2.c代码实现

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#include<openssl/rsa.h>
#include<openssl/pem.h>
#include<openssl/err.h>
#include<openssl/bio.h>
#include<openssl/evp.h>


#define PUB_KEY  "./public_key.txt"
#define PRI_KEY  "./prive_key.txt"


/*************************
**1---------------创建密钥
**************************/
void creat_key()
{	
	RSA *r = RSA_new();//初始化RSA结构体
	int bits=1024;
	BIGNUM *e = BN_new();//新生成一个BIGNUM结构
	BN_set_word(e,65537);//设置e为65537 

/***
**RSA_generate_key_ex:生成一对钥匙
**参数1:RSA结构         参数2:大小
**参数3:BIGNUM结构 参数4:一般置空
******/
	RSA_generate_key_ex(r, bits, e, NULL);

/****
**int RSA_print_fp(FILE *fp, const RSA *r,int offset);
**							-----将生成的密钥输出到文件
**参数1:文件fp指针              参数2:RSA结构体
**参数3:打印偏移量offset是为了调整输出格式
******/
	//RSA_print_fp(stdout,r,0);
	
	BIO *out;
	
/****
**BIO *BIO_new_file(const char *filename, const char *mode);
*****/
	out = BIO_new_file("./prive_key.txt","wr");

/***
**PEM_write_bio_RSAPrivateKey(BIO *bp, RSA *x, const EVP_CIPHER *enc,
**		unsigned char *kstr, int klen,pem_password_cb *cb, void *u);
**对RSA结构的RSA私钥进行PEM格式的写处理——————私钥
*****/
	int ret=PEM_write_bio_RSAPrivateKey(out,r,NULL,NULL,0,NULL,NULL);
	printf("私钥:%d\n",ret);

/***
**函数原型是一个宏函数
**#define BIO_flush(b) (int)BIO_ctrl(b,BIO_CTRL_FLUSH,0,NULL)
**作用:将BIO内部缓冲区的数据都写出去
*****/
	BIO_flush(out);
    BIO_free(out);

	out=BIO_new_file("./public_key.txt","wr");
	//写入公钥
	ret=PEM_write_bio_RSAPublicKey(out,r);
	printf("公钥:%d\n",ret);
    BIO_flush(out);
    BIO_free(out);
	
	BN_free(e);
    RSA_free(r);
}

/***************************
**2------------公钥加密
****************************/
char *pub_encryption(char *str,char *pubkey_path)
{
	RSA *rsa = NULL;
    FILE *fp = NULL;
    char *en = NULL;
    int len = 0;
    int rsa_len = 0;
 
    if ((fp = fopen(pubkey_path, "r")) == NULL) {
		printf("=====1======\n");
        return NULL;
    }
 
    /* 读取公钥PEM,PUBKEY格式PEM使用PEM_read_RSA_PUBKEY函数 */
    if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) == NULL) {
		perror(" PEM_read_RSAPublicKey error");
		close(fp);
		printf("=======2====\n");
        return NULL;
    }
 
   // RSA_print_fp(stdout, rsa, 0);
 
    len = strlen(str);
    rsa_len = RSA_size(rsa);

	//为加密后的内容 申请空间(根据秘钥的长度+1)
    en = (char *)malloc(rsa_len + 1);
    memset(en, 0, rsa_len + 1);

//RSA_public_encrypt-->加解密函数
//函数原型:int RSA_public_encrypt(intflen, const unsigned char *from, unsigned char *to, RSA *rsa,int padding); 
//参数1:密钥长度          参数2:加密的内容            参数3:为加密后内容申请的空间       
//参数4:密钥            参数5:有三种模式
	if (RSA_public_encrypt(rsa_len, (unsigned char *)str, (unsigned char*)en, rsa, RSA_NO_PADDING) < 0) {
		perror(" RSA_public_encrypt error");
		close(fp);
		printf("========3===\n");
		return NULL;
    }
 
    RSA_free(rsa);
    fclose(fp);
 	printf("===========en %s \n",en);
    return en;
}

char *my_decrypt(char *str, char *prikey_path)
{
    RSA *rsa = NULL;
    FILE *fp = NULL;
    char *de = NULL;
    int rsa_len = 0;
 
    if ((fp = fopen(prikey_path, "r")) == NULL) {
        return NULL;
    }
 
    if ((rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL)) == NULL) {
		perror(" PEM_read_RSAPrivateKey error");
		close(fp);
        return NULL;
    }
 
   // RSA_print_fp(stdout, rsa, 0);
 
    rsa_len = RSA_size(rsa);

	//为解密后的内容 申请空间(根据秘钥的长度+1)
    de = (char *)malloc(rsa_len + 1);
    memset(de, 0, rsa_len + 1);

	//解密函数
    if (RSA_private_decrypt(rsa_len, (unsigned char *)str, (unsigned char*)de, rsa, RSA_NO_PADDING) < 0) {
		perror(" RSA_private_decrypt error");
		close(fp);
		return NULL;
    }
 
    RSA_free(rsa);
    fclose(fp);
 
    return de;
}


int main()
{
	char *source="hello world!";
	creat_key();
	char *en = NULL;
    char *de = NULL;
	en=pub_encryption(source,PUB_KEY);

	de= my_decrypt(en, PRI_KEY);
    printf("dec is: %s\n", de);
	
	return 0;
}

编译运行结果
在这里插入图片描述

  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在iOS中使用OpenSSL实现AES-GCM和ECB加密解密需要以下步骤: 1. 下载OpenSSL库并将其添加到iOS项目中。 2. 导入OpenSSL库头文件: ```objc #import <openssl/evp.h> #import <openssl/aes.h> ``` 3. 实现AES-GCM加密解密: ```objc // AES-GCM加密 + (NSData *)AESGCMEncryptWithKey:(NSData *)key iv:(NSData *)iv aad:(NSData *)aad plainText:(NSData *)plainText tagLength:(NSUInteger)tagLength { EVP_CIPHER_CTX *ctx; int len, outlen; unsigned char *outbuf; NSData *tag = nil; NSData *cipherText = nil; // 初始化EVP_CIPHER_CTX ctx = EVP_CIPHER_CTX_new(); EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL); // 设置key和iv EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)iv.length, NULL); EVP_EncryptInit_ex(ctx, NULL, NULL, key.bytes, iv.bytes); // 设置aad EVP_EncryptUpdate(ctx, NULL, &len, aad.bytes, (int)aad.length); // 加密明文 outbuf = malloc(plainText.length + AES_BLOCK_SIZE); EVP_EncryptUpdate(ctx, outbuf, &len, plainText.bytes, (int)plainText.length); cipherText = [NSData dataWithBytes:outbuf length:len]; free(outbuf); // 获取tag outbuf = malloc(tagLength); EVP_EncryptFinal_ex(ctx, outbuf, &outlen); tag = [NSData dataWithBytes:outbuf length:outlen]; free(outbuf); // 释放EVP_CIPHER_CTX EVP_CIPHER_CTX_free(ctx); // 返回加密结果和tag NSMutableData *resultData = [NSMutableData dataWithData:cipherText]; [resultData appendData:tag]; return resultData; } // AES-GCM解密 + (NSData *)AESGCMDecryptWithKey:(NSData *)key iv:(NSData *)iv aad:(NSData *)aad cipherText:(NSData *)cipherText tagLength:(NSUInteger)tagLength { EVP_CIPHER_CTX *ctx; int len, outlen; unsigned char *outbuf; NSData *tag = nil; NSData *plainText = nil; // 初始化EVP_CIPHER_CTX ctx = EVP_CIPHER_CTX_new(); EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL); // 设置key和iv EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, (int)iv.length, NULL); EVP_DecryptInit_ex(ctx, NULL, NULL, key.bytes, iv.bytes); // 设置aad EVP_DecryptUpdate(ctx, NULL, &len, aad.bytes, (int)aad.length); // 解密文 outbuf = malloc(cipherText.length); EVP_DecryptUpdate(ctx, outbuf, &len, cipherText.bytes, (int)cipherText.length - tagLength); plainText = [NSData dataWithBytes:outbuf length:len]; free(outbuf); // 获取tag tag = [cipherText subdataWithRange:NSMakeRange(cipherText.length - tagLength, tagLength)]; EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, (int)tag.length, (void *)tag.bytes); // 验证tag if (EVP_DecryptFinal_ex(ctx, NULL, &outlen) <= 0) { return nil; // tag验证失败 } // 释放EVP_CIPHER_CTX EVP_CIPHER_CTX_free(ctx); // 返回解密结果 return plainText; } ``` 4. 实现ECB加密解密: ```objc // ECB加密 + (NSData *)ECBEncryptWithKey:(NSData *)key plainText:(NSData *)plainText { EVP_CIPHER_CTX *ctx; int len; unsigned char *outbuf; NSData *cipherText = nil; // 初始化EVP_CIPHER_CTX ctx = EVP_CIPHER_CTX_new(); EVP_EncryptInit_ex(ctx, EVP_aes_256_ecb(), NULL, key.bytes, NULL); // 加密明文 outbuf = malloc(plainText.length + AES_BLOCK_SIZE); EVP_EncryptUpdate(ctx, outbuf, &len, plainText.bytes, (int)plainText.length); cipherText = [NSData dataWithBytes:outbuf length:len]; free(outbuf); // 释放EVP_CIPHER_CTX EVP_CIPHER_CTX_free(ctx); // 返回加密结果 return cipherText; } // ECB解密 + (NSData *)ECBDecryptWithKey:(NSData *)key cipherText:(NSData *)cipherText { EVP_CIPHER_CTX *ctx; int len; unsigned char *outbuf; NSData *plainText = nil; // 初始化EVP_CIPHER_CTX ctx = EVP_CIPHER_CTX_new(); EVP_DecryptInit_ex(ctx, EVP_aes_256_ecb(), NULL, key.bytes, NULL); // 解密文 outbuf = malloc(cipherText.length); EVP_DecryptUpdate(ctx, outbuf, &len, cipherText.bytes, (int)cipherText.length); plainText = [NSData dataWithBytes:outbuf length:len]; free(outbuf); // 释放EVP_CIPHER_CTX EVP_CIPHER_CTX_free(ctx); // 返回解密结果 return plainText; } ``` 以上就是使用OpenSSL实现AES-GCM和ECB加密解密的步骤,需要注意的是,在iOS13及以上版本中,Apple已经将OpenSSL库废弃,推荐使用自带的CryptoKit框架实现加密解密

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值