import time from M2Crypto import X509, EVP, RSA, ASN1 def issuer_name(): """ 認證發行人名稱(專有名稱)。 Parameters: none Return: X509標準的發行人obj. """ issuer = X509.X509_Name() issuer.C = "CN" # 國家名稱 issuer.CN = "*.111cn.net" # 普通名字 issuer.ST = "Hunan Changsha" issuer.L = "Hunan Changsha" issuer.O = "Geekso Company Ltd" issuer.OU = "Geekso Company Ltd" issuer.Email = "1085015507@qq.com" return issuer def make_request(bits, cn): """ 建立一個X509標準的請求。 Parameters: bits = 認證位元 cn = 認證名稱 Return: 返回 X509 request 與 private key (EVP). """ rsa = RSA.gen_key(bits, 65537, None) pk = EVP.PKey() pk.assign_rsa(rsa) req = X509.Request() req.set_pubkey(pk) name = req.get_subject() name.C = "US" name.CN = cn req.sign(pk,'sha256') return req, pk def make_certificate_valid_time(cert, days): """ 從目前時間算起認證有效期間幾天。 Parameters: cert = 認證obj days = 認證到期的天數 Return: none """ t = long(time.time()) # 擷取目前時間 time_now = ASN1.ASN1_UTCTIME() time_now.set_time(t) time_exp = ASN1.ASN1_UTCTIME() time_exp.set_time(t + days * 24 * 60 * 60) cert.set_not_before(time_now) cert.set_not_after(time_exp) def make_certificate(bits): """ 建立認證 Parameters: bits = 證快的位元 Return: 認證, 私密金鑰 key (EVP) 與 公開金鑰 key (EVP). """ req, pk = make_request(bits, "localhost") puk = req.get_pubkey() cert = X509.X509() cert.set_serial_number(1) # 認證的序例號 cert.set_version(1) # 認證的版本 cert.set_issuer(issuer_name()) # 發行人資訊 cert.set_subject(issuer_name()) # 主題資訊 cert.set_pubkey(puk) make_certificate_valid_time(cert, 365) # 認證的到期時間 cert.sign(pk, 'sha256') return cert, pk, puk # 開始建立 cert, pk, puk= make_certificate(1024) cert.save_pem('111cn.net-cret.pem') pk.save_key('111cn.net-private.pem',cipher = None, callback = lambda: None) puk.get_rsa().save_pub_key('111cn.net-public.pem') 2.用認證加密、私密金鑰檔案解密 def geekso_encrypt_with_certificate(message, cert_loc): """ cert認證加密,可以用私密金鑰檔案解密. Parameters: message = 要加密的串 cert_loc = cert憑證路徑 Return: 加密串 or 異常串 """ cert = X509.load_cert(cert_loc) puk = cert.get_pubkey().get_rsa() # get RSA for encryption message = base64.b64encode(message) try: encrypted = puk.public_encrypt(message, RSA.pkcs1_padding) except RSA.RSAError as e: return "ERROR encrypting " + e.message return encrypted encrypted = geekso_encrypt_with_certificate('www.111cn.net','111cn.net-cret.pem') print '加密串',encrypted def geekso_decrypt_with_private_key(message, pk_loc): """ 私密金鑰解密認證產生的加密串 Parameters: message = 加密的串 pk_loc = 私密金鑰路徑 Return: 解密串 or 異常串 """ pk = RSA.load_key(pk_loc) # load RSA for decryption try: decrypted = pk.private_decrypt(message, RSA.pkcs1_padding) decrypted = base64.b64decode(decrypted) except RSA.RSAError as e: return "ERROR decrypting " + e.message return decrypted print '解密串',geekso_decrypt_with_private_key(encrypted, '111cn.net-private.pem') |