def test_pub_verify(self): dsa = DSA.load_key(self.privkey) r, s = dsa.sign(self.data) dsapub = DSA.load_pub_key(self.pubkey) assert dsapub.check_key() assert dsapub.verify(self.data, r, s) self.assertRaises(DSA.DSAError, dsapub.sign)
def make_app(global_conf, pub_key, key_type='RSA', cookie_name=None, hdr_prefix=None, log_name=None, **app_conf): """Paste application factory""" pub_key = RSA.load_pub_key( pub_key) if key_type == 'RSA' else DSA.load_pub_key(pub_key) params = {} if cookie_name is not None: params['cookie_name'] = cookie_name if hdr_prefix is not None: params['hdr_prefix'] = hdr_prefix if log_name is not None: params['log_name'] = log_name cache_opts = parse_cache_config_options(app_conf) if cache_opts.get('enabled') == True: cache_mgr = CacheManager(**cache_opts) cache = cache_mgr.get_cache('tickets_cache') params['cache'] = cache return AuthRequestApp(pub_key, **params)
def verifySign(self): message = self.toRaw() md = EVP.MessageDigest('sha1') md.update(message) digest = md.final() dsa = DSA.load_pub_key("keys/dsa_pub_ms.pem") good = dsa.verify(digest, self.signature[0],self.signature[1]) print "*** Verifying MapReply sign ", good return good
def decrypt(): load_keys() usrname = request.cookies.get('username', None) content = get_message(usrname) msg_out = "" for entry in content['messages']: cipher = entry['message'] senderID = entry['senderID'] rsa_user, dsa_rec = key_lookup(senderID) cipher_out = cipher.split(" ") enc_key = base64.b64decode(cipher_out[0]) ciphertext = base64.b64decode(cipher_out[1]) dsa_sign = base64.b64decode(cipher_out[2]) cipher_o = ' '.join(cipher_out[0:2]) cipher_o = cipher_o.encode('utf8') dsa_rec = "-----BEGIN PUBLIC KEY-----\n" + '\n'.join(textwrap.wrap(dsa_rec, 64)) + "\n-----END PUBLIC KEY-----" with open('dsa_rec_pub.key','w') as f: f.write(dsa_rec) some = SHA.new() some.update(cipher_o) dsa_re = DSA.load_pub_key('dsa_rec_pub.key') if dsa_re.verify_asn1(some.digest(), dsa_sign): print "" else: sys.exit() rsa_priv = RSA.importKey(rsa) pkcs = PKCS1_v1_5.new(rsa_priv) dsize = SHA.digest_size sentinel = Random.new().read(15 + dsize) aes_key = pkcs.decrypt(enc_key, sentinel) iv = ciphertext[0:16] #AES CTR decryption backend = default_backend() cipher = Cipher(algorithms.AES(aes_key), modes.CTR(iv), backend=backend) decryptor = cipher.decryptor() mcrc = decryptor.update(ciphertext[16:]) mcrc = pkcs5_unpad(mcrc) mcrc_hex = mcrc.encode('hex') crc = mcrc_hex[-8:] app_message = mcrc_hex[0:len(mcrc_hex)-8].decode('hex') sender = app_message.split(":")[0] message = app_message.split(":")[1] new_crc = binascii.crc32(app_message) new_crc = binascii.unhexlify(do_crc(new_crc)) if crc.decode('hex') != new_crc: continue if sender != senderID: continue msg_out = msg_out + senderID + " : " + message + "<br/><br/>" return msg_out
def __init__(self, filename=None, pub_key=None): if filename: self.filename = file try: pub_key = DSA.load_pub_key(filename) except DSA.DSAError: pass if pub_key is None: pub_key = RSA.load_pub_key(filename) if pub_key is None: raise ValueError("Please specify filename or public key") if not isinstance(pub_key, RSA.RSA_pub) and not isinstance(pub_key, DSA.DSA_pub): raise ValueError('Unknown key type: %s' % type(pub_key)) self.pub_key = pub_key
def verifySign(self): message = self.toRaw() print "VerSign Raw:", (":".join("{0:02x}".format(ord(c)) for c in message)) md = EVP.MessageDigest('sha1') md.update(message) digest = md.final() print "VerSign SHA1:", (":".join("{0:02x}".format(ord(c)) for c in digest)) #print "Mask:", (":".join("{0:02x}".format(ord(c)) for c in self.mask)) #print "Mask:", self.mask dsa = DSA.load_pub_key("keys/dsa_pub_xtr.pem") good = dsa.verify(digest, self.signature[0],self.signature[1]) print "VerSign r:", (":".join("{0:02x}".format(ord(c)) for c in self.signature[0])) print "VerSign s:", (":".join("{0:02x}".format(ord(c)) for c in self.signature[1])) print 'VerSign: ', good return good
def __init__(self, filename=None, pub_key=None): if filename: self.filename = filename try: pub_key = DSA.load_pub_key(filename) except DSA.DSAError: pass if pub_key is None: pub_key = RSA.load_pub_key(filename) if pub_key is None: raise ValueError("Please specify filename or public key") if not isinstance(pub_key, RSA.RSA_pub) and not isinstance( pub_key, DSA.DSA_pub): raise ValueError('Unknown key type: %s' % type(pub_key)) self.pub_key = pub_key
def make_from_config(cls, app, config, prefix='auth.', **kw): """Creates instance of AuthPubTKTMiddleware from dictionary-like configuration. """ keytype = config.get(prefix+'key_type', 'RSA') if keytype not in ('RSA', 'DSA'): raise ConfigError('Wrong key type: %s' % keytype) authpubkey = config.get(prefix+'pubkey', '') if not authpubkey: raise ConfigError('%spubkey parameter is required' % prefix) try: if keytype == 'RSA': pubkey = RSA.load_pub_key(authpubkey) else: pubkey = DSA.load_pub_key(authpubkey) except Exception, err: raise ConfigError('Error loading public key %s: %s' % (authpubkey, str(err)))
def verifySign(self): message = self.toRaw() print "VerSign Raw:", (":".join("{0:02x}".format(ord(c)) for c in message)) md = EVP.MessageDigest('sha1') md.update(message) digest = md.final() print "VerSign SHA1:", (":".join("{0:02x}".format(ord(c)) for c in digest)) #print "Mask:", (":".join("{0:02x}".format(ord(c)) for c in self.mask)) #print "Mask:", self.mask dsa = DSA.load_pub_key("keys/dsa_pub_xtr.pem") good = dsa.verify(digest, self.signature[0], self.signature[1]) print "VerSign r:", (":".join("{0:02x}".format(ord(c)) for c in self.signature[0])) print "VerSign s:", (":".join("{0:02x}".format(ord(c)) for c in self.signature[1])) print 'VerSign: ', good return good
def make_from_config(cls, app, config, prefix='auth.', **kw): """Creates instance of AuthPubTKTMiddleware from dictionary-like configuration. """ keytype = config.get(prefix + 'key_type', 'RSA') if keytype not in ('RSA', 'DSA'): raise ConfigError('Wrong key type: %s' % keytype) authpubkey = config.get(prefix + 'pubkey', '') if not authpubkey: raise ConfigError('%spubkey parameter is required' % prefix) try: if keytype == 'RSA': pubkey = RSA.load_pub_key(authpubkey) else: pubkey = DSA.load_pub_key(authpubkey) except Exception as err: raise ConfigError('Error loading public key %s: %s' % (authpubkey, str(err))) if 'required_tokens' not in kw: rt = config.get(prefix + 'required_tokens', '').strip() if rt: kw['required_tokens'] = rt.split(',') def asbool(v, param): v = v.lower() if v in ('true', 'yes', 'on', '1'): v = True elif v in ('false', 'no', 'off', '0'): v = False else: ConfigError('Bad value for param %s: %s' % (params, v)) return v for p, t in (('cookie_name', 'str'), ('login_url', 'str')): k = prefix + p if (p not in kw) and (k in config): v = config[k] if t == 'bool': v = asbool(v, k) kw[p] = v return cls(app, pubkey, **kw)
def make_from_config(cls, app, config, prefix='auth.', **kw): """Creates instance of AuthPubTKTMiddleware from dictionary-like configuration. """ keytype = config.get(prefix+'key_type', 'RSA') if keytype not in ('RSA', 'DSA'): raise ConfigError('Wrong key type: %s' % keytype) authpubkey = config.get(prefix+'pubkey', '') if not authpubkey: raise ConfigError('%spubkey parameter is required' % prefix) try: if keytype == 'RSA': pubkey = RSA.load_pub_key(authpubkey) else: pubkey = DSA.load_pub_key(authpubkey) except Exception as err: raise ConfigError('Error loading public key %s: %s' % (authpubkey, str(err))) if 'required_tokens' not in kw: rt = config.get(prefix+'required_tokens', '').strip() if rt: kw['required_tokens'] = rt.split(',') def asbool(v, param): v = v.lower() if v in ('true', 'yes', 'on', '1'): v = True elif v in ('false', 'no', 'off', '0'): v = False else: ConfigError('Bad value for param %s: %s' % (params, v)) return v for p, t in (('cookie_name', 'str'), ('login_url', 'str')): k = prefix+p if (p not in kw) and (k in config): v = config[k] if t == 'bool': v = asbool(v, k) kw[p] = v return cls(app, pubkey, **kw)
def make_app(global_conf, pub_key, key_type='RSA', cookie_name=None, hdr_prefix=None, log_name=None, **app_conf): """Paste application factory""" pub_key = RSA.load_pub_key(pub_key) if key_type == 'RSA' else DSA.load_pub_key(pub_key) params = {} if cookie_name is not None: params['cookie_name'] = cookie_name if hdr_prefix is not None: params['hdr_prefix'] = hdr_prefix if log_name is not None: params['log_name'] = log_name cache_opts = parse_cache_config_options(app_conf) if cache_opts.get('enabled') == True: cache_mgr = CacheManager(**cache_opts) cache = cache_mgr.get_cache('tickets_cache') params['cache'] = cache return AuthRequestApp(pub_key, **params)
import sys import logging import os.path from os.path import join as pjoin import unittest from M2Crypto import RSA, DSA from auth_pubtkt import * tests_dir = os.path.dirname(os.path.abspath(__file__)) rsa_priv = RSA.load_key(pjoin(tests_dir, 'rsa_priv.pem')) rsa_pub = RSA.load_pub_key(pjoin(tests_dir, 'rsa_pub.pem')) dsa_priv = DSA.load_key(pjoin(tests_dir, 'dsa_priv.pem')) dsa_pub = DSA.load_pub_key(pjoin(tests_dir, 'dsa_pub.pem')) logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) def verify_ok(pubkey, data, sig): return True class ParseTicketTests(unittest.TestCase): def test_valid_rsa(self): ticket = '''uid=user1;cip=192.168.1.10;validuntil=1277190189;tokens=editor,moderator;udata=custom data;sig=W4/D/Ci2B9e60s7a1K810wPCQ3TzvlCXnAimjTVFRb6mqTFTlvdxCFmc6urC86d+8v8CtM4KsV5jsTmW/250OVkgk1PcoCz/Fvk84V5WqieWj2AVPC5DOujwy73lEeuu3/a4BfnsTagFWJZa6wGWqTEE5pULq8ZWthNXqkhXLzs=''' fields = parse_ticket(ticket, rsa_pub) assert 'uid' in fields and fields['uid'] == 'user1'
""" def __init__(self, pub_key_Path, priv_key_Path=None): ##LOAD priv_key try: if priv_key_Path is not None: try: priv_key = RSA.load_key(priv_key_Path) except Exception, e: priv_key = DSA.load_key(priv_key_Path) else: priv_key = None if priv_key_Path is not None and isinstance(priv_key, RSA.RSA): pub_key = RSA.load_pub_key(pub_key_Path) else: pub_key = DSA.load_pub_key(pub_key_Path) except Exception, e: raise ValueError('Unknown key type: %s' % self.pub_key) self.priv_key = priv_key self.pub_key = pub_key def __verify_sig(self, data, sig): """Verify ticket signature. Returns False if ticket is tampered with and True if ticket is good. Arguments: ``data``:
""" def __init__(self,pub_key_Path, priv_key_Path=None ): ##LOAD priv_key try: if priv_key_Path is not None: try: priv_key = RSA.load_key(priv_key_Path) except Exception, e: priv_key = DSA.load_key(priv_key_Path) else : priv_key = None if priv_key_Path is not None and isinstance(priv_key, RSA.RSA): pub_key = RSA.load_pub_key(pub_key_Path) else: pub_key = DSA.load_pub_key(pub_key_Path) except Exception, e: raise ValueError('Unknown key type: %s' % self.pub_key) self.priv_key = priv_key self.pub_key = pub_key def __verify_sig(self, data, sig): """Verify ticket signature. Returns False if ticket is tampered with and True if ticket is good. Arguments: