python和c openssl 公钥,带口令密钥加解密

python 生成密钥,并利用公钥给字符串加密

输入 mac地址,日期,输出rsa公钥文件,带口令私钥文件和加密后的license文件。

# -*- coding: utf-8 -*-
import rsa
import sys
import time
import os

mac=sys.argv[1]
date=sys.argv[2]
expire_time = time.mktime(time.strptime(date, "%Y-%m-%d/%H:%M:%S"))

message = mac + ',' + str(int(expire_time))
print(message)

# 先生成一对密钥,然后保存.pem格式文件,当然也可以直接使用
#(pubkey, privkey) = rsa.newkeys(1024)
cmd = 'openssl genrsa  -des3 -out private.pem -passout pass:blackTcup 1024'
os.system(cmd)
cmd = 'openssl rsa -in private.pem -passin pass:blackTcup -RSAPublicKey_out -out public.pem'
os.system(cmd)

# 从公钥数据中加载公钥 
with open('public.pem','r') as f:
    pubkey = rsa.PublicKey.load_pkcs1(f.read().encode())
print(pubkey)
#print(privkey)

# 用公钥加密
crypto = rsa.encrypt(message.encode(), pubkey)
print (crypto)

flicense = open('blackTcup.license', 'wb')
flicense.write(crypto)
flicense.close()

flicense = open('blackTcup.license', 'rb')
license = flicense.read()
flicense.close()
print (license)

C调用openssl api,读取带口令密钥,并对license解密


#include <openssl/rsa.h>
#include <openssl/pem.h>
 
#define PUBLICKEY "public.pem"
#define PRIVATEKEY "private.pem"
 
#define PASS "blackTcup" //口令
 
int main(int argc, char *argv[])
{
	char source[1024];
	FILE *fp = NULL;
	RSA *publicRsa = NULL;
	RSA *privateRsa = NULL;

	if ((fp = fopen(PRIVATEKEY, "r")) == NULL) 
	{
		printf("private key path error\n");
		return -1;
	}
	OpenSSL_add_all_algorithms();//密钥有经过口令加密需要这个函数
	if ((privateRsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, (char *)PASS)) == NULL) 
	{
		printf("PEM_read_RSAPrivateKey error\n");
		return -1;
	}
	printf("%s\n", (char *)privateRsa);
	fclose(fp);		
	
    fp = fopen("blackTcup.license", "rb");
    fgets(source, 1024, fp);
    printf("source is :%s\n", (char *)source);

	int rsa_len = RSA_size(privateRsa);
	unsigned char *decryptMsg = (unsigned char *)malloc(rsa_len);
	memset(decryptMsg, 0, rsa_len);
	
	int mun =  RSA_private_decrypt(rsa_len, source, decryptMsg, privateRsa, RSA_PKCS1_PADDING);
	
	if ( mun < 0)
		printf("RSA_private_decrypt error\n");
	else
		printf("RSA_private_decrypt %s\n", decryptMsg);

	
	RSA_free(publicRsa);
	RSA_free(privateRsa);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值