Пример #1
0
def extractKey(inFile, password):
	db = bsddb.hashopen(inFile, 'r')
	keyDict = {}
	try:
		key, value = db.first()
		while 1:
			keyDict[key] = value
			key, value = db.next()
	except KeyError:
		db.close()

	nsKey = asn1.decode(keyDict['Server-Key\0'])
	rc4 = nsKey[1][1][0][1][0][1]
	if rc4 != RC4Signature:
		raise ValueError, 'RC4 signature not found'
	entrySalt = nsKey[0][1]
	octetString = nsKey[1][1][1][1]

	globalSalt = keyDict['global-salt']
	passwd = keyDict['global-salt'] + password
	saltedPasswd = x509.SHA1(passwd, 0, len(passwd))
	key = entrySalt + saltedPasswd
	rc4Key = x509.MD5(key, 0, len(key))
	data = x509.RC4(rc4Key, octetString, 0, len(octetString))
	pkcs1 = asn1.decode(data)
	keyData = pkcs1[0][1][2][1]
	return x509.PrivateKey('rsa', keyData, 0, len(keyData))
Пример #2
0
def extractKey(inFile, password):
    db = bsddb.hashopen(inFile, 'r')
    keyDict = {}
    try:
        key, value = db.first()
        while 1:
            keyDict[key] = value
            key, value = db.next()
    except KeyError:
        db.close()

    nsKey = asn1.decode(keyDict['Server-Key\0'])
    rc4 = nsKey[1][1][0][1][0][1]
    if rc4 != RC4Signature:
        raise ValueError, 'RC4 signature not found'
    entrySalt = nsKey[0][1]
    octetString = nsKey[1][1][1][1]

    globalSalt = keyDict['global-salt']
    passwd = keyDict['global-salt'] + password
    saltedPasswd = x509.SHA1(passwd, 0, len(passwd))
    key = entrySalt + saltedPasswd
    rc4Key = x509.MD5(key, 0, len(key))
    data = x509.RC4(rc4Key, octetString, 0, len(octetString))
    pkcs1 = asn1.decode(data)
    keyData = pkcs1[0][1][2][1]
    return x509.PrivateKey('rsa', keyData, 0, len(keyData))
Пример #3
0
    def decryptColumn(self, ecc_key, column):
        sql = 'SELECT id, Enc' + column + ' FROM PeopleEncColumn' + column
        enc_col = self.cursor.execute(sql).fetchall()

        col = [(id, asn1.decode(ecc_key.decrypt(asn1.decode(val)[0]))[0])
               for id, val in enc_col]

        print("Decrypted column " + column + ":")
        for id, val in col:
            print("%2d |" % id, val)
        print()

        return col
Пример #4
0
    def verifyASN1(self, str, sig):
##        print 'HI.verify'
##        print repr(str), repr(sig)
##        print binascii.hexlify(sig[1:21]), binascii.hexlify(sig[21:])
##        print binascii.hexlify(sha.new(str).digest())
##        print repr(self.dsa.__dict__)
##        print self.dsa.size()
        seq, rest = asn1.decode(sig)
        if rest: raise ValueError, 'HI: unpack failed'
        r, rest = asn1.decode(seq.value)
        s, rest = asn1.decode(rest)
        return self.dsa.verify(bytes_to_long(sha.new(str).digest()),
                               (r.value, s.value))
Пример #5
0
    def decryptElement(self, ecc_key, id, column):
        sql = 'SELECT EncElement FROM PeopleEncElement WHERE id = (?) AND colName = (?)'
        enc_elem = self.cursor.execute(sql, (id, column)).fetchone()

        enc_elem = enc_elem[0]

        elem, tail = asn1.decode(ecc_key.decrypt(asn1.decode(enc_elem)[0]))

        print('Decrypted Element ' + column)
        print('%2d |' % id, elem)
        print()

        return elem
Пример #6
0
 def decode(self, octets, index=0):
     ls = asn1.decode(octets, index)
     if (len(ls) != 2 or not isinstance(ls[0], asn1.OID)
             or not isinstance(ls[1], list)):
         raise DecodeError
     self.oid = ls[0]
     self.hash_alg = cryptohash.ASN1_HashAlg.fromlist(ls[1])
Пример #7
0
    def _decode(self, input):
        """
           _decode(input)
           
           Decode input octet stream (string) into lists or encoded
           Object IDs and their associated values (lists of strings).
        """
        (bindings, rest) = asn1.SEQUENCE().decode(input)
            
        # Initialize objids and vals lists
        self['encoded_oids'] = []
        self['encoded_vals'] = []
        
        # Walk over bindings
        while bindings:
            # Unpack one binding
            (binding, bindings) = asn1.SEQUENCE().decode(bindings)

            # Get OID
            oid = asn1.OBJECTID()
            binding = oid.decode(binding)[1]
            self['encoded_oids'].append(oid.encode())

            # Get value
            (val, binding) = asn1.decode(binding)
            self['encoded_vals'].append(val.encode())

            # Nothing should left out
            if binding:
                raise TypeError('Trailing garbage in binding: %s' % repr(binding))
        return rest
Пример #8
0
    def _decode(self, input):
        """
           _decode(input)
           
           Decode input octet stream (string) into lists or encoded
           Object IDs and their associated values (lists of strings).
        """
        (bindings, rest) = asn1.SEQUENCE().decode(input)

        # Initialize objids and vals lists
        self['encoded_oids'] = []
        self['encoded_vals'] = []

        # Walk over bindings
        while bindings:
            # Unpack one binding
            (binding, bindings) = asn1.SEQUENCE().decode(bindings)

            # Get OID
            oid = asn1.OBJECTID()
            binding = oid.decode(binding)[1]
            self['encoded_oids'].append(oid.encode())

            # Get value
            (val, binding) = asn1.decode(binding)
            self['encoded_vals'].append(val.encode())

            # Nothing should left out
            if binding:
                raise TypeError('Trailing garbage in binding: %s' %
                                repr(binding))
        return rest
Пример #9
0
 def decode(self, octets, index=0):
     ls, index = asn1.decode(octets, index)
     if len(ls) != 3:
         raise DecodeError(f"expect length 3, get {len(ls)}")
     self.param = []
     self.param.append(cryptohash.ASN1_HashAlg.fromlist(ls[0][0]))
     self.param.append(mgf.ASN1_MGFAlg.fromlist(ls[1][0]))
     self.param.append(ASN1_PSpecified.fromlist(ls[2][0]))
     return index
Пример #10
0
    def decryptRow(self, ecc_key, id):
        sql = 'SELECT EncRow FROM PeopleEncRow WHERE id = (?)'
        encrypted_res = self.cursor.execute(sql, id).fetchone()
        if len(encrypted_res) != 1:
            return None

        encrypted_res = encrypted_res[0]

        encrypted_res, tail = asn1.decode(encrypted_res)
        print(encrypted_res)
        encoded_res = ecc_key.decrypt(encrypted_res)  #TODO: расшифровать
        res, tail = asn1.decode(encoded_res)

        print("Decrypted row:")
        print("%2d | %12s | %12s | %2d | %s" % tuple(res))
        print()

        return res
Пример #11
0
    def _filter(self, key, value):
        """
        """
        if not value or not self.FILTER.has_key(key):
            return

        for val in value:
            object = asn1.decode(val)[0]
            if not object.__class__.__name__ in self.FILTER[key]:
                return -1
Пример #12
0
    def _filter(self, key, value):
        """
        """
        if not value or not self.FILTER.has_key(key):
            return

        for val in value:
            object = asn1.decode(val)[0]
            if not object.__class__.__name__ in self.FILTER[key]:
                return -1
Пример #13
0
 def decode(self, octets, index=0):
     ls, index = asn1.decode(octets, index)
     if len(ls) != 4:
         raise DecodeError(f"expect length 4, get {len(ls)}")
     self.param = []
     self.param.append(cryptohash.ASN1_HashAlg.fromlist(ls[0][0]))
     self.param.append(mgf.ASN1_MGFAlg.fromlist(ls[1][0]))
     if not isinstance(ls[2][0], int) or not isinstance(ls[3][0], int):
         raise TypeError("expect two integers for parameter 2 and 3")
     self.param.append(ls[2][0])
     if ls[3][0] != 1:
         raise ValueError("trailing field other than 0xBC not implemented")
     self.param.append(ls[3][0])
     return index
Пример #14
0
 def unpackASN1(self, string):
     # yuck what a horrid library!
     seq, rest = asn1.decode(string)
     if rest: raise ValueError, 'HI: unpack failed'
     algseq, pubkey = asn1.decode(seq.value)
     oid, rest = asn1.decode(algseq.value)
     dssParmseq, junk = asn1.decode(rest)
     dssParms = dssParmseq.value
     parms = []
     while dssParms:
         p, dssParms = asn1.decode(dssParms)
         parms.append(p)
     p, rest = asn1.decode(pubkey)
     parms.append(p)
     parms = [x.value for x in parms]
     p, q, g, y = tuple(parms)
     self.dsa = DSA.construct([y, g, p, q])
Пример #15
0
        else:
            print '%s%s - %s' % (prefix, repr(t), repr(v))


def dumpStrings(asn):
    for t, v in asn:
        if t in StringTypes:
            print v.tostring()
        elif t in ContainerTypes:
            dumpStrings(v)


if __name__ == '__main__':
    f = open(sys.argv[1])
    block = []
    collect = 0
    while 1:
        line = f.readline()
        if not line:
            break
        if line[:5] == '-----':
            if block:
                break
            else:
                collect = 1
        elif collect:
            block.append(line)
    f.close()
    asn = asn1.decode(a2b_base64(string.join(block, '')))
    dumpStrings(asn)
Пример #16
0
                    base64.b64encode(pub.encode("pkcs1")).decode("utf-8")))
            f.write("\n\n")
            f.write(
                textwrap.fill(
                    base64.b64encode(prv.encode("pkcs1")).decode("utf-8")))
            f.write("\n\n")
            f.write("A quick brown fox jumps over the lazy dog.\n")

    s = input("Public key: ")
    if s != "":
        key = ""
        while s != "":
            key += s
            s = input()
        pub = RSAPublicKey.fromlist(
            asn1.decode(base64.b64decode(key))[0], "pkcs1")
    s = input("Private key: ")
    if s != "":
        key = ""
        while s != "":
            key += s
            s = input()
        prv = RSAPrivateKey.fromlist(
            asn1.decode(base64.b64decode(key))[0], "pkcs1")

    msg = input("Message: ")
    print()
    cipher = pub.encrypt_basic(msg)
    print(textwrap.fill(f"RSA-1024 encrypted: {cipher.hex()}"))
    print(f"Decrypted: {prv.decrypt_basic(cipher).decode('utf-8')}")
    oaep = ASN1_RSAES_OAEP()
Пример #17
0
			print '%s%s' % (prefix, repr(t))
			printASN(v, prefix + '  ')
		else:
			print '%s%s - %s' % (prefix, repr(t), repr(v))

def dumpStrings(asn):
	for t, v in asn:
		if t in StringTypes:
			print v.tostring()
		elif t in ContainerTypes:
			dumpStrings(v)

if __name__ == '__main__':
	f = open(sys.argv[1])
	block = []
	collect = 0
	while 1:
		line = f.readline()
		if not line:
			break
		if line[:5] == '-----':
			if block:
				break
			else:
				collect = 1
		elif collect:
			block.append(line)
	f.close()
	asn = asn1.decode(a2b_base64(string.join(block, '')))
	dumpStrings(asn)