def encryptUrlQuery(self, plain_string): log = logging.getLogger('csdt') log.info("RegisterPublic.encryptUrlQuery()") # Create a nonce nonce = random.randint(1, 4000000000) log.debug("nonce = %d" % nonce) # Appends nonce to beginning of plaintext and has the ";" as the deliminator plaintext = str(nonce) + ";" + plain_string log.debug("plaintext = %s" % plaintext) key = ezPyCrypto.key(1024) # Path = ../../../../email_key.pub path = os.path.join(os.path.dirname(__file__), '..', '..', '..', '..', 'email_key.pub') fd = open(path, "rb") public_key = fd.read() fd.close() key.importKey(public_key) plaintext_ascii = unicodedata.normalize('NFKD', plaintext).encode('ascii', 'ignore') ciphertext = key.encStringToAscii(plaintext_ascii) return ciphertext
def do_key_generate(self): if self.config.get('gringotts', 'key'): print ' existing key found - skipping' return import ezPyCrypto print ' Generating 2048-bit keypair - could take a while...' k = ezPyCrypto.key(2048) self.config.set('gringotts', 'key', k.exportKeyPrivate()) self.config.save() k = ezPyCrypto.key(str(self.config.get('gringotts','key'))) secret = 'Something noone should know' if secret == k.decString(k.encString(secret)): print ' Encryption test successful' print ' done.'
def do_key_generate(self): if self.config.get('gringotts', 'key'): print ' existing key found - skipping' return import ezPyCrypto print ' Generating 2048-bit keypair - could take a while...' k = ezPyCrypto.key(2048) self.config.set('gringotts', 'key', k.exportKeyPrivate()) self.config.save() k = ezPyCrypto.key(str(self.config.get('gringotts', 'key'))) secret = 'Something noone should know' if secret == k.decString(k.encString(secret)): print ' Encryption test successful' print ' done.'
def createKeyPair(self, bitlength = None): """ Creates a key pair for the algorithm. """ if bitlength == None: bitlength = config.rsa_keylength privatekey = ezPyCrypto.key(bitlength,'RSA') return privatekey.exportKeyPrivate()
def sign(doc): fd = open("id_rsa") pubprivkey = fd.read() fd.close() k = ezPyCrypto.key(pubprivkey) sig = k.signString(doc) return sig
def getPublicKey(self, privateKeySt = None): """ Returns the public part of the key pair. """ if privateKeySt == None: privateKeySt = self._privateKey if privateKeySt == None: return None key = ezPyCrypto.key(privateKeySt) return key.exportKey()
def expand_macro(self, formatter, names, content): if not content: edit = '' text = "''Gringlet Name Missing''" acl = '' elif not re.match(r'^[a-zA-Z0-9]+$', content): edit = '' text = tag.em( "Invalid Gringlet Name - only letters and numbers allowed") acl = '' else: db = self.env.get_db_cnx() cursor = db.cursor() cursor.execute( 'SELECT text,acl FROM gringotts WHERE name=%s AND version=' '(SELECT MAX(version) FROM gringotts WHERE name=%s)', (content, content)) try: text, acl = cursor.fetchone() key = str(self.config.get('gringotts', 'key')) k = ezPyCrypto.key(key) text = wiki_to_html(k.decStringFromAscii(text), self.env, formatter.req) edit = 'Edit' except: edit = 'Create' text = tag.em("No Gringlet called \"%s\" found" % content) acl = '' if acl: if not validate_acl(formatter.req, acl): text = tag.em( "You do not have permission to view the \"%s\" Gringlet." % content) edit = '' control = None if edit: control = tag.div(tag.a(edit, href=(formatter.href.gringotts() + "/" + content + "?action=edit")), class_="gringottcontrol") # Use eight divs for flexible frame styling return tag.div(tag.div(tag.div(tag.div(tag.div(tag.div( tag.div(tag.div(tag.div(text, class_="gringottcontent") + control, class_="gringott"), class_="gringott"), class_="gringott"), class_="gringott"), class_="gringott"), class_="gringott"), class_="gringott"), class_="gringottframe")
def expand_macro(self, formatter, names, content): if not content: edit = '' text = "''Gringlet Name Missing''" acl = '' elif not re.match(r'^[a-zA-Z0-9]+$', content): edit = '' text = tag.em("Invalid Gringlet Name - only letters and numbers allowed") acl = '' else: db = self.env.get_db_cnx() cursor = db.cursor() cursor.execute('SELECT text,acl FROM gringotts WHERE name=%s AND version=' '(SELECT MAX(version) FROM gringotts WHERE name=%s)', (content, content)) try: text,acl = cursor.fetchone() key = str(self.config.get('gringotts', 'key')) k = ezPyCrypto.key(key) text = wiki_to_html(k.decStringFromAscii(text), self.env, formatter.req) edit = 'Edit' except: edit = 'Create' text = tag.em("No Gringlet called \"%s\" found" % content) acl = '' if acl: if not validate_acl(formatter.req, acl): text = tag.em("You do not have permission to view the \"%s\" Gringlet." % content) edit = '' control = None if edit: control = tag.div(tag.a(edit, href=(formatter.href.gringotts() + "/" + content + "?action=edit")), class_="gringottcontrol") # Use eight divs for flexible frame styling return tag.div( tag.div( tag.div( tag.div( tag.div( tag.div( tag.div( tag.div( tag.div(text, class_="gringottcontent") + control, class_="gringott"), class_="gringott"), class_="gringott"), class_="gringott"), class_="gringott"), class_="gringott"), class_="gringott"), class_="gringottframe")
def __cryptKey(self, url): if not self.useCrypto_: return None key = self.__key(url) try: cryptKey = self.keys_[key] except KeyError: cryptKey = ezPyCrypto.key(passphrase=url) self.keys_[key] = cryptKey return cryptKey
def render_macro(self, req, name, content): # args will be null if the macro is called without parenthesis. if not content: edit = '' text = "''Gringlet Name Missing''" acl = '' elif not re.match(r'^[a-zA-Z0-9]+$', content): edit = '' text = "<em>Invalid Gringlet Name - only letters and numbers allowed</em>" acl = '' else: db = self.env.get_db_cnx() cursor = db.cursor() cursor.execute('SELECT text,acl FROM gringotts WHERE name=%s AND version=' '(SELECT MAX(version) FROM gringotts WHERE name=%s)', (content, content)) try: text,acl = cursor.fetchone() key = str(self.config.get('gringotts', 'key')) k = ezPyCrypto.key(key) text = wiki_to_html(k.decStringFromAscii(text), self.env, req) edit = 'Edit' except: edit = 'Create' text = "<em>No Gringlet called "%s" found</em>" % content acl = '' if acl: if not validate_acl(req, acl): text = "<em>You do not have permission to view the "%s" Gringlet.</em>" % content edit = '' control = '' if edit: control = ('<div class="gringottcontrol">' + \ '<a href="%s/%s">' + edit + '</a>' + \ '</div>') % (req.href.gringotts(), content) # Use eight divs for flexible frame styling html = '<div class="gringottframe"><div class="gringott">' + \ '<div class="gringott"><div class="gringott">' + \ '<div class="gringott"><div class="gringott">' + \ '<div class="gringott"><div class="gringott">' + \ '<div class="gringottcontent">' + \ text + \ '</div>' + \ control + \ '</div></div></div></div></div></div></div></div>' return html
def encrypt(self, plaintext, keyst): """ Encrypts the plain text. @param plaintext: String to be encrypted @type plaintext: C{String} @param keyst: Key to use for encryption (should be the public key of the receiver) - in PyCrypto Format! @type keyst: C{String} @return: The corresponding cipher text @rtype: C{String} """ key = ezPyCrypto.key() key.importKey(keyst) cipher = key.encStringToAscii(plaintext) return cipher
def decrypt(self, ciphertext, keyst = None): """ Decrypts the ciphertext. @param ciphertext: RSA encrypted message @type ciphertext: C{String} @param keyst: (Private) key to be used. If none given, the key loaded will be used @type keyst: C{String} @return: The Plain Text @rtype: C{String} """ if keyst == None: keyst = self._privateKey key = ezPyCrypto.key(keyst) plain = key.decStringFromAscii(ciphertext) return plain
def signMessage(self, message, keyst = None): """ Provides a signature for the given message. @param message: Message to be signed (usually plain text) @type message: C{String} @param keyst: Private key to use for signing - if none given, the one stored in the instance will be used @type keyst: C{String} @return: Corresponding Signature @rtype: C{String} """ if keyst == None: keyst = self._privateKey key = ezPyCrypto.key(keyst) signature = key.signString(message) return signature
def validate(self, message, signature, keyst): """ Verifies, whether the exactly this message has been signed with the corresponding private key for this public key. @param message: Message, which was signed (usually plain text) @type message: C{String} @param signature: Signature, which was created for this message @type signature: C{String} @param keyst: Public key - the corresponding private key must have been used for signing the message @type keyst: C{String} @return: True, if this message has produced exactly this signature if the corresponding private key was used, otherwise false @rtype: C{Boolean} """ key = ezPyCrypto.key() key.importKey(keyst) return key.verifyString(message, signature)
def setupKey(): key = ezPyCrypto.key(1024) public_key = key.exportKey() private_key = key.exportKeyPrivate() # Path = ../email_key.pub path = os.path.join(os.path.dirname(__file__), '..', 'email_key.pub') fd = open(path, "w") fd.write(public_key) fd.close() # Path = ../email_key.priv path = os.path.join(os.path.dirname(__file__), '..', 'email_key.priv') fd = open(path, "w") fd.write(private_key) fd.close() return
def decryptUrlQuery(self, ciphertext): log = logging.getLogger('csdt') log.info("RegisterPublic.decryptUrlQuery()") # Path = ../../../../email_key.priv path = os.path.join(os.path.dirname(__file__), '..', '..', '..', '..', 'email_key.priv') fd = open(path, "rb") private_key = fd.read() fd.close() key = ezPyCrypto.key(private_key) try: plaintext = key.decStringFromAscii(ciphertext) except: plaintext = "" return plaintext
def __init__(self): directory= os.path.dirname(os.path.realpath(__file__)) self.ind = appindicator.Indicator("new-gmail-indicator", directory+"/normal.png" , appindicator.CATEGORY_APPLICATION_STATUS) self.ind.set_status(appindicator.STATUS_ACTIVE) self.ind.set_attention_icon(directory+"/new.png") self.menu_setup() self.ind.set_menu(self.menu) self.last_count=0 fd = open(directory+"/.ex_mykey.priv","rb") k = ezPyCrypto.key(fd.read()) fd.close() fd=open(directory+"/email", "rb") self.email= k.decString(fd.read()) fd.close() fd=open(directory+"/pwd", "rb") self.pwd= k.decString(fd.read()) fd.close() pynotify.init("CheckGmail")
#!/usr/bin/env python """ example8.py Like example 7, but demonstrates exporting private key with custom passphrase """ import ezPyCrypto mysecret = "Don't look at this!!!" raw = "Here is a string to encrypt" # Create a key object k = ezPyCrypto.key(passphrase=mysecret) # Export public/private key anotherSecret = "This is another passphrase" publicAndPrivateKey = k.exportKeyPrivate(passphrase=anotherSecret) # Encrypt against this keypair enc = k.encString(raw) # Create a new key object, and import keys (with new passphrase) k1 = ezPyCrypto.key(publicAndPrivateKey, passphrase=anotherSecret) # Decrypt text dec = k.decString(enc) # test if dec == raw: print "Successful decryption using correct NEW passphrase"
def process_request(self, req): gringlet = req.args.get('gringlet') db = self.env.get_db_cnx() cursor = db.cursor() # Do we want an edit page? if gringlet: cursor.execute('SELECT MAX(version) FROM gringotts WHERE name=%s', (gringlet,)) try: version = int(cursor.fetchone()[0]) except: version = 0 messages = [] action = 'edit' if req.method == 'POST' and req.args.has_key('save'): if int(req.args['version']) != version: # Collision messages.append('Someone else has editted this Gringlet and your changes have been lost!') else: if not validate_acl(req, req.args['acl']): messages.append('Your change to the ACL would have locked you out.') messages.append('Please change it accordingly and try again.') data = { 'action': 'edit', 'edit_rows': '20', 'messages': messages, 'gringlet': { 'name': gringlet, 'version': version, 'source': req.args['text'], 'acl': req.args['acl'] } } add_stylesheet(req, 'common/css/wiki.css') return 'gringlet.html', data, None # Save the update key = str(self.config.get('gringotts', 'key')) k = ezPyCrypto.key(key) text = k.encStringToAscii(str(req.args['text'])) cursor.execute('INSERT INTO gringotts (name, version, time, text, acl) ' 'VALUES (%s, %s, %s, %s, %s)', (gringlet, (version+1), int(time()), text, req.args['acl'])) db.commit() version += 1 messages.append('Gringlet saved successfully.') action = 'view' if version > 0: cursor.execute('SELECT text, acl FROM gringotts WHERE name=%s AND version=%s', (gringlet,version)) source,acl = cursor.fetchone() key = str(self.config.get('gringotts', 'key')) k = ezPyCrypto.key(key) source = k.decStringFromAscii(source) else: source = 'Enter the text for your Gringlet here' if req.authname == 'anonymous': acl = '' else: acl = req.authname # If we are allowed, then show the edit page, otherwise just show the listing if validate_acl(req, acl): if not req.args.has_key('action') or req.args['action'] != 'edit': action = 'view' data = { 'action': action, 'edit_rows': '20', 'messages': messages, 'gringlet': { 'name': gringlet, 'version': version, 'source': source, 'acl': acl } } else: messages.append("You do not have the necessary permission to see this Gringlett") data = { 'action': 'view', 'messages': messages } add_stylesheet(req, 'common/css/wiki.css') return 'gringlet.html', data, None # Listing page cursor.execute('SELECT name,acl FROM gringotts g1 WHERE version=' '(SELECT MAX(version) FROM gringotts g2 WHERE g1.name=g2.name) ' 'ORDER BY name') names = [] for name,acl in cursor: names.append({'name': name, 'permitted': validate_acl(req, acl)}) data = { 'gringlets' : { 'list': names } } return 'gringotts.html', data, None
def importPrivateKey(passphrase): global private_key if private_key is None: private_key = ezPyCrypto.key() private_key.importKey(settings.PUBLIC_AND_PRIVATE_KEY, passphrase=passphrase)
if len(sys.argv) != 3: usage() exit() email = sys.argv[1] pwd = sys.argv[2] print "Email: " + email print "Password: "******"Remember to escape weird characters like $ with a \ this way ~> \$" directory = os.path.dirname(os.path.realpath(__file__)) # Create a key object k = ezPyCrypto.key(1280) # Read in the public key fd = open(directory + "/.ex_mykey.pub", "rb") print "Reading public key: .ex_mykey.pub" pubkey = fd.read() fd.close() # import this public key k.importKey(pubkey) # Now encrypt the email against this public key print "Encrypting email..." enc = k.encString(email) # Save the encrypted email to disk
# $Id: crypto.py 410 2007-12-08 03:38:34Z suriya $ # Some simple functions that build on top of ezPyCrypto.py import ezPyCrypto from django.conf import settings from django.utils.encoding import smart_unicode public_key = ezPyCrypto.key() public_key.importKey(settings.PUBLIC_KEY) private_key = None def importPrivateKey(passphrase): global private_key if private_key is None: private_key = ezPyCrypto.key() private_key.importKey(settings.PUBLIC_AND_PRIVATE_KEY, passphrase=passphrase) def encrypt(u): global public_key if not isinstance(u, unicode): raise TypeError('encrypt(u): u should be of type unicode') s = u.encode(settings.DEFAULT_CHARSET) assert isinstance(s, str) encrypted = public_key.encStringToAscii(s) assert isinstance(encrypted, str) return encrypted def decrypt(s, passphrase=None):
#!/usr/bin/env python """ example4.py Import a private key, and decrypt some data """ import ezPyCrypto # Read in a private key fd = open("ex_mykey.priv", "rb") pubprivkey = fd.read() fd.close() # Create a key object, and auto-import private key k = ezPyCrypto.key(pubprivkey) # Read in an encrypted file fd = open("ex_mysecret.enc", "rb") enc = fd.read() fd.close() # Decrypt this file dec = k.decString(enc) # Spill the beans print "Decrypted: %s" % dec
import ezPyCrypto key = ezPyCrypto.key(512, "RSA") print key.exportKeyPrivate() print key.exportKey()
def process_request(self, req): gringlet = req.args.get('gringlet') db = self.env.get_db_cnx() cursor = db.cursor() # Do we want an edit page? if gringlet: req.hdf['wiki.edit_rows'] = 20 cursor.execute('SELECT MAX(version) FROM gringotts WHERE name=%s', (gringlet,)) try: version = int(cursor.fetchone()[0]) except: version = 0 if req.method == 'POST' and req.args.has_key('save'): if int(req.args['version']) != version: # Collision req.hdf['messages'] = [ 'Someone else has editted this Gringlet and your changes have been lost!' ] else: if not validate_acl(req, req.args['acl']): messages = [] messages.append('Your change to the ACL would have locked you out.') messages.append('Please change it accordingly and try again.') req.hdf['messages'] = messages req.hdf['gringlet.version'] = version req.hdf['gringlet.source'] = req.args['text'] req.hdf['gringlet.acl'] = req.args['acl'] add_stylesheet(req, 'common/css/wiki.css') return 'gringlet.cs', None # Save the update key = str(self.config.get('gringotts', 'key')) k = ezPyCrypto.key(key) text = k.encStringToAscii(str(req.args['text'])) cursor.execute('INSERT INTO gringotts (name, version, time, text, acl) ' 'VALUES (%s, %s, %s, %s, %s)', (gringlet, (version+1), int(time()), text, req.args['acl'])) db.commit() version += 1 req.hdf['messages'] = [ 'Gringlet saved successfully.' ] if version > 0: cursor.execute('SELECT text, acl FROM gringotts WHERE name=%s AND version=%s', (gringlet,version)) source,acl = cursor.fetchone() key = str(self.config.get('gringotts', 'key')) k = ezPyCrypto.key(key) source = k.decStringFromAscii(source) else: source = 'Enter the text for your Gringlet here' if req.authname == 'anonymous': acl = '' else: acl = req.authname # If we are allowed, then show the edit page, otherwise just show the listing if validate_acl(req, acl): req.hdf['gringlet.version'] = version req.hdf['gringlet.source'] = source req.hdf['gringlet.acl'] = acl add_stylesheet(req, 'common/css/wiki.css') return 'gringlet.cs', None # Listing page cursor.execute('SELECT name,acl FROM gringotts g1 WHERE version=' '(SELECT MAX(version) FROM gringotts g2 WHERE g1.name=g2.name) ' 'ORDER BY name') names = [] for name,acl in cursor: names.append({'name': name, 'permitted': validate_acl(req, acl)}) req.hdf['gringlets.list'] = names req.hdf['gringotts_href'] = req.href.gringotts() return 'gringotts.cs', None
""" example6.py Verify a signature against a document """ import ezPyCrypto # Read in a public key fd = open("ex_mykey.pub") pubkey = fd.read() fd.close() # Create a key object, and auto-import just a public key k = ezPyCrypto.key(pubkey) # Read in a document we need to verify fd = open("ex_signeddoc.txt") doc = fd.read() fd.close() # Read in the signature fd = open("ex_signeddoc.txt.sig") sig = fd.read() fd.close() # Now try to verify if k.verifyString(doc, sig): print "Verification successful - signature is authentic" else:
#!/usr/bin/env python import ezPyCrypto k = ezPyCrypto.key() publicKey = k.exportKey() publicAndPrivateKey = k.exportKeyPrivate() fd = open("id_rsa.pub", "w") fd.write(publicKey) fd.close() fd = open("id_rsa", "w") fd.write(publicAndPrivateKey) fd.close()
#!/usr/bin/env python """ example3.py Import a public key, and encrypt some data """ orig = "Here is something we don't want the govt to know about" import ezPyCrypto # Create a key object k = ezPyCrypto.key() # Read in a public key fd = open("ex_mykey.pub", "rb") pubkey = fd.read() fd.close() # import this public key k.importKey(pubkey) # Now encrypt some text against this public key enc = k.encString(orig) # Save the encrypted text to disk fd = open("ex_mysecret.enc", "wb") fd.write(enc) fd.close() print "Original text:"
#!/usr/bin/env python """ example1.py Simple demo of ezPyCrypto """ from pdb import set_trace as trace import ezPyCrypto secretString = "Hello, this string will be encrypted" # Create a key object print "Generating 2048-bit keypair - could take a while..." k = ezPyCrypto.key(2048) #k = ezPyCrypto.key(512) # Encrypt a string print "Unencrypted string: '%s'" % secretString enc = k.encString(secretString) # Now decrypt it dec = k.decString(enc) print "Decrypted string: '%s'" % dec
def verify(doc, sig, pubkey): k = ezPyCrypto.key(pubkey) return k.verifyString(doc, sig)
#!/usr/bin/env python """ example7.py Demonstrate the use of passphrases with private keys """ import ezPyCrypto mysecret = "Don't look at this!!!" raw = "Here is a string to encrypt" # Create a key object k = ezPyCrypto.key(passphrase=mysecret) # Export public/private key publicAndPrivateKey = k.exportKeyPrivate() # Encrypt against this keypair enc = k.encString(raw) # Create a new key object, and import keys (with passphrase) k1 = ezPyCrypto.key(publicAndPrivateKey, passphrase=mysecret) # Decrypt text dec = k.decString(enc) # test if dec == raw: print "Successful decryption using correct passphrase"