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

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

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 
#include 
 
#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 errorn");
		return -1;
	}
	OpenSSL_add_all_algorithms();//密钥有经过口令加密需要这个函数
	if ((privateRsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, (char *)PASS)) == NULL) 
	{
		printf("PEM_read_RSAPrivateKey errorn");
		return -1;
	}
	printf("%sn", (char *)privateRsa);
	fclose(fp);		
	
    fp = fopen("blackTcup.license", "rb");
    fgets(source, 1024, fp);
    printf("source is :%sn", (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 errorn");
	else
		printf("RSA_private_decrypt %sn", decryptMsg);

	
	RSA_free(publicRsa);
	RSA_free(privateRsa);
	return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5579232.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存