#!/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. LCD升压反压驱动电路

    在嵌入式系统里,较多场合需要LCD人机界面.分析以下LCD驱动电路. LCD_VIN是3.6~5V,经过DC/DC burst升压得到LCD_AVDD,LCD_AVDD为LCD需要的模拟电压,根据LC ...

  2. C++语言对C的增强(1)——实用性、变量检测、struct类型、C++中所有变量和函数都必须有类型、bool类型、三目运算符

    1.“实用性”增强 C语言中的变量都必须在作用域开始的位置定义,C++中更强调语言的“实用性”,所有的变量都可以在需要使用时再定义. 2.变量检测加强 在C语言中,重复定义多个同名的全局变量是合法的: ...

  3. [转]NME Android目标中文输入问题完美解决!

    最近研究了一下haxe,发现蛮牛逼的,转几篇知识帖 haXe开发笔记:中文问题的小结 * .hx源文件中如果包含中文,要保存成UTF-8编码才能够正确被haXe编译器解析,是否包含BOM(Byte O ...

  4. Windbg内核调试之二: 常用命令

    运用Windbg进行内核调试, 熟练的运用命令行是必不可少的技能. 但是面对众多繁琐的命令, 实在是不可能全部的了解和掌握. 而了解Kernel正是需要这些命令的指引, 不断深入理解其基本的内容. 下 ...

  5. angular track by $index

    这个东西配合删除数组时会出现永远删除uoloadPicArr这个数组的最后一个一项 其用法是主要用在当ng-repeat循环时如果其内部的dom元素有id属性存在 可以避免页面出现相同的id  只是一 ...

  6. C# 单例模式代码

    原文地址:http://blog.jobbole.com/101746/ 代码一: public sealed class Singleton     {         static Singlet ...

  7. Hybrid APP混合开发

    写在前面: 由于业务需要,接触到一个Hybrid APP混合开发的项目.当时是第一次接触混合开发,有一些经验和总结,欢迎各位一起交流学习~ 1.混合开发概述 Hybrid App主要以JS+Nativ ...

  8. HDU5468(dfs序+容斥原理)

    Puzzled Elena Time Limit: 5000/2500 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)T ...

  9. java流。基础

    总结:read()方法返回类型是int型??不知道该怎么用好循环> package com.da; import java.io.*; public class fgbv { public st ...

  10. Mybatis多参数查询映射

    一.单个参数: public List<XXBean> getXXBeanList(String xxCode); <select id="getXXXBeanList&q ...