def test_verify_fail2(self): dsa = DSA.load_key(self.privkey) r, s = dsa.sign(self.data) dsa2 = DSA.load_params(self.param) assert not dsa2.check_key() with self.assertRaises(AssertionError): dsa2.verify(self.data, r, s)
def generatedata(n, owner="freeconet", keyfile="freeconet.priv.pem"): start = 48600000000 end = 48699999999 thissip = "sip.freeconet.pl" prevsip = "new.freeconet.pl" thisdate = datetime.datetime(2009, 2, 14, 12).isoformat() prevdate = datetime.datetime(2009, 2, 15, 9).isoformat() from random import randrange # no duplicates points = list(set(randrange(start, end) for i in xrange(n))) points.sort() first = ["+%s" % start, "+%s" % points[0], thissip, owner, thisdate] from M2Crypto import DSA dsa = DSA.load_key(keyfile) first.append(crypto.sign_record(dsa, *first)) data = [first] for i in xrange(n - 1): print i, i + 1, len(points), points[i] s = points[i] e = points[i + 1] - 1 thissip, prevsip = prevsip, thissip thisdate, prevdate = prevdate, thisdate r = ["+%s" % s, "+%s" % e, thissip, owner, thisdate] r.append(crypto.sign_record(dsa, *r)) data.append(r) return data
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 test_loadkey(self): dsa = DSA.load_key(self.privkey) self.assertEqual(len(dsa), 1024) with self.assertRaises(AttributeError): getattr(dsa, 'foobar') for k in ('p', 'q', 'g', 'priv', 'pub'): with self.assertRaises(DSA.DSAError): setattr(dsa, k, 1)
def generateSign(self): message = self.toRaw() md = EVP.MessageDigest('sha1') md.update(message) digest = md.final() dsa = DSA.load_key("keys/dsa_priv_ms.pem") self.signature = dsa.sign(digest) return
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:
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 :
def keymaker(organisation, server_id, license_edition, license_type_name, purchase_date=datetime.today(), private_key='./private.pem'): license_types = ('ACADEMIC', 'COMMERCIAL', 'COMMUNITY', 'DEMONSTRATION', 'DEVELOPER', 'NON_PROFIT', 'OPEN_SOURCE', 'PERSONAL', 'STARTER', 'HOSTED', 'TESTING') license_editions = ('BASIC', 'STANDARD', 'PROFESSIONAL', 'ENTERPRISE') if license_type_name not in license_types: raise ValueError( 'License Type Name must be one of the following values:\n\t%s' % ', '.join(license_types)) if license_edition not in license_editions: raise ValueError( 'License Edition must be one of the following values:\n\t%s' % ', '.join(license_editions)) header = purchase_date.ctime() properties = { 'Description': 'Questions for Confluence (Server)\\: Developer', 'CreationDate': purchase_date.strftime('%Y-%m-%d'), 'com.atlassian.confluence.plugins.confluence-questions.active': 'true', 'com.atlassian.confluence.plugins.confluence-questions.Starter': 'false', 'com.atlassian.confluence.plugins.confluence-questions.LicenseTypeName': 'COMMERCIAL', 'com.atlassian.confluence.plugins.confluence-questions.enterprise': 'true', 'Evaluation': 'false', 'licenseVersion': '2', 'MaintenanceExpiryDate': '2099-12-31', 'Organisation': organisation, 'NumberOfUsers': '-1', 'ServerID': server_id, 'SEN': 'SEN-L0000000', 'LicenseID': 'LIDSEN-L0000000', 'LicenseExpiryDate': '2099-12-31', 'PurchaseDate': purchase_date.strftime('%Y-%m-%d') } properties_text = '#%s\n%s' % (header, '\n'.join( ['%s=%s' % (key, value) for key, value in properties.iteritems()])) compressed_properties_text = zlib.compress(properties_text, 9) license_text_prefix = map(chr, (13, 14, 12, 10, 15)) license_text = ''.join(license_text_prefix + [compressed_properties_text]) dsa = DSA.load_key(private_key) assert dsa.check_key() license_signature = dsa.sign_asn1(sha1(license_text).digest()) license_pair_base64 = base64.b64encode( '%s%s%s' % (unichr(len(license_text)).encode('UTF-32BE'), license_text, license_signature)) license_str = '%sX02%s' % (license_pair_base64, base_n(len(license_pair_base64), 31)) return license_str
def set_security_agent(request): serviceDIGEST = "user_id=%s&granted_roles=%s×tamp=%s" serviceACTION = "%s/setgrantedroles?%s&sign=%s" Roles = () serviceURL = "" try: if request.method == "POST": for key, value in request.POST.iteritems(): if key == "serviceURL": serviceURL = value elif key == "csrfmiddlewaretoken": continue else: role = Role.objects.get(name=key) if not isinstance(role, roles): return HttpResponse('FALSE') Roles = Roles + ( key, ) validator = URLValidator() try: validator(serviceURL) except Exception, e: return HttpResponse("Service URL is not well formed") granted_roles = "" for value in Roles: granted_roles += str(value) + "," granted_roles = granted_roles[:-1] serviceDIGEST = serviceDIGEST % (request.user.username, granted_roles, str(int(time.time()))) key = DSA.load_key(settings.MOD_AUTH_PRIVTICKET) serviceSIGN = calculate_sign(key, serviceDIGEST) requestURL = serviceACTION % (serviceURL, serviceDIGEST, serviceSIGN) username = "******" password = "******" passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, requestURL, username, password) authhandler = urllib2.HTTPBasicAuthHandler(passman) opener = urllib2.build_opener(authhandler) urllib2.install_opener(opener) try: pagehandle = urllib2.urlopen(requestURL) except: pagehandle = urllib2.urlopen(requestURL) if pagehandle.code != 200: return HttpResponse(' Sec/Agent request refused.') return HttpResponse('TRUE') except Exception, e: return HttpResponse("FALSE")
def generateSign(self): message = self.toRaw() print "GenSign Raw:", (":".join("{0:02x}".format(ord(c)) for c in message)) md = EVP.MessageDigest('sha1') md.update(message) digest = md.final() print "GenSign SHA1:", (":".join("{0:02x}".format(ord(c)) for c in digest)) #print "Mask:", self.mask dsa = DSA.load_key("keys/dsa_priv_xtr.pem") self.signature = dsa.sign(digest) print "GenSign r:", (":".join("{0:02x}".format(ord(c)) for c in self.signature[0])) print "GenSign s:", (":".join("{0:02x}".format(ord(c)) for c in self.signature[1])) return
def private_key_type(key_file): """ Determines type of the private key: RSA, DSA, EC. :param key_file: file path :type key_file: str :return: one of "RSA", "DSA" or "EC" :except CannotFindKeyTypeError """ try: RSA.load_key(key_file) return "RSA" except: pass try: DSA.load_key(key_file) return "DSA" except: pass try: EC.load_key(key_file) return "EC" except: raise CannotFindKeyTypeError
def encrypt(): load_keys() usrname = request.cookies.get('username', None) user_rec = request.form['recepient'] rsa_rec, dsa_rec = key_lookup(user_rec) message = request.form['message'] app_message = usrname+"3A".decode('hex')+message.encode('utf8') crc = binascii.crc32(app_message) mcrc = app_message.encode('hex') + do_crc(crc) mcrc = binascii.unhexlify(mcrc) mpadded = pkcs5_pad(mcrc) #AES CTR encryption aes_key = os.urandom(16) iv = os.urandom(16) backend = default_backend() cipher = Cipher(algorithms.AES(aes_key), modes.CTR(iv), backend=backend) encryptor = cipher.encryptor() ciphertext = encryptor.update(mpadded) + encryptor.finalize() prepend_cipher = iv + ciphertext #RSA encryption rsa_rec = base64.b64decode(rsa_rec) rec_pub = RSA.importKey(rsa_rec) pkcs = PKCS1_v1_5.new(rec_pub) enc_key = pkcs.encrypt(aes_key) enc_key_b64=base64.b64encode(enc_key) ciphertext_b64=base64.b64encode(prepend_cipher) output = enc_key_b64+"20".decode('hex')+ciphertext_b64 #outputtemp=output.encode('utf8') dsa_me = DSA.load_key('dsa.key') some = SHA.new() some.update(output) dsa_sign = dsa_me.sign_asn1(some.digest()) dsa_sign_64 = base64.b64encode(str(dsa_sign)) cipher_out = output + "20".decode('hex') + dsa_sign_64 send_message(cipher_out,user_rec, usrname) return "Message sent! <a href='http://jmessage.server.isi.jhu.edu/getMessages/"+user_rec+"'>Check Here!</a>"
def main(keylen, hashalg): global dsa, dgst # this exists ONLY for speed testing Rand.load_file('randpool.dat', -1) pvtkeyfilename = 'DSA%dpvtkey.pem' % (keylen) pubkeyfilename = 'DSA%dpubkey.pem' % (keylen) if makenewkey: print ' making and saving a new key' dsa = DSA.gen_params(keylen) dsa.gen_key() dsa.save_key(pvtkeyfilename, None) # no pswd callback dsa.save_pub_key(pubkeyfilename) else: print ' loading an existing key' dsa = DSA.load_key(pvtkeyfilename) print ' dsa key length:', len(dsa) if not dsa.check_key(): raise 'key is not initialised' if showpubkey: dsa_pub = dsa.pub pub_pem = base64.encodestring(dsa_pub) print ' PEM public key is: \n', pub_pem # since we are testing signing and verification, let's not # be fussy about the digest. Just make one. md = EVP.MessageDigest(hashalg) md.update('can you spell subliminal channel?') dgst = md.digest() print ' hash algorithm: %s' % hashalg if showdigest: print ' %s digest: \n%s' % (hashalg, base64.encodestring(dgst)) test(dsa, dgst) # test_asn1(dsa, dgst) test_speed(dsa, dgst) Rand.save_file('randpool.dat')
def main(keylen, hashalg): global dsa, dgst # this exists ONLY for speed testing Rand.load_file('randpool.dat', -1) pvtkeyfilename = 'DSA%dpvtkey.pem' % (keylen) pubkeyfilename = 'DSA%dpubkey.pem' % (keylen) if makenewkey: print ' making and saving a new key' dsa = DSA.gen_params(keylen) dsa.gen_key() dsa.save_key(pvtkeyfilename, None ) # no pswd callback dsa.save_pub_key(pubkeyfilename) else: print ' loading an existing key' dsa = DSA.load_key(pvtkeyfilename) print ' dsa key length:', len(dsa) if not dsa.check_key(): raise 'key is not initialised' if showpubkey: dsa_pub = dsa.pub pub_pem = base64.encodestring(dsa_pub) print ' PEM public key is: \n',pub_pem # since we are testing signing and verification, let's not # be fussy about the digest. Just make one. md = EVP.MessageDigest(hashalg) md.update('can you spell subliminal channel?') dgst = md.digest() print ' hash algorithm: %s' % hashalg if showdigest: print ' %s digest: \n%s' % (hashalg, base64.encodestring(dgst)) test(dsa, dgst) # test_asn1(dsa, dgst) test_speed(dsa, dgst) Rand.save_file('randpool.dat')
def test_sign(self): dsa = DSA.load_key(self.privkey) assert dsa.check_key() r, s = dsa.sign(self.data) assert dsa.verify(self.data, r, s) assert not dsa.verify(self.data, s, r)
def _sign(privkey_path, data): key = DSA.load_key(privkey_path) return key.sign_asn1(hashlib.sha1(data).digest()).encode('hex')
def keymaker(organisation, server_id, license_edition, license_type_name, purchase_date=datetime.today(), private_key='./private.pem'): license_types = ('ACADEMIC', 'COMMERCIAL', 'COMMUNITY', 'DEMONSTRATION', 'DEVELOPER', 'NON_PROFIT', 'OPEN_SOURCE', 'PERSONAL', 'STARTER', 'HOSTED', 'TESTING') license_editions = ('BASIC', 'STANDARD', 'PROFESSIONAL', 'ENTERPRISE') if license_type_name not in license_types: raise ValueError('License Type Name must be one of the following values:\n\t%s' % ', '.join(license_types)) if license_edition not in license_editions: raise ValueError('License Edition must be one of the following values:\n\t%s' % ', '.join(license_editions)) header = purchase_date.ctime() properties = { # 'Description': 'JIRA\\: Developer', # 'CreationDate': purchase_date.strftime('%Y-%m-%d'), # 'jira.LicenseEdition': license_edition, # 'Evaluation': 'false', # 'jira.LicenseTypeName': license_type_name, # 'jira.active': 'true', # 'licenseVersion': '2', # 'MaintenanceExpiryDate': '2099-12-31', # 'Organisation': organisation, # 'jira.NumberOfUsers': '-1', # 'ServerID': server_id, # 'SEN': 'SEN-L0000000', # 'LicenseID': 'LIDSEN-L0000000', # 'LicenseExpiryDate': '2099-12-31', # 'PurchaseDate': purchase_date.strftime('%Y-%m-%d') # 'com.thed.zephyr.je.active':'true', # 'Description':'Zephyr for JIRA - Test Management for JIRA\: Commercial', # 'NumberOfUsers':'-1', # 'CreationDate': purchase_date.strftime('%Y-%m-%d'), # 'Evaluation':'false', # 'licenseVersion':'2', # 'MaintenanceExpiryDate':'2099-12-31', # 'Organisation':organisation, # 'SEN':'SEN-L0000000', # 'LicenseExpiryDate': '2099-12-31', # 'LicenseTypeName': license_type_name, # 'PurchaseDate': purchase_date.strftime('%Y-%m-%d') # 'Description':'Confluence (Server)\: Evaluation', # 'CreationDate':'2016-06-04', # 'conf.active':'true', # 'conf.Starter':'false', # 'ContactEMail':'*****@*****.**', # 'Evaluation':'true', # 'conf.LicenseTypeName':'COMMERCIAL', # 'licenseVersion':'2', # 'MaintenanceExpiryDate':'2099-12-31', # 'Organisation':'Evaluation license', # 'ServerID':server_id, # 'SEN':'SEN-L0000000', # 'LicenseID':'LIDSEN-L7989958', # 'conf.NumberOfUsers':'-1', # 'LicenseExpiryDate':'2099-12-31', # 'PurchaseDate':'2016-06-04', # 'Description':'HTML for Confluence\: Evaluation', # 'NumberOfUsers':'-1', # 'CreationDate':'2016-06-04', # 'ContactEMail':'*****@*****.**', # 'Evaluation':'true', # 'licenseVersion':'2', # 'MaintenanceExpiryDate':'2099-07-03', # 'Organisation':'Evaluation license', # 'org.swift.confluence.html.active':'true', # 'SEN':'SEN-L7991799', # 'LicenseExpiryDate':'2099-07-03', # 'org.swift.confluence.html.Starter':'false', # 'LicenseTypeName':'COMMERCIAL', # 'org.swift.confluence.html.enterprise':'true', # 'PurchaseDate':'2099-07-03', # 'Description':'Balsamiq Mockups for Confluence Server\: Evaluation', # 'NumberOfUsers':'-1', # 'CreationDate':'2016-06-04', # 'com.balsamiq.confluence.plugins.mockups.enterprise':'true', # 'ContactEMail':'*****@*****.**', # 'Evaluation':'true', # 'com.balsamiq.confluence.plugins.mockups.Starter':'false', # 'licenseVersion':'2', # 'MaintenanceExpiryDate':'2099-07-03', # 'com.balsamiq.confluence.plugins.mockups.active':'true', # 'Organisation':'Evaluation license', # 'SEN':'SEN-L0000000', # 'LicenseExpiryDate':'2099-07-03', # 'LicenseTypeName':'COMMERCIAL', # 'PurchaseDate':'2016-06-04', # 'Description':'ProtoShare - Interactive Mockups\: Evaluation', # 'NumberOfUsers':'-1', # 'com.protoshare.confluence.plugins.protoshare-confluence.enterprise':'true', # 'CreationDate':'2016-06-04', # 'ContactEMail':'*****@*****.**', # 'Evaluation':'true', # 'com.protoshare.confluence.plugins.protoshare-confluence.Starter':'false', # 'licenseVersion':'2', # 'MaintenanceExpiryDate':'2099-07-04', # 'Organisation':'Evaluation license', # 'SEN':'SEN-L0000000', # 'LicenseExpiryDate':'2099-07-04', # 'LicenseTypeName':'COMMERCIAL', # 'com.protoshare.confluence.plugins.protoshare-confluence.active':'true', # 'PurchaseDate':'2016-06-04', # 'Description':'Sketchboard.Me for Confluence\: Evaluation', # 'NumberOfUsers':'-1', # 'CreationDate':'2016-06-04', # 'net.sevenscales.confluence.plugins.sketcho-confluence.Starter':'false', # 'ContactEMail':'*****@*****.**', # 'Evaluation':'true', # 'licenseVersion':'2', # 'MaintenanceExpiryDate':'2099-07-04', # 'Organisation':'Evaluation license', # 'SEN':'SEN-L0000000', # 'LicenseExpiryDate':'2099-07-04', # 'LicenseTypeName':'COMMERCIAL', # 'net.sevenscales.confluence.plugins.sketcho-confluence.active':'true', # 'net.sevenscales.confluence.plugins.sketcho-confluence.enterprise':'true', # 'PurchaseDate':'2016-06-04', # 'Description':'Yoikee Creator Templates by Mind Mapping\: Evaluation', # 'NumberOfUsers':'-1', # 'CreationDate':'2016-06-04', # 'com.keinoby.confluence.plugins.yoikee-creator.active':'true', # 'com.keinoby.confluence.plugins.yoikee-creator.Starter':'false', # 'com.keinoby.confluence.plugins.yoikee-creator.enterprise':'true', # 'ContactEMail':'*****@*****.**', # 'Evaluation':'true', # 'licenseVersion':'2', # 'MaintenanceExpiryDate':'2099-07-04', # 'Organisation':'Evaluation license', # 'SEN':'SEN-L0000000', # 'LicenseExpiryDate':'2099-07-04', # 'LicenseTypeName':'COMMERCIAL', # 'PurchaseDate':'2016-06-04', # 'Description':'EasyMind\: Evaluation', # 'NumberOfUsers':'-1', # 'CreationDate':'2016-06-04', # 'cz.morosystems.atlassian.plugin.easymind.enterprise':'true', # 'ContactEMail':'*****@*****.**', # 'Evaluation':'true', # 'cz.morosystems.atlassian.plugin.easymind.Starter':'false', # 'licenseVersion':'2', # 'MaintenanceExpiryDate':'2099-07-04', # 'Organisation':'Evaluation license', # 'SEN':'SEN-L7992124', # 'cz.morosystems.atlassian.plugin.easymind.active':'true', # 'LicenseExpiryDate':'2099-07-04', # 'LicenseTypeName':'COMMERCIAL', # 'PurchaseDate':'2099-07-04', # 'Description':'Docs - JavaDocs, PHPDocs, HTML-Pages...\: Evaluation', # 'NumberOfUsers':'-1', # 'CreationDate':'2016-06-04', # 'ContactEMail':'*****@*****.**', # 'Evaluation':'true', # 'net.meixxi.confluence.docs.docs-plugin.active':'true', # 'licenseVersion':'2', # 'MaintenanceExpiryDate':'2016-07-04', # 'Organisation':'Evaluation license', # 'SEN':'SEN-L7992224', # 'LicenseExpiryDate':'2016-07-04', # 'LicenseTypeName':'COMMERCIAL', # 'net.meixxi.confluence.docs.docs-plugin.enterprise':'true', # 'net.meixxi.confluence.docs.docs-plugin.Starter':'false', # 'PurchaseDate':'2016-06-04', # "Description":"Gantt-Chart for JIRA\: Evaluation", # "NumberOfUsers":"-1", # "de.polscheit.jira.plugins.gantt.active":"true", # "CreationDate":"2016-07-14", # "ContactEMail":"*****@*****.**", # "Evaluation":"true", # "de.polscheit.jira.plugins.gantt.enterprise":"true", # "licenseVersion":"2", # "MaintenanceExpiryDate":"2099-08-12", # "Organisation":"sskaje", # "SEN":"SEN-L0000000", # "LicenseExpiryDate":"2099-08-12", # "de.polscheit.jira.plugins.gantt.Starter":"false", # "LicenseTypeName":"COMMERCIAL", # "PurchaseDate":"2016-07-14", # "com.allenta.jira.plugins.gitlab.gitlab-listener.enterprise":"true", # "NumberOfUsers":"-1", # "Organisation":"sskaje", # "ContactEMail":"*****@*****.**", # "licenseVersion":"2", # "Evaluation":"true", # "Description":"GitLab Listener\: Evaluation", # "com.allenta.jira.plugins.gitlab.gitlab-listener.Starter":"false", # "PurchaseDate":"2016-03-07", # "com.allenta.jira.plugins.gitlab.gitlab-listener.active":"true", # "LicenseTypeName":"COMMERCIAL", # "MaintenanceExpiryDate":"2099-04-05", # "SEN":"SEN-000000", # "CreationDate":"2016-03-07", # "LicenseExpiryDate":"2099-04-05", #jira software #"NumberOfUsers":"-1", #"jira.NumberOfUsers":"-1", #"PurchaseDate":"2017-01-04", #"LicenseTypeName":"COMMERCIAL", #"LicenseExpiryDate":"2099-12-31", #"ContactEMail":"*****@*****.**", #"ServerID":"BOLV-5F7S-6593-F6Z2", #"jira.product.jira-software.active":"true", #"jira.product.jira-software.DataCenter":"true", #"Subscription":"true", #"jira.LicenseEdition":"ENTERPRISE", #"greenhopper.LicenseTypeName":"COMMERCIAL", #"MaintenanceExpiryDate":"2099-12-31", #"jira.product.jira-software.NumberOfUsers":"-1", #"LicenseID":"LIDSEN-L0000000", #"jira.DataCenter":"true", #"SEN":"SEN-L0000000", #"jira.product.jira-software.Starter":"false", #"Organisation":"Evaluation license", #"CreationDate":"2017-01-04", #"licenseVersion":"2", #"greenhopper.enterprise":"true", #"Description":"JIRA Software (Data Center)\: Evaluation", #"jira.active":"true", #"jira.LicenseTypeName":"COMMERCIAL", #"greenhopper.active":"true", #"Evaluation":"true" #"NumberOfUsers":"-1", #"jira.product.jira-core.NumberOfUsers":"-1", #"jira.NumberOfUsers":"-1", #"PurchaseDate":"2017-01-06", #"LicenseTypeName":"COMMERCIAL", #"LicenseExpiryDate":"2099-12-31", #"ContactEMail":"*****@*****.**", #"ServerID":"BOLV-5F7S-6593-F6Z2", #"jira.product.jira-core.Starter":"false", #"jira.LicenseEdition":"ENTERPRISE", #"jira.product.jira-core.active":"true", #"MaintenanceExpiryDate":"2099-12-31", #"LicenseID":"LIDSEN-L0000000", #"SEN":"SEN-L0000000", #"Organisation":"Evaluation license", #"CreationDate":"2017-01-06", #"licenseVersion":"2", #"Description":"JIRA Core (Server)\: Evaluation", #"jira.active":"true", #"jira.LicenseTypeName":"COMMERCIAL", #"Evaluation":"true", "jira.product.jira-servicedesk.active":"true", "jira.product.jira-servicedesk.Starter":"false", "NumberOfUsers":"-1", "PurchaseDate":"2017-01-06", "com.atlassian.servicedesk.active":"true", "LicenseTypeName":"COMMERCIAL", "LicenseExpiryDate":"2099-12-31", "ContactEMail":"*****@*****.**", "ServerID":"BOLV-5F7S-6593-F6Z2", "com.atlassian.servicedesk.LicenseTypeName":"COMMERCIAL", "jira.product.jira-servicedesk.NumberOfUsers":"-1", "MaintenanceExpiryDate":"2099-12-31", "com.atlassian.servicedesk.enterprise":"true", "LicenseID":"LIDSEN-L0000000", "SEN":"SEN-L0000000", "Organisation":"Evaluation license", "CreationDate":"2017-01-06", "com.atlassian.servicedesk.numRoleCount":"-1", "licenseVersion":"2", "Description":"JIRA Service Desk (Server)\: Evaluation", "Evaluation":"true", } properties_text = '#%s\n%s' % (header, '\n'.join(['%s=%s' % (key, value) for key, value in properties.iteritems()])) compressed_properties_text = zlib.compress(properties_text, 9) license_text_prefix = map(chr, (13, 14, 12, 10, 15)) license_text = ''.join(license_text_prefix + [compressed_properties_text]) dsa = DSA.load_key(private_key) assert dsa.check_key() license_signature = dsa.sign_asn1(sha1(license_text).digest()) license_pair_base64 = base64.b64encode('%s%s%s' % (unichr(len(license_text)).encode('UTF-32BE'), license_text, license_signature)) license_str = '%sX02%s' % (license_pair_base64, base_n(len(license_pair_base64), 31)) return license_str
def test_verify_fail(self): dsa = DSA.load_key(self.privkey) r, s = dsa.sign(self.data) assert not dsa.verify(self.different_data, r, s)
def test_sign_asn1(self): dsa = DSA.load_key(self.privkey) blob = dsa.sign_asn1(self.data) assert dsa.verify_asn1(self.data, blob)
def recsign(r, keyfile="freeconet.priv.pem"): from M2Crypto import DSA import crypto dsa = DSA.load_key(keyfile) return crypto.sign_record(dsa, *r)
#!/usr/bin/env python """DSA demonstration. Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved.""" from M2Crypto import DSA, EVP, Rand md = EVP.MessageDigest('sha1') md.update('can you spell subliminal channel?') dgst = md.digest() d = DSA.load_key('dsatest.pem') def test(): print 'testing signing...', r, s = d.sign(dgst) if not d.verify(dgst, r, s): print 'not ok' else: print 'ok' def test_asn1(): # XXX Randomly fails: bug in there somewhere... (0.9.4) print 'testing asn1 signing...', blob = d.sign_asn1(dgst) if not d.verify_asn1(dgst, blob): print 'not ok' else: print 'ok'
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 loadKey(self, file, callback, cipher=None, parent=None): key = None if cipher == "RSA" or cipher == None: try: key = RSA.load_key(file, callback) return key, "RSA" except IOError, (errno, strerror): return None, "RSA" # file not found except RSA.RSAError, args: print "RSA key generation error: " + args[0] pass except ValueError: pass if cipher == "DSA" or cipher == None: try: key = DSA.load_key(file, callback) return key, "DSA" except IOError, (errno, strerror): return None, "DSA" # file not found except ValueError: pass except DSA.DSAError: pass return None, None def saveKey(self, cipher, filename, handle, callback, save_cipher="des_ede3_cbc", prompt=0, parent=None): success = 1 if cipher == "RSA": success = handle.save_key(filename, save_cipher, callback) elif cipher == "DSA": handle.save_key(filename, callback)
def test_loadkey_junk(self): with self.assertRaises(DSA.DSAError): DSA.load_key(self.errkey)
def test_loadkey(self): dsa = DSA.load_key(self.privkey) assert len(dsa) == 1024 self.assertRaises(AttributeError, getattr, dsa, 'foobar') for k in ('p', 'q', 'g', 'priv', 'pub'): self.assertRaises(DSA.DSAError, setattr, dsa, k, 1)
#!/usr/bin/env python """DSA demonstration. Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved.""" from M2Crypto import DSA, EVP, Rand md=EVP.MessageDigest('sha1') md.update('can you spell subliminal channel?') dgst=md.digest() d=DSA.load_key('dsatest.pem') def test(): print 'testing signing...', r,s=d.sign(dgst) if not d.verify(dgst, r, s): print 'not ok' else: print 'ok' def test_asn1(): # XXX Randomly fails: bug in there somewhere... (0.9.4) print 'testing asn1 signing...', blob=d.sign_asn1(dgst) if not d.verify_asn1(dgst, blob): print 'not ok' else: print 'ok'
def test_loadkey(self): dsa = DSA.load_key(self.privkey) assert len(dsa) == 512
def test_loadparam(self): with self.assertRaises(DSA.DSAError): DSA.load_key(self.param) dsa = DSA.load_params(self.param) assert not dsa.check_key() self.assertEqual(len(dsa), 1024)