python常见的加密解密
#!/usr/bin/env python ''' Python Crypto Wrapper - By Chase Schultz Currently Supports: AES-256, RSA Public Key, RSA Signing, ECC Public Key, ECC Signing Dependencies: pyCrypto - https://github.com/dlitz/pycrypto
PyECC - https://github.com/rtyler/PyECC Python Cryptography Wrapper based on pyCrypto
Copyright (C) 2011 Chase Schultz - chaschul@uat.edu This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. ''' __author__ = 'Chase Schultz'
__version__ = '0.1' import os
import base64
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
from pyecc import ECC class CryptoWrapper(): '''AES Cipher Specifics'''
blockSize = 16 #Block Size
keySize = 32 #keySize in Bytes - 32 bytes = 256bit Encryption
mode = AES.MODE_CBC #Cipher Block Mode def __init__(self): pass def __generateAESKeystring__(self):
'''Generates Pseudo Random AES Key and Base64 Encodes Key - Returns AES Key'''
key = os.urandom(self.keySize)
keyString = base64.urlsafe_b64encode(str(key))
return keyString def __extractAESKey__(self, keyString):
'''Extracts Key from Base64 Encoding'''
key = base64.urlsafe_b64decode(keyString)
if len(key) != self.keySize:
raise Exception('Error: Key Invalid')
os._exit(1)
return key def __extractCrypto__(self, encryptedContent):
'''Decodes Base64 Encoded Crypto'''
cipherText = base64.urlsafe_b64decode(encryptedContent)
return cipherText def __encodeCrypto__(self, encryptedContent):
'''Encodes Crypto with Base64'''
encodedCrypto = base64.urlsafe_b64encode(str(encryptedContent))
return encodedCrypto def aesEncrypt(self, data):
'''Encrypts Data w/ pseudo randomly generated key and base64 encodes cipher - Returns Encrypted Content and AES Key'''
key = self.__generateAESKeystring__()
encryptionKey = self.__extractAESKey__(key)
pad = self.blockSize - len(data) % self.blockSize
data = data + pad * chr(pad)
iv = os.urandom(self.blockSize)
cipherText = AES.new(encryptionKey, self.mode, iv).encrypt(data)
encryptedContent = iv + cipherText
encryptedContent = self.__encodeCrypto__(encryptedContent)
return encryptedContent, key def aesDecrypt(self, key, data):
'''Decrypts AES(base64 encoded) Crypto - Returns Decrypted Data'''
decryptionKey = self.__extractAESKey__(key)
encryptedContent = self.__extractCrypto__(data)
iv = encryptedContent[:self.blockSize]
cipherText = encryptedContent[self.blockSize:]
plainTextwithpad = AES.new(decryptionKey, self.mode, iv).decrypt(cipherText)
pad = ord(plainTextwithpad[-1])
plainText = plainTextwithpad[:-pad]
return plainText def generateRSAKeys(self,keyLength):
'''Generates Public/Private Key Pair - Returns Public / Private Keys'''
private = RSA.generate(keyLength)
public = private.publickey()
privateKey = private.exportKey()
publicKey = public.exportKey()
return privateKey, publicKey def rsaPublicEncrypt(self, pubKey, data):
'''RSA Encryption Function - Returns Encrypted Data'''
publicKey = RSA.importKey(pubKey)
encryptedData = publicKey.encrypt(data,'')
return encryptedData def rsaPrivateDecrypt(self, privKey, data):
'''RSA Decryption Function - Returns Decrypted Data'''
privateKey = RSA.importKey(privKey)
decryptedData = privateKey.decrypt(data)
return decryptedData def rsaSign(self, privKey, data):
'''RSA Signing - Returns an RSA Signature'''
privateKey = RSA.importKey(privKey)
if privateKey.can_sign() == True:
digest = SHA256.new(data).digest()
signature = privateKey.sign(digest,'')
return signature
else:
raise Exception("Error: Can't Sign with Key") def rsaVerify(self, pubKey, data, signature):
'''Verifies RSA Signature based on Data received - Returns a Boolean Value'''
publicKey = RSA.importKey(pubKey)
digest = SHA256.new(data).digest()
return publicKey.verify(digest, signature) def eccGenerate(self):
'''Generates Elliptic Curve Public/Private Keys'''
ecc = ECC.generate()
publicKey = ecc._public
privateKey = ecc._private
curve = ecc._curve
return privateKey, publicKey, curve def eccEncrypt(self,publicKey, curve, data):
'''Encrypts Data with ECC using public key'''
ecc = ECC(1, public=publicKey, private='', curve=curve)
encrypted = ecc.encrypt(data)
return encrypted def eccDecrypt(self,privateKey, curve, data):
'''Decrypts Data with ECC private key'''
ecc = ECC(1, public='', private=privateKey, curve=curve)
decrypted = ecc.decrypt(data)
return decrypted def eccSign(self, privateKey, curve, data):
'''ECC Signing - Returns an ECC Signature'''
ecc = ECC(1, public='', private=privateKey, curve=curve)
signature = ecc.sign(data)
return signature def eccVerify(self, publicKey, curve, data, signature):
'''Verifies ECC Signature based on Data received - Returns a Boolean Value'''
ecc = ECC(1, public=publicKey, private='', curve=curve)
return ecc.verify(data, signature) if __name__ == '__main__':
'''Usage Examples''' print ''' Python Crypto Wrapper - By Chase Schultz Currently Supports: AES-256, RSA Public Key, RSA Signing, ECC Public Key, ECC Signing Dependencies: pyCrypto - https://github.com/dlitz/pycrypto
PyECC - https://github.com/rtyler/PyECC ''' '''Instantiation of Crypto Wrapper and Message'''
crypto = CryptoWrapper();
message = 'Crypto Where art Thou... For ye art a brother...'
print 'Message to be Encrypted: %s\n' % message '''AES ENCRYPTION USAGE'''
'''***Currently Supporting AES-256***'''
encryptedAESContent, key = crypto.aesEncrypt(message)
print 'Encrypted AES Message: %s\nEncrypted with Key: %s' % (encryptedAESContent, key)
decryptedAESMessage = crypto.aesDecrypt(key, encryptedAESContent)
print '\nDecrypted AES Content: %s\n' % decryptedAESMessage '''RSA ENCRYPTION USAGE'''
privateKey, publicKey = crypto.generateRSAKeys(2048) encryptedRSAContent = crypto.rsaPublicEncrypt(publicKey, message)
print 'Encrypted RSA Message with RSA Public Key: %s\n' % encryptedRSAContent
decryptedRSAMessage = crypto.rsaPrivateDecrypt(privateKey, encryptedRSAContent)
print '\nDecrypted RSA Content with RSA Private Key: %s\n' % decryptedRSAMessage '''RSA SIGNING USAGE'''
signature = crypto.rsaSign(privateKey, message)
print 'Signature for message is: %s\n ' % signature
if crypto.rsaVerify(publicKey, message, signature) is False:
print 'Could not Verify Message\n'
else:
print 'Verified RSA Content\n' '''ECC ENCRYPTION USAGE'''
eccPrivateKey, eccPublicKey, eccCurve = crypto.eccGenerate() encryptedECCContent = crypto.eccEncrypt(eccPublicKey, eccCurve , message)
print 'Encrypted ECC Message with ECC Public Key: %s\n' % encryptedECCContent
decryptedECCContent = crypto.eccDecrypt(eccPrivateKey, eccCurve, encryptedECCContent)
print 'Decrypted ECC Content with ECC Private: %s\n' % decryptedECCContent '''ECC SIGNING USAGE'''
signature = crypto.eccSign(eccPrivateKey, eccCurve, message)
print 'Signature for message is: %s\n ' % signature
if crypto.eccVerify(eccPublicKey, eccCurve, message, signature) is False:
print 'Could not Verify Message\n'
else:
print 'Verified ECC Content\n'
python常见的加密解密的更多相关文章
- python下RSA加密解密以及跨平台问题
Reference: http://www.cnblogs.com/luchanghong/archive/2012/07/18/2596886.html 项目合作需要,和其他网站通信,消息内容采用 ...
- python常见的加密方式
1.前言 我们所说的加密方式都是对二进制编码的格式进行加密,对应到python中,则是我妈们的bytes. 所以当我们在Python中进行加密操作的时候,要确保我们的操作是bytes,否则就会报错. ...
- 16: vue + crypto-js + python前后端加密解密
1.1 vue中使用crypto-js进行AES加密解密 参考博客:https://www.cnblogs.com/qixidi/p/10137935.html 1.初始化vue项目 vue i ...
- 常见的加密解密算法-MD5
一.MD5加密概述 Message Digest Algorithm MD5(中文名为消息摘要算法第五版)为计算机安全领域广泛使用的一种散列函数,用以提供消息的完整性保护.该算法的文件号为RFC 13 ...
- Python下RSA加密/解密, 签名/验证
原文是py2环境,而我的环境是py3,所以对原代码做了修改:decode(), encode() import rsa # 生成密钥 (pubkey, privkey) = rsa.newkeys(1 ...
- python下RSA 加密/解密,签名/验证
基于win7 + python3.4 原文是py2环境,而我的环境是py3,所以对原代码做了修改:decode(), encode() import rsa # 生成密钥 (pubkey, privk ...
- python基本语法-加密解密等
1. 编写函数,要求输入x与y,返回x和y的平方差 2. 计算1到100的平方的和 3. 编写函数,若输入为小于100的数,返回TRUE,大于100的数,返回FALSE 4. 某个公司采用公用电话传递 ...
- python实现RSA加密解密方法
python3.5 安装pip 安装rsa python -m pip install rsa 我们可以生成RSA公钥和密钥,也可以load一个.pem文件进来 # -*- coding: utf-8 ...
- 常见MD5加密解密值及免费解密网站
常用的MD5解密 MD5(admin,16) = 7a57a5a743 MD5(admin,16) = 7a57a5a743894a0e MD5(admin888,16) = 469e ...
随机推荐
- BZOJ3075,LG3082 [USACO13MAR]项链Necklace
题意 Bessie the cow has arranged a string of N rocks, each containing a single letter of the alphabet, ...
- Makefile中的路径
使用 $(shell pwd) 可以在Makefile中指定为当前Makefile所在目录的路径
- HIVE-如何查看执行日志
HIVE既然是运行在hadoop上,最后又被翻译为MapReduce程序,通过yarn来执行.所以我们如果想解决HIVE中出现的错误,需要分成几个过程 HIVE自身翻译成为MR之前的解析错误 Hado ...
- java中final用法
1.修饰基础数据成员 这是final的主要用途,其含义相当于C/C++的const,即该成员被修饰成常量,不可修改. 2.修饰类或者对象的引用的final 在java中我们无法让对象被修饰为final ...
- PIX v2版本中Query 失败时, ERR段的构造
在ITI-9中描述PIX query事务的几个TestCase场景.其中有些是对于Query失败的描述. ERR 段包含Error location, Error code, Error code t ...
- Angular5学习笔记 - 集成Bootstrap、Jquery、Tether(三)
一.添加配置 cnpm i bootstrap jquery tether --save 添加后效果 二.配置添加样式和js的引用 打开.angular-cli.json文件,在styles和scri ...
- POJ1063Cable master(二分搜索)
Cable master Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 36288 Accepted: 7743 Des ...
- Oracle存储过程返回
IF IN_DN_NUMBER IS NOT NULL THEN SELECT COUNT(*) INTO V_HAS FROM SALEFROMSTORE WHERE ORDERID = IN_DN ...
- python第二十三天-----Tornado
Tornado是一个轻量级完整的web框架,在Linux系统下它会使用epoll,是一个异步非阻塞的web服务器框架,对于实时应用来说很理想,想想同是异步非阻塞的nginx的残暴程度就知道了 1.路由 ...
- PostgreSQL 9.5 客户端认证
PostgreSQL 9.5 客户端认证 当一个客户端应用连接一个数据库服务器时,它将指定以哪个PostgreSQL 数据库用户名连接,就像我们以一个特定用户登录一台 Unix 计算机一样.在 SQL ...