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;
}