#!/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常见的加密解密的更多相关文章

  1. python下RSA加密解密以及跨平台问题

    Reference:  http://www.cnblogs.com/luchanghong/archive/2012/07/18/2596886.html 项目合作需要,和其他网站通信,消息内容采用 ...

  2. python常见的加密方式

    1.前言 我们所说的加密方式都是对二进制编码的格式进行加密,对应到python中,则是我妈们的bytes. 所以当我们在Python中进行加密操作的时候,要确保我们的操作是bytes,否则就会报错. ...

  3. 16: vue + crypto-js + python前后端加密解密

    1.1 vue中使用crypto-js进行AES加密解密    参考博客:https://www.cnblogs.com/qixidi/p/10137935.html 1.初始化vue项目 vue i ...

  4. 常见的加密解密算法-MD5

    一.MD5加密概述 Message Digest Algorithm MD5(中文名为消息摘要算法第五版)为计算机安全领域广泛使用的一种散列函数,用以提供消息的完整性保护.该算法的文件号为RFC 13 ...

  5. Python下RSA加密/解密, 签名/验证

    原文是py2环境,而我的环境是py3,所以对原代码做了修改:decode(), encode() import rsa # 生成密钥 (pubkey, privkey) = rsa.newkeys(1 ...

  6. python下RSA 加密/解密,签名/验证

    基于win7 + python3.4 原文是py2环境,而我的环境是py3,所以对原代码做了修改:decode(), encode() import rsa # 生成密钥 (pubkey, privk ...

  7. python基本语法-加密解密等

    1. 编写函数,要求输入x与y,返回x和y的平方差 2. 计算1到100的平方的和 3. 编写函数,若输入为小于100的数,返回TRUE,大于100的数,返回FALSE 4. 某个公司采用公用电话传递 ...

  8. python实现RSA加密解密方法

    python3.5 安装pip 安装rsa python -m pip install rsa 我们可以生成RSA公钥和密钥,也可以load一个.pem文件进来 # -*- coding: utf-8 ...

  9. 常见MD5加密解密值及免费解密网站

    常用的MD5解密 MD5(admin,16)    = 7a57a5a743  MD5(admin,16)    = 7a57a5a743894a0e  MD5(admin888,16) = 469e ...

随机推荐

  1. 服务端缓存页面及IIS缓存设置

    缓存信息基本概念 我们在看网页的header信息时,经常看到这几个参数:Expires.Cache-Control.Last-Modified.ETag,它们是RFC 2616(HTTP/1.1)协议 ...

  2. LeetCode Output Contest Matches

    原题链接在这里:https://leetcode.com/problems/output-contest-matches/description/ 题目: During the NBA playoff ...

  3. h5废弃的标签和属性及新增的标签和属性

    一.废弃的标签和属性 1.表现性元素 a) basefont b) big c) center d) font e) strike f) tt 2.框架类元素 a) frame b) frameset ...

  4. nodejs 安装 cnpm 命令

    npm install -g cnpm --registry=https://registry.npm.taobao.org

  5. 理解SQL查询的底层原理

    阅读目录 一.SQL Server组成部分 二.查询的底层原理 本系列[T-SQL]主要是针对T-SQL的总结. T-SQL基础 [T-SQL基础]01.单表查询-几道sql查询题 [T-SQL基础] ...

  6. 流畅的python之序列

    python对开发者友好的根源在于:1.序列的泛型操作2.内置的元组和映身类型3.用缩进来架构的源码4.无需变量声明的强类型 序列数据共用的一套丰富的操作:迭代.切片.排序和拼接.内置序列类型:1.容 ...

  7. Angular5学习笔记 - 创建、运行、发布项目(一)

    一.安装脚手架 npm install -g cnpm --registry=https://registry.npm.taobao.org #安装阿里镜像 npm install -g @angul ...

  8. The lesser known pitfalls of allowing file uploads on your website

    These days a lot of websites allow users to upload files, but many don’t know about the unknown pitf ...

  9. Java8 日期和时间实用技巧

    新的日期API ZoneId: 时区ID,用来确定Instant和LocalDateTime互相转换的规则 Instant: 用来表示时间线上的一个点 LocalDate: 表示没有时区的日期, Lo ...

  10. DDD学习笔录——简介领域驱动设计的实践与原则

    DDD在存在许多DDD模式的同时,也有大量实践和指导原则,这些都是DDD思想体系成功的关键. 1.专注于核心领域 DDD强调的是在核心子域付出最多努力的需要.核心子域是你的产品会成功还是会失败的差异化 ...