Example #1
0
 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)
Example #2
0
 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)
Example #3
0
 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)
Example #4
0
 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)
Example #5
0
 def test_genparam_setparam_genkey(self):
     dsa = DSA.gen_params(1024, self.callback)
     assert len(dsa) == 1024
     p = dsa.p
     q = dsa.q
     g = dsa.g
     dsa2 = DSA.set_params(p,q,g)
     assert not dsa2.check_key()
     dsa2.gen_key()
     assert dsa2.check_key()
     r,s = dsa2.sign(self.data)
     assert dsa2.verify(self.data, r, s)
Example #6
0
 def test_pub_key_from_params(self):
     dsa = DSA.gen_params(1024, self.callback)
     dsa.gen_key()
     assert len(dsa) == 1024
     p = dsa.p
     q = dsa.q
     g = dsa.g
     pub = dsa.pub
     dsa2 = DSA.pub_key_from_params(p,q,g,pub)
     assert dsa2.check_key()
     r,s = dsa.sign(self.data)
     assert dsa2.verify(self.data, r, s)
Example #7
0
 def test_genparam_setparam_genkey(self):
     dsa = DSA.gen_params(1024, self.callback)
     self.assertEqual(len(dsa), 1024)
     p = dsa.p
     q = dsa.q
     g = dsa.g
     dsa2 = DSA.set_params(p, q, g)
     assert not dsa2.check_key()
     dsa2.gen_key()
     assert dsa2.check_key()
     r, s = dsa2.sign(self.data)
     assert dsa2.verify(self.data, r, s)
Example #8
0
 def test_pub_key_from_params(self):
     dsa = DSA.gen_params(1024, self.callback)
     dsa.gen_key()
     assert len(dsa) == 1024
     p = dsa.p
     q = dsa.q
     g = dsa.g
     pub = dsa.pub
     dsa2 = DSA.pub_key_from_params(p, q, g, pub)
     assert dsa2.check_key()
     r, s = dsa.sign(self.data)
     assert dsa2.verify(self.data, r, s)
Example #9
0
def _dnskey_to_dsa(key):
    # get T
    t = key[0]
    # python3/python2 dual compatibility
    if not isinstance(t, int):
        t = ord(t)
    offset = 1

    # get Q
    new_offset = offset + 20
    q = bn_to_mpi(hex_to_bn(binascii.hexlify(key[offset:new_offset])))
    offset = new_offset

    # get P
    new_offset = offset + 64 + (t << 3)
    p = bn_to_mpi(hex_to_bn(binascii.hexlify(key[offset:new_offset])))
    offset = new_offset

    # get G
    new_offset = offset + 64 + (t << 3)
    g = bn_to_mpi(hex_to_bn(binascii.hexlify(key[offset:new_offset])))
    offset = new_offset

    # get Y
    new_offset = offset + 64 + (t << 3)
    y = bn_to_mpi(hex_to_bn(binascii.hexlify(key[offset:new_offset])))
    offset = new_offset

    # create the DSA public key
    return DSA.pub_key_from_params(p, q, g, y)
Example #10
0
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
Example #11
0
def _dnskey_to_dsa(key):
    # get T
    t, = struct.unpack(b'B', key[0])
    offset = 1

    # get Q
    new_offset = offset + 20
    q = bn_to_mpi(hex_to_bn(binascii.hexlify(key[offset:new_offset])))
    offset = new_offset

    # get P
    new_offset = offset + 64 + (t << 3)
    p = bn_to_mpi(hex_to_bn(binascii.hexlify(key[offset:new_offset])))
    offset = new_offset

    # get G
    new_offset = offset + 64 + (t << 3)
    g = bn_to_mpi(hex_to_bn(binascii.hexlify(key[offset:new_offset])))
    offset = new_offset

    # get Y
    new_offset = offset + 64 + (t << 3)
    y = bn_to_mpi(hex_to_bn(binascii.hexlify(key[offset:new_offset])))
    offset = new_offset

    # create the DSA public key
    return DSA.pub_key_from_params(p, q, g, y)
Example #12
0
def _dnskey_to_dsa(key):
    # get T
    t, = struct.unpack(b'B',key[0])
    offset = 1

    # get Q
    new_offset = offset+20
    q = bn_to_mpi(hex_to_bn(binascii.hexlify(key[offset:new_offset])))
    offset = new_offset

    # get P
    new_offset = offset+64+(t<<3)
    p = bn_to_mpi(hex_to_bn(binascii.hexlify(key[offset:new_offset])))
    offset = new_offset

    # get G
    new_offset = offset+64+(t<<3)
    g = bn_to_mpi(hex_to_bn(binascii.hexlify(key[offset:new_offset])))
    offset = new_offset

    # get Y
    new_offset = offset+64+(t<<3)
    y = bn_to_mpi(hex_to_bn(binascii.hexlify(key[offset:new_offset])))
    offset = new_offset

    # create the DSA public key
    return DSA.pub_key_from_params(p,q,g,y)
Example #13
0
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)
Example #14
0
def parse_pub_key(pubstr):
    if not isinstance(pubstr, str):
        raise TypeError('str argument required')
    if not pubstr.startswith('-----BEGIN PUBLIC KEY-----'):
        raise ValueError("public key didn't start with '-----BEGIN PUBLIC KEY-----'")
    mem = BIO.MemoryBuffer(pubstr)
    return DSA.load_pub_key_bio(mem)
Example #15
0
def generate_dsa_key_pair(bits=1024):
    dsa = DSA.gen_params(1024, lambda x:None)
    dsa.gen_key()
    pub = BIO.MemoryBuffer()
    dsa.save_pub_key_bio(pub)
    priv = BIO.MemoryBuffer()
    dsa.save_key_bio(priv, cipher=None)
    return dsa, priv.read(), pub.read()
Example #16
0
def load_pub_key_params(p, q, g, pub):
    """Create a DSA_pub object from parameters and key."""
    dsa = m2.dsa_new()
    m2.dsa_set_p(dsa, p)
    m2.dsa_set_q(dsa, q)
    m2.dsa_set_g(dsa, g)
    m2.dsa_set_pub(dsa, pub)
    return DSA.DSA_pub(dsa, 1)
Example #17
0
def parse_priv_key(privstr):
    if not isinstance(privstr, str):
        raise TypeError('str argument required')
    if not privstr.startswith('-----BEGIN DSA PRIVATE KEY-----') \
            and not privstr.startswith('-----BEGIN RSA PRIVATE KEY-----'):
        raise ValueError("public key didn't start with '-----BEGIN ANY PRIVATE KEY-----'")
    mem = BIO.MemoryBuffer(privstr)
    return DSA.load_key_bio(mem)
Example #18
0
 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
Example #19
0
 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)
Example #20
0
 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)
Example #21
0
 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
Example #22
0
 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:
Example #23
0
 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 :
Example #24
0
def dsa_set_priv(dsa, value):
    """Set the private-key component of a DSA object."""
    bn = _m2lib.BN_mpi2bn(value, len(value), None)
    if not bn:
        raise DSA.DSAError("invalid private key data")
    dsa_p = ctypes.cast(ctypes.c_void_p(int(dsa)), ctypes.POINTER(_DSA))
    if dsa_p.contents.priv_key:
        _m2lib.BN_free(dsa_p.contents.priv_key)
    dsa_p.contents.priv_key = bn
Example #25
0
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
Example #26
0
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
Example #27
0
def set_security_agent(request):
    serviceDIGEST = "user_id=%s&granted_roles=%s&timestamp=%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")
Example #28
0
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')
Example #29
0
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 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
Example #31
0
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
Example #32
0
 def createKey(self, cipher, length, callback, parent=None):
     key = None
     if cipher == "RSA":
         exp = 65537
         print ("Create RSA key with key length %d bits\n" % length)
         key = RSA.gen_key(length, exp, callback)
     elif cipher == "DSA":
         print ("Create DSA key with key length %d bits\n" % length)
         dsa = DSA.gen_params(length, callback)
         dsa.gen_key()
         key = dsa
     if parent != None:
         parent.finishedGeneration(key)
     return 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
Example #34
0
    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
Example #35
0
    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
Example #36
0
 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 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
Example #38
0
def convert(fin, fout):
    key = decode_key(fin)
    ret = read_key(key)
    key_type = ret[0]

    if key_type == "ssh-rsa":
        e, n = ret[1:]
        rsa = rsa_new_pub_key((e, n))
        rsa.save_pem(fout)

    elif key_type == "ssh-dss":
        p, q, g, y = ret[1:]
        dsa = DSA.set_params(p, q, g)
        dsa.gen_key()
        dsa.save_pub_key(fout)
        # FIXME: This is wrong.
        # M2Crypto doesn't allow us to set the public key parameter
        raise Exception("DSA keys are not supported yet: M2Crypto doesn't allow us to set the public key parameter")
Example #39
0
def convert(fin, fout):
    key = decode_key(fin)
    ret = read_key(key)
    key_type = ret[0]

    if key_type == "ssh-rsa":
        e, n = ret[1:]
        rsa = rsa_new_pub_key((e, n))
        rsa.save_pem(fout)

    elif key_type == "ssh-dss":
        p, q, g, y = ret[1:]
        dsa = DSA.set_params(p, q, g)
        dsa.gen_key()
        dsa.save_pub_key(fout)
        # FIXME: This is wrong.
        # M2Crypto doesn't allow us to set the public key parameter
        raise Exception("DSA keys are not supported yet: M2Crypto doesn't allow us to set the public key parameter")
Example #40
0
def key_generation():

  #DSA key generation

  dsa = DSA.gen_params(1024)
  dsa.gen_key()
  dsa.save_key('dsa.key', None)
  dsa.save_pub_key('dsa_pub.key')

  #RSA key generation

  new_key = RSA.generate(1024)
  public_key = new_key.publickey().exportKey("PEM")
  private_key = new_key.exportKey("PEM")
  with open('rsa_pub.key','w') as f:
    f.write(public_key)
  with open('rsa.key','w') as f:
    f.write(private_key)
  return "Key generated!"
Example #41
0
    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 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
Example #43
0
def _generate_keypair(password=None):
    dsa = DSA.gen_params(1024, os.urandom)

    mem_pub = BIO.MemoryBuffer()
    mem_private = BIO.MemoryBuffer()

    dsa.gen_key()
    if password is None:
        dsa.save_key_bio(mem_private, cipher=None)
    else:
        dsa.save_key_bio(mem_private, callback=lambda _: password)

    private_key = mem_private.getvalue()

    dsa.save_pub_key_bio(mem_pub)

    public_key = _run_ssh_on_string(SSH_KEYGEN_COMMAND + " -f %s -i -m PKCS8",
                                    mem_pub.getvalue())[:-1]
    return {"public": public_key, "private": private_key}
Example #44
0
    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)
Example #45
0
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>"
Example #46
0
    def from_string(cls, key):
        """
        Loads an RFC 4716 formatted public key.
        """
        pubkey = cls()

        if key.startswith('ssh-'):
            pubkey.hashed = key.split()[1]
        else:
            pubkey.hashed = key

        pubkey.key_type, remainder = unpack_string(pubkey.blob)

        if pubkey.key_type == 'ssh-rsa':
            e, n = get_packed_mp_ints(remainder, 2)
            pubkey.instance = RSA.new_pub_key((e, n))
        elif pubkey.key_type == 'ssh-dss':
            p, q, g, y = get_packed_mp_ints(remainder, 4)
            pubkey.instance = DSA.set_params(p, q, g)

        return pubkey
Example #47
0
def _dnskey_to_dsa(key):
    # get T
    t, = struct.unpack(b'B',key[0])
    offset = 1

    # get Q
    new_offset = offset+20
    q = b''
    for c in key[offset:new_offset]:
        q += b'%02x' % struct.unpack(b'B',c)[0]
    q = bn_to_mpi(hex_to_bn(q))
    offset = new_offset

    # get P
    new_offset = offset+64+(t<<3)
    p = b''
    for c in key[offset:new_offset]:
        p += b'%02x' % struct.unpack(b'B',c)[0]
    p = bn_to_mpi(hex_to_bn(p))
    offset = new_offset

    # get G
    new_offset = offset+64+(t<<3)
    g = b''
    for c in key[offset:new_offset]:
        g += b'%02x' % struct.unpack(b'B',c)[0]
    g = bn_to_mpi(hex_to_bn(g))
    offset = new_offset

    # get Y
    new_offset = offset+64+(t<<3)
    y = b''
    for c in key[offset:new_offset]:
        y += b'%02x' % struct.unpack(b'B',c)[0]
    y = bn_to_mpi(hex_to_bn(y))
    offset = new_offset

    # create the DSA public key
    return DSA.pub_key_from_params(p,q,g,y)
Example #48
0
def _dnskey_to_dsa(key):
    # get T
    t, = struct.unpack(b'B', key[0])
    offset = 1

    # get Q
    new_offset = offset + 20
    q = b''
    for c in key[offset:new_offset]:
        q += b'%02x' % struct.unpack(b'B', c)[0]
    q = bn_to_mpi(hex_to_bn(q))
    offset = new_offset

    # get P
    new_offset = offset + 64 + (t << 3)
    p = b''
    for c in key[offset:new_offset]:
        p += b'%02x' % struct.unpack(b'B', c)[0]
    p = bn_to_mpi(hex_to_bn(p))
    offset = new_offset

    # get G
    new_offset = offset + 64 + (t << 3)
    g = b''
    for c in key[offset:new_offset]:
        g += b'%02x' % struct.unpack(b'B', c)[0]
    g = bn_to_mpi(hex_to_bn(g))
    offset = new_offset

    # get Y
    new_offset = offset + 64 + (t << 3)
    y = b''
    for c in key[offset:new_offset]:
        y += b'%02x' % struct.unpack(b'B', c)[0]
    y = bn_to_mpi(hex_to_bn(y))
    offset = new_offset

    # create the DSA public key
    return DSA.pub_key_from_params(p, q, g, y)
    def generate_keypair(self, password=None):
        ''' Generate a 1024 bit DSA key.  Someday they will be password
        protected.
        returns public key, private key '''

        dsa = DSA.gen_params(1024, os.urandom)

        mem_pub = BIO.MemoryBuffer()
        mem_private = BIO.MemoryBuffer()

        dsa.gen_key()
        if password is None:
            dsa.save_key_bio(mem_private, cipher=None)
        else:
            dsa.save_key_bio(mem_private, callback=lambda _: password)

        private_key = mem_private.getvalue()

        dsa.save_pub_key_bio(mem_pub)

        public_key = self._pubkey_from_private(mem_pub.getvalue())

        return public_key, private_key
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)
Example #51
0
 def test_sign_with_params_only(self):
     dsa = DSA.load_params(self.param)
     self.assertRaises(AssertionError, dsa.sign, self.data)
     self.assertRaises(AssertionError, dsa.sign_asn1, self.data)
Example #52
0
def _sign(privkey_path, data):
    key = DSA.load_key(privkey_path)
    return key.sign_asn1(hashlib.sha1(data).digest()).encode('hex')
Example #53
0
 def test_sign_with_params_only(self):
     dsa = DSA.load_params(self.param)
     with self.assertRaises(AssertionError):
         dsa.sign(self.data)
     with self.assertRaises(AssertionError):
         dsa.sign_asn1(self.data)
Example #54
0
 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)
Example #55
0
#!/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'
Example #56
0
 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)