Example #1
0
 def __init__(self,file=None,Rec=None,List=None,Size=512):
     if file:
         self.dsa = DSA.construct(cPickle.load(open(file, 'rb')))
     elif Rec:
         self.unpack(Rec)
     elif List:
         self.dsa = DSA.construct(List)
     else:
         self.dsa = DSA.generate(Size, HIPutils.RandomPool.get_bytes)
Example #2
0
def DSAKey(pub=None, priv=None, fd=None):
    """
    make DSA KeyPair Object
    """
    if fd is not None:
        pub = int.from_bytes(fd.read(128), 'big')
        priv = int.from_bytes(fd.read(128), 'big')
    if priv:
        return DSA.construct((pub, dsa_g, dsa_p, dsa_q, priv))
    return DSA.construct((pub, dsa_g, dsa_p, dsa_q))
    def test7(self):
        """Verify public/private method"""

        self.description = "can_sign() test"
        key = DSA.construct((self.Y, self.G, self.P, self.Q, self.X))
        signer = DSS.new(key, 'fips-186-3')
        self.failUnless(signer.can_sign())

        key = DSA.construct((self.Y, self.G, self.P, self.Q))
        signer = DSS.new(key, 'fips-186-3')
        self.failIf(signer.can_sign())
Example #4
0
    def keyObject(self):
        """
        A C{Crypto.PublicKey} object similar to this key.

        As PyCrypto is no longer used for the underlying operations, this
        property should be avoided.
        """
        # Lazy import to have PyCrypto as a soft dependency.
        from Crypto.PublicKey import DSA, RSA

        keyObject = None
        keyType = self.type()
        keyData = self.data()
        isPublic = self.isPublic()

        if keyType == 'RSA':
            if isPublic:
                keyObject = RSA.construct((
                    keyData['n'],
                    long(keyData['e']),
                ))
            else:
                keyObject = RSA.construct((
                    keyData['n'],
                    long(keyData['e']),
                    keyData['d'],
                    keyData['p'],
                    keyData['q'],
                    keyData['u'],
                ))
        elif keyType == 'DSA':
            if isPublic:
                keyObject = DSA.construct((
                    keyData['y'],
                    keyData['g'],
                    keyData['p'],
                    keyData['q'],
                ))
            else:
                keyObject = DSA.construct((
                    keyData['y'],
                    keyData['g'],
                    keyData['p'],
                    keyData['q'],
                    keyData['x'],
                ))
        else:
            raise BadKeyError('Unsupported key type.')

        return keyObject
Example #5
0
    def keyObject(self):
        """
        A C{Crypto.PublicKey} object similar to this key.

        As PyCrypto is no longer used for the underlying operations, this
        property should be avoided.
        """
        # Lazy import to have PyCrypto as a soft dependency.
        from Crypto.PublicKey import DSA, RSA

        keyObject = None
        keyType = self.type()
        keyData = self.data()
        isPublic = self.isPublic()

        if keyType == 'RSA':
            if isPublic:
                keyObject = RSA.construct((
                    keyData['n'],
                    long(keyData['e']),
                    ))
            else:
                keyObject = RSA.construct((
                    keyData['n'],
                    long(keyData['e']),
                    keyData['d'],
                    keyData['p'],
                    keyData['q'],
                    keyData['u'],
                    ))
        elif keyType == 'DSA':
            if isPublic:
                keyObject = DSA.construct((
                    keyData['y'],
                    keyData['g'],
                    keyData['p'],
                    keyData['q'],
                    ))
            else:
                keyObject = DSA.construct((
                    keyData['y'],
                    keyData['g'],
                    keyData['p'],
                    keyData['q'],
                    keyData['x'],
                    ))
        else:
            raise BadKeyError('Unsupported key type.')

        return keyObject
Example #6
0
    def __init__(self, key=None, private=False):
        self.priv = self.pub = None

        if not isinstance(key, tuple):
            raise TypeError('4/5-tuple required for key')

        if len(key) == 5 and private:
            self.priv = DSA.construct(key)
            self.pub = self.priv.publickey()
        elif len(key) == 4 and not private:
            self.pub = DSA.construct(key)
        else:
            raise TypeError('wrong number of arguments for ' \
                    'private={0!r}: got {1} '
                    .format(private, len(key)))
Example #7
0
    def __init__(self, key=None, private=False):
        self.priv = self.pub = None

        if not isinstance(key, tuple):
            raise TypeError('4/5-tuple required for key')

        if len(key) == 5 and private:
            self.priv = DSA.construct(key)
            self.pub = self.priv.publickey()
        elif len(key) == 4 and not private:
            self.pub = DSA.construct(key)
        else:
            raise TypeError('wrong number of arguments for ' \
                    'private={0!r}: got {1} '
                    .format(private, len(key)))
Example #8
0
    def pkcs11_to_crypto_key(self,
                             pkcs11_public_key: pkcs11.KeyType) -> PublicKey:
        """
        Convert a `pkcs11` public key to a `cryptography` public key.

        :param pkcs11.KeyType pkcs11_public_key: A `pkcs11` format public key.
        :return: A `cryptography` format public key.
        :rtype: :class:`PublicKey`
        """
        if self.pkcs11_key_type == pkcs11.KeyType.RSA:
            der_public_key = encode_rsa_public_key(pkcs11_public_key)
        elif self.pkcs11_key_type == pkcs11.KeyType.DSA:
            y = int.from_bytes(pkcs11_public_key[pkcs11.Attribute.VALUE],
                               byteorder="big")
            g = int.from_bytes(pkcs11_public_key[pkcs11.Attribute.BASE],
                               byteorder="big")
            p = int.from_bytes(pkcs11_public_key[pkcs11.Attribute.PRIME],
                               byteorder="big")
            q = int.from_bytes(pkcs11_public_key[pkcs11.Attribute.SUBPRIME],
                               byteorder="big")

            der_public_key = DSA.construct(
                (y, g, p, q)).export_key(format="DER")
        elif self.pkcs11_key_type == pkcs11.KeyType.EC:
            der_public_key = encode_ec_public_key(pkcs11_public_key)
        else:
            raise TypeError(f"Key type for {pkcs11_public_key} not supported")

        return load_der_public_key(der_public_key)
Example #9
0
def strtoprivkey(data, passphrase):
    kind = data[0][11: 14]
    if data[1].startswith('Proc-Type: 4,ENCRYPTED'):  # is an encrypted key
        ivdata = data[2].split(',')[1][:-1]
        iv = ''.join([chr(int(ivdata[i:i + 2], 16)) for i in range(0, len(ivdata), 2)])

        if not passphrase:
            raise BadKeyError('encrypted key with no passphrase')

        ba = hashlib.md5(passphrase + iv).digest()
        bb = hashlib.md5(ba + passphrase + iv).digest()
        decKey = (ba + bb)[:24]
        b64Data = base64.decodestring(''.join(data[4:-1]))
        keyData = DES3.new(decKey, DES3.MODE_CBC, iv).decrypt(b64Data)
        removeLen = ord(keyData[-1])
        keyData = keyData[:-removeLen]
    else:
        keyData = base64.decodestring(''.join(data[1:-1]))
    decodedKey = asn1parse(keyData)
    if isinstance(decodedKey[0], list):
        decodedKey = decodedKey[0]  # this happens with encrypted keys
    if kind == 'RSA':
        n, e, d, p, q = decodedKey[1:6]
        return RSA.construct((n, e, d, p, q))
    elif kind == 'DSA':
        p, q, g, y, x = decodedKey[1: 6]
        return DSA.construct((y, g, p, q, x))
Example #10
0
 def _construct_DSA(self,privkey):
     k,x = privkey
     return DSA.construct([self.pubkey.y,
                           self.pubkey.g,
                           self.pubkey.p,
                           self.pubkey.q,
                           x])
 def validate(self, user_id, record_id, updated_data):
     session = session_class()
     digital_sign = session.query(DDigitalSign).filter_by(
         record_id=record_id).first()
     if digital_sign is None:
         session.close()
         return False, '该病历未被签名'
     user = session.query(DUser).filter_by(id=user_id).first()
     if user is None:
         session.close()
         return False, '用户不存在'
     info = session.query(DDoctorInfo).filter_by(
         id=user.doctor_info_id).first()
     if user is None:
         session.close()
         return False, '用户信息不存在'
     private_key = session.query(DPrivateKey).filter_by(
         id=info.private_key_id).first()
     if private_key is None:
         session.close()
         return False, '用户密钥不存在'
     record = session.query(DMedicalRecord).filter_by(id=record_id).first()
     if record is None:
         session.close()
         return False, '病历不存在'
     session.close()
     hashed_text = SHA256.new(updated_data.encode('utf-8')).digest()
     key = DSA.construct((int(private_key.key_y), int(private_key.key_g),
                          int(private_key.key_p), int(private_key.key_q),
                          int(private_key.key_x)))
     ret = key.verify(hashed_text,
                      (int(digital_sign.sign_1), int(digital_sign.sign_2)))
     return True, ret
Example #12
0
def sign_DSA(msg, key_tuple, k=None):
    """Create a DSA signature.

    :Parameters:
        - `msg`: string of data signature applies to 
        - `key_tuple`: tuple of DSA integers (y, g, p, q, x)
          (see `DSA tuple`_)
        - `k`: random integer 2 < k < q (automatically generated by
          default)

    :Returns: tuple (integer, integer) DSA signature values (r, s)

    .. _DSA tuple:

    DSA tuple:

        - `y`: integer DSA public key
        - `g`: integer DSA group
        - `p`: integer DSA prime
        - `q`: integer DSA order
        - `x`: integer DSA secret value
    """
    import Crypto.PublicKey.DSA as DSA
    if k is None: # generate our own k value (2 < k < q)
        import Crypto.Util.number as NUM
        import Crypto.Util.randpool as RND
        rnd = RND.RandomPool()
        q = key_tuple[3]
        while 1:
            k = NUM.getRandomNumber(8*len(STN.int2str(q)), rnd.get_bytes)
            if 2 < k < q:
                break
    dsa = DSA.construct(key_tuple) # note change in ordering
    return dsa.sign(msg, k)
Example #13
0
    def _process_ssh_dss(self, data):
        """ Parses ssh-dsa public keys """
        data_fields = {}
        current_position = 0
        for item in ("p", "q", "g", "y"):
            current_position, value = self._unpack_by_int(
                data, current_position)
            data_fields[item] = self._parse_long(value)

        self.dsa = DSA.construct((data_fields["y"], data_fields["g"],
                                  data_fields["p"], data_fields["q"]))
        self.bits = self.dsa.size() + 1

        q_bits = self._bits_in_number(data_fields["q"])
        if q_bits != self.DSA_N_LENGTH:
            raise InvalidKeyError(
                "Incorrect DSA key parameters: bits(p)=%s, q=%s" %
                (self.bits, q_bits))
        if self.strict_mode:
            min_length = self.DSA_MIN_LENGTH_STRICT
            max_length = self.DSA_MAX_LENGTH_STRICT
        else:
            min_length = self.DSA_MIN_LENGTH_LOOSE
            max_length = self.DSA_MAX_LENGTH_LOOSE
        if self.bits < min_length:
            raise TooShortKeyError(
                "%s key can not be shorter than %s bits (was %s)" %
                (self.key_type, min_length, self.bits))
        if self.bits > max_length:
            raise TooLongKeyError(
                "%s key data can not be longer than %s bits (was %s)" %
                (self.key_type, max_length, self.bits))
        return current_position
Example #14
0
 def decode_pkcs1_public(cls, key_data):
     if (isinstance(key_data, tuple) and len(key_data) == 5 and
         all_ints(key_data) and key_data[0] == 0):
         _, p, q, g, y = key_data
         return cls(DSA.construct((y, g, p, q)))
     else:
         raise KeyImportError('Invalid DSA public key')
Example #15
0
    def _fromString_PRIVATE_LSH(Class, data):
        """
        Return a private key corresponding to this LSH private key string.
        The LSH private key string format is::
            <s-expression: ('private-key', (<key type>, (<name>, <value>)+))>

        The names for a RSA (key type 'rsa-pkcs1-sha1') key are: n, e, d, p, q.
        The names for a DSA (key type 'dsa') key are: y, g, p, q, x.

        @type data: C{str}
        @return: a {Crypto.PublicKey.pubkey.pubkey} object
        @raises BadKeyError: if the key type is unknown
        """
        sexp = sexpy.parse(data)
        assert sexp[0] == 'private-key'
        kd = {}
        for name, data in sexp[1][1:]:
            kd[name] = common.getMP(common.NS(data))[0]
        if sexp[1][0] == 'dsa':
            assert len(kd) == 5, len(kd)
            return Class(
                DSA.construct((kd['y'], kd['g'], kd['p'], kd['q'], kd['x'])))
        elif sexp[1][0] == 'rsa-pkcs1':
            assert len(kd) == 8, len(kd)
            if kd['p'] > kd['q']:  # make p smaller than q
                kd['p'], kd['q'] = kd['q'], kd['p']
            return Class(
                RSA.construct((kd['n'], kd['e'], kd['d'], kd['p'], kd['q'])))
        else:
            raise BadKeyError('unknown lsh key type %s' % sexp[1][0])
Example #16
0
def dsaToKey(vm,dsa):
    yy=loadBN(dsa.deref('pub_key'))
    gg=loadBN(dsa.deref('g'))
    pp=loadBN(dsa.deref('p'))
    qq=loadBN(dsa.deref('q'))
    xx=loadBN(dsa.deref('priv_key'))
    return DSA.construct((yy,gg,pp,qq,xx))
Example #17
0
def dsa_sign(priv, msg):
    if isinstance(msg, int):
        msg = msg.to_bytes((msg.bit_length() // 8) + 1, 'big')
    msg = sha512(msg).digest()
    dsa = DSA.construct((pow(G, priv, P), G, P, Q, priv))
    k = Rand.randrange(1, Q)
    return dsa.sign(msg, k)
 def _construct_DSA(self,privkey):
     k,x = privkey
     return DSA.construct([self.pubkey.y,
                           self.pubkey.g,
                           self.pubkey.p,
                           self.pubkey.q,
                           x])
Example #19
0
def dsa_sign_validate(key, signature, message):
    dsakey = DSA.construct(key)
    h = SHA.new(message).digest()
    if dsakey.verify(h,signature):
        return True
    else:
        return False
Example #20
0
    def Read(key):
        """
    Reads a DSA public key from a JSON string representation of it.

    @param key: a JSON representation of a DSA public key
    @type key: string

    @return: a DSA public key
    @rtype: L{DsaPublicKey}
    """

        dsa = json.loads(key)
        params = {
            "y": util.Base64WSDecode(dsa["y"]),
            "p": util.Base64WSDecode(dsa["p"]),
            "g": util.Base64WSDecode(dsa["g"]),
            "q": util.Base64WSDecode(dsa["q"]),
        }
        pubkey = DSA.construct(
            (
                util.BytesToLong(params["y"]),
                util.BytesToLong(params["g"]),
                util.BytesToLong(params["p"]),
                util.BytesToLong(params["q"]),
            )
        )
        return DsaPublicKey(params, pubkey, dsa["size"])
Example #21
0
	def load_unencrypted(pkeyInfo):
		version, pkeyAlgo, pkeyData = pkeyInfo[0:3]
		if version != 0:
			raise PKCSError('unknown PKCS#8 version: {}'.format(version))
		algoId, algoParms = pkeyAlgo.get_pos(0,2)
		if algoId == OID_PKCS_RSAPKEY:
			from Crypto.PublicKey import RSA
			rsakey = asn1.loads(pkeyData)
			vals = rsakey[1:6] # n, e, d, p, q
			pkey = RSA.construct([long(val) for val in vals])
			print 'RSA!', vals
		elif algoId == OID_PKCS_DSAPKEY:
			from Crypto.PublicKey import DSA
			p, q, g = algoParms
			x = asn1.loads(pkeyData)
			y = pow(g, x, p)
			vals = (y, g, p, q, x)
			pkey = DSA.construct([long(val) for val in vals])
		elif algoId == OID_PKCS_DHPKEY:
			from Crypto.PublicKey import ElGamal
			p, g = algoParms[0:2]
			x = asn1.loads(pkeyData)
			y = pow(g, x, p)
			vals = (p, g, y, x)
			pkey = ElGamal.construct([long(val) for val in vals])
		else:
			raise PKCSError('unknown PKCS#8 key algorithm: {}'.format(algoId))
		return pkey
Example #22
0
def make_pkey(keyAlg, keyData, isPublic):
	algoId, algoParams = keyAlg.get_slice(0,2)
	if algoId == OID_PKCS_RSAKEY:
		from Crypto.PublicKey import RSA
		vals = asn1.loads(keyData)
		if isPublic:
			vals = vals[0:2] # n, e
		else:
			vals = vals[1:6] # n, e, d, p, q
		key = RSA.construct([long(val) for val in vals])
	elif algoId == OID_X957_DSAKEY:
		from Crypto.PublicKey import DSA
		p, q, g = algoParams
		val = asn1.loads(keyData)
		if isPublic:
			vals = (val, g, p, q) # y, g, p, q
		else:
			y = pow(g, val, p)
			vals = (y, g, p, q, val) # y, g, p, q, x
		key = DSA.construct([long(val) for val in vals])
	else:
		raise ValueError('unknown key algorithm id: {}'.format(algoId))
#	if attrs:
#		for attrId, attrValues in attrs:
#			if attrId in ATTR_NAMES and attrValues:
#				setattr(key, ATTR_NAMES[attrId], attrValues[0])
	return key
Example #23
0
def dsa_verify(pub, msg, sig):
    if isinstance(msg, int):
        msg = msg.to_bytes((msg.bit_length() // 8) + 1, 'big')
    msg = sha512(msg).digest()
    dsa = DSA.construct((pub, G, P, Q))
    if not dsa.verify(msg, sig):
        raise ValueError("dsa verification failed")
Example #24
0
    def _fromString_PUBLIC_LSH(Class, data):
        """
        Return a public key corresponding to this LSH public key string.
        The LSH public key string format is::
            <s-expression: ('public-key', (<key type>, (<name, <value>)+))>

        The names for a RSA (key type 'rsa-pkcs1-sha1') key are: n, e.
        The names for a DSA (key type 'dsa') key are: y, g, p, q.

        @type data: C{bytes}
        @return: a C{Crypto.PublicKey.pubkey.pubkey} object
        @raises BadKeyError: if the key type is unknown
        """
        sexp = sexpy.parse(base64.decodestring(data[1:-1]))
        assert sexp[0] == b'public-key'
        kd = {}
        for name, data in sexp[1][1:]:
            kd[name] = common.getMP(common.NS(data))[0]
        if sexp[1][0] == b'dsa':
            return Class(
                DSA.construct((kd[b'y'], kd[b'g'], kd[b'p'], kd[b'q'])))
        elif sexp[1][0] == b'rsa-pkcs1-sha1':
            return Class(RSA.construct((kd[b'n'], kd[b'e'])))
        else:
            raise BadKeyError('unknown lsh key type %s' % (sexp[1][0], ))
Example #25
0
def solve():
    with open("public.pem", "rb") as public:
        public_dsa = DSA.importKey(public.read())
    with open('signed', 'rb') as f:
        signed_msg = f.read()
    with open('signature', 'rb') as f:
        r, s = eval(f.read())
    with open('sign_me', 'rb') as f:
        to_sign = f.read()

    k = nonce(signed_msg, public_dsa.q)
    hashed_message = int.from_bytes(SHA.new(signed_msg).digest(),
                                    byteorder='big')
    x = (((s * k) - hashed_message) * modinv(r, public_dsa.q)) % public_dsa.q
    if x:
        print('Found a potential private key !')
    else:
        raise Exception('Problem when calculating the private key')

    private_dsa = DSA.construct(
        (public_dsa.y, public_dsa.g, public_dsa.p, public_dsa.q, x))
    # verify the private key is the right one:
    new_r, new_s = private_dsa.sign(hashed_message, k)
    if new_r != r or new_s != s:
        print(
            "Error when getting the private key, the generated signature doesn't coincide with the known one"
        )
        return
    else:
        print("The private key found is the right one")
    to_sign_hashed = SHA.new(to_sign).digest()
    solution = private_dsa.sign(to_sign_hashed, nonce(to_sign, public_dsa.q))
    print('Here is the signed message: {}'.format(solution))
Example #26
0
 def testExportKey5(self):
     tup = (self.y, self.g, self.p, self.q, self.x)
     key = DSA.construct(tup)
     encoded = key.exportKey('DER')
     self.assertEqual(self.der_pkcs8, encoded)
     encoded = key.exportKey('DER', pkcs8=True)
     self.assertEqual(self.der_pkcs8, encoded)
Example #27
0
def strtoprivkey(data, password):
    kind = data[0][11:14]
    if data[1].startswith('Proc-Type: 4,ENCRYPTED'):  # encrypted key
        if not password:
            raise BadKeyPassword("password required")
        enc_type, salt = data[2].split(": ")[1].split(",")
        salt = unhexlify(salt.strip())
        b64Data = base64.decodestring(''.join(data[4:-1]))
        if enc_type == "DES-EDE3-CBC":
            key = get_key_data(salt, password, 24)
            keyData = DES3.new(key, DES3.MODE_CBC, salt).decrypt(b64Data)
        elif enc_type == "AES-128-CBC":
            key = get_key_data(salt, password, 16)
            keyData = AES.new(key, AES.MODE_CBC, salt).decrypt(b64Data)
        else:
            raise BadKeyError("unknown encryption")
        removeLen = ord(keyData[-1])
        keyData = keyData[:-removeLen]
    else:
        keyData = base64.decodestring(''.join(data[1:-1]))
    decodedKey = asn1parse(keyData)
    if isinstance(decodedKey[0], list):
        decodedKey = decodedKey[0]  # this happens with encrypted keys
    if kind == 'RSA':
        n, e, d, p, q = decodedKey[1:6]
        return RSA.construct((n, e, d, p, q))
    elif kind == 'DSA':
        p, q, g, y, x = decodedKey[1:6]
        return DSA.construct((y, g, p, q, x))
Example #28
0
def strtoprivkey(data, password):
    kind = data[0][11: 14]
    if data[1].startswith('Proc-Type: 4,ENCRYPTED'):  # encrypted key
        if not password:
            raise BadKeyPassword("password required")
        enc_type, salt = data[2].split(": ")[1].split(",")
        salt = unhexlify(salt.strip())
        b64Data = base64.decodestring(''.join(data[4:-1]))
        if enc_type == "DES-EDE3-CBC":
            key = get_key_data(salt, password, 24)
            keyData = DES3.new(key, DES3.MODE_CBC, salt).decrypt(b64Data)
        elif enc_type == "AES-128-CBC":
            key = get_key_data(salt, password, 16)
            keyData = AES.new(key, AES.MODE_CBC, salt).decrypt(b64Data)
        else:
            raise BadKeyError("unknown encryption")
        removeLen = ord(keyData[-1])
        keyData = keyData[:-removeLen]
    else:
        keyData = base64.decodestring(''.join(data[1:-1]))
    decodedKey = asn1parse(keyData)
    if isinstance(decodedKey[0], list):
        decodedKey = decodedKey[0]  # this happens with encrypted keys
    if kind == 'RSA':
        n, e, d, p, q = decodedKey[1:6]
        return RSA.construct((n, e, d, p, q))
    elif kind == 'DSA':
        p, q, g, y, x = decodedKey[1: 6]
        return DSA.construct((y, g, p, q, x))
Example #29
0
def DSA_times(tests_information):
    key_param = [line.strip('\n') for line in open("dsa_key_params.txt")]
    p = int(key_param[0], 16)
    q = int(key_param[1], 16)
    g = int(key_param[2], 16)
    x = int(key_param[3], 16)
    y = int(key_param[4], 16)

    key = DSA.construct([y, g, p, q, x])  #Construccion de la llave
    sign_times = []
    verify_times = []
    print(key)
    for t in tests_information:
        [hash_type, message] = t.split(',')
        h = hashed_message(hash_type, message)

        #sign
        start_time = time.perf_counter()
        sign = DSA_sign(key, h)
        elapsed_time = time.perf_counter() - start_time
        sign_times.append(elapsed_time)

        #verification
        start_time = time.perf_counter()
        DSA_verify(sign, key, h)
        elapsed_time = time.perf_counter() - start_time
        verify_times.append(elapsed_time)

    return [sign_times, verify_times]
Example #30
0
    def _fromString_BLOB(Class, blob):
        """
        Return a public key object corresponding to this public key blob.
        The format of a RSA public key blob is::
            string 'ssh-rsa'
            integer e
            integer n

        The format of a DSA public key blob is::
            string 'ssh-dss'
            integer p
            integer q
            integer g
            integer y

        @type blob: C{str}
        @return: a C{Crypto.PublicKey.pubkey.pubkey} object
        @raises BadKeyError: if the key type (the first string) is unknown.
        """
        keyType, rest = common.getNS(blob)
        if keyType == 'ssh-rsa':
            e, n, rest = common.getMP(rest, 2)
            return Class(RSA.construct((n, e)))
        elif keyType == 'ssh-dss':
            p, q, g, y, rest = common.getMP(rest, 4)
            return Class(DSA.construct((y, g, p, q)))
        else:
            raise BadKeyError('unknown blob type: %s' % keyType)
Example #31
0
    def _fromString_PRIVATE_LSH(Class, data):
        """
        Return a private key corresponding to this LSH private key string.
        The LSH private key string format is::
            <s-expression: ('private-key', (<key type>, (<name>, <value>)+))>

        The names for a RSA (key type 'rsa-pkcs1-sha1') key are: n, e, d, p, q.
        The names for a DSA (key type 'dsa') key are: y, g, p, q, x.

        @type data: C{str}
        @return: a {Crypto.PublicKey.pubkey.pubkey} object
        @raises BadKeyError: if the key type is unknown
        """
        sexp = sexpy.parse(data)
        assert sexp[0] == 'private-key'
        kd = {}
        for name, data in sexp[1][1:]:
            kd[name] = common.getMP(common.NS(data))[0]
        if sexp[1][0] == 'dsa':
            assert len(kd) == 5, len(kd)
            return Class(DSA.construct((kd['y'], kd['g'], kd['p'],
                kd['q'], kd['x'])))
        elif sexp[1][0] == 'rsa-pkcs1':
            assert len(kd) == 8, len(kd)
            if kd['p'] > kd['q']: # make p smaller than q
                kd['p'], kd['q'] = kd['q'], kd['p']
            return Class(RSA.construct((kd['n'], kd['e'], kd['d'],
                kd['p'], kd['q'])))
        else:
            raise BadKeyError('unknown lsh key type %s' % sexp[1][0])
Example #32
0
    def _fromString_BLOB(Class, blob):
        """
        Return a public key object corresponding to this public key blob.
        The format of a RSA public key blob is::
            string 'ssh-rsa'
            integer e
            integer n

        The format of a DSA public key blob is::
            string 'ssh-dss'
            integer p
            integer q
            integer g
            integer y

        @type blob: C{str}
        @return: a C{Crypto.PublicKey.pubkey.pubkey} object
        @raises BadKeyError: if the key type (the first string) is unknown.
        """
        keyType, rest = common.getNS(blob)
        if keyType == 'ssh-rsa':
            e, n, rest = common.getMP(rest, 2)
            return Class(RSA.construct((n, e)))
        elif keyType == 'ssh-dss':
            p, q, g, y, rest = common.getMP(rest, 4)
            return Class(DSA.construct((y, g, p, q)))
        else:
            raise BadKeyError('unknown blob type: %s' % keyType)
Example #33
0
def validate_dsa_key_pair(public_key, private_key):
    """ Validates a pair of dsa keys """

    # FIXME: Make this function validate private key too

    # Construct DSA key
    keystring = binascii.a2b_base64(public_key.split(" ")[1])
    keyparts = []

    while len(keystring) > 4:
        length = struct.unpack(">I", keystring[:4])[0]
        keyparts.append(keystring[4 : 4 + length])
        keystring = keystring[4 + length :]

    if keyparts[0] == "ssh-dss":
        tup = [bytes_to_long(keyparts[x]) for x in (4, 3, 1, 2)]
    else:
        return False

    key = DSA.construct(tup)

    # Validate DSA key
    fmt_error = not isPrime(key.p)
    fmt_error |= ((key.p - 1) % key.q) != 0
    fmt_error |= key.g <= 1 or key.g >= key.p
    fmt_error |= pow(key.g, key.q, key.p) != 1
    fmt_error |= key.y <= 0 or key.y >= key.p

    # The following piece of code is currently useless, because 'x' attribute is the private key
    # if hasattr(key, 'x'):
    #    fmt_error |= key.x<=0 or key.x>=key.q
    #    fmt_error |= pow(key.g, key.x, key.p)!=key.y

    return not fmt_error
Example #34
0
 def testExportKey6(self):
     tup = (self.y, self.g, self.p, self.q, self.x)
     key = DSA.construct(tup)
     encoded = key.export_key('PEM')
     self.assertEqual(self.pem_pkcs8, encoded)
     encoded = key.export_key('PEM', pkcs8=True)
     self.assertEqual(self.pem_pkcs8, encoded)
Example #35
0
def verify_DSA(msg, sig_tuple, key_tuple):
    """Verify a DSA signature.

    :Parameters:
        - `msg`: string of data signature applies to 
        - `sig_tuple`: tuple of DSA signature integers (r, s)
          (see `DSA signature tuple`_)
        - `key_tuple`: tuple of DSA key integers (y, g, p, q)
          (see `DSA key tuple`_)
    
    :Returns: integer 1 or 0, for verification true or false

    .. _DSA signature tuple:

    DSA signature tuple:

            - `r`: integer DSA "r"
            - `s`: integer DSA "s"
            
    .. _DSA key tuple:

    DSA key tuple:

            - `y`: integer DSA public key
            - `g`: integer DSA group
            - `p`: integer DSA prime
            - `q`: integer DSA order
    """
    import Crypto.PublicKey.DSA as DSA
    dsa = DSA.construct(key_tuple) # note change in ordering
    return dsa.verify(msg, sig_tuple)
 def testExportKey5(self):
     tup = (self.y, self.g, self.p, self.q, self.x)
     key = DSA.construct(tup)
     encoded = key.exportKey('DER')
     self.assertEqual(self.der_pkcs8, encoded)
     encoded = key.exportKey('DER', pkcs8=True)
     self.assertEqual(self.der_pkcs8, encoded)
Example #37
0
def gen_default_dsa_key():
    y = 10065689456240776697243340416224367304785334515903313938753754692449556744891294275571921504812155755633033070842442588494918706471482430570053177445644851409815983894470226083940844477850160279070472918743069426277569357040310205734636800470656967025557907735225590493033003364020999812910619036024526885174
    x = 421795802289395826330823439675135199394937484571
    p = 89884656743115803759180203114063383466180690588722053911463224944885017434174903858634611545540835526658396218743967959201220771129990761195103857796657133483888273939088694871893945049965573302513381214518927077553282692268109694520931555898962816380021211527704558026558765695609946702501030536821136113329
    q = 755719585439660880181233694028045355865479263581
    g = 3858849187684168834100460213688488364714152124092208039472479785767018518758411189129858105331022159237787752225919238451049099638627854779720795529639191345479493879067880151209974626184020193962141724836702547632962279245016730666514536955424657022187744035456419806555119892163419599934826518566694719935

    return DSA.construct((y, g, p, q, x))
Example #38
0
    def __init__(self, key=None):
        self.priv = self.pub = None
        if isinstance(key, tuple):
            if len(key) == 5:
                self.priv = DSA.construct(key)
                self.pub = self.priv.publickey()
            if len(key) == 4:
                self.pub = DSA.construct(key)
        elif isinstance(key, DSA._DSAobj):
            if key.has_private():
                self.priv = key
                self.pub = self.priv.publickey()
            else:
                self.pub = key

        if self.priv is None and self.pub is None:
            raise TypeError('DSA object or 4/5-tuple required for key')
 def testExportError2(self):
     tup = (self.y, self.g, self.p, self.q, self.x)
     key = DSA.construct(tup)
     self.assertRaises(ValueError,
                       key.exportKey,
                       'DER',
                       pkcs8=False,
                       passphrase="PWDTEST")
 def testA02PyCryptoDSAVerification(self):
     """PyCrypto.PublicKey.DSA._verify: PyCrypto signature verification"""
     # this file has known good signature parameters
     sig = pickle.load(file('pgpfiles'+os.sep+'sig'+os.sep+'DSA_sig_test.pkl.py'))
     dsa = DSA.construct((sig['dsa_y'], sig['dsa_g'], sig['dsa_p'], sig['dsa_q'], sig['dsa_x']))
     r_s = dsa.sign(sig['msg'], sig['k'])
     ret = dsa.verify(sig['msg'], r_s)
     self.assertEqual(1, ret)
Example #41
0
def get_dsa_key(key_location=None, key_file_obj=None, passphrase=None, use_pycrypto=False):
    key_fobj = key_file_obj or open(key_location)
    try:
        key = paramiko.DSSKey.from_private_key(key_fobj, password=passphrase)
        if use_pycrypto:
            key = DSA.construct((key.y, key.g, key.p, key.q, key.x))
        return key
    except (paramiko.SSHException, ValueError):
        raise exception.SSHError("Invalid DSA private key file or missing passphrase: %s" % key_location)
 def privkey(self):
     """
     Reconstructs a DSA Signature Object
     :return: DSA Private Key Object
     """
     assert self.x  # privkey must be recovered fist
     return DSA.construct([
         self.pubkey.y, self.pubkey.g, self.pubkey.p, self.pubkey.q, self.x
     ])
Example #43
0
 def receive_dsa_key(self):
     message = self.splitter_socket.recv(struct.calcsize("256s256s256s40s"))
     y, g, p, q = struct.unpack("256s256s256s40s", message)
     y = self.convert_to_long(y)
     g = self.convert_to_long(g)
     p = self.convert_to_long(p)
     q = self.convert_to_long(q)
     self.dsa_key = DSA.construct((y, g, p, q))
     _print_("DSA key received")
Example #44
0
def import_dsa_key_from_file(file_name, encoding='base64'):
    from Crypto.Util import asn1
    with open(file_name) as f:
        seq = asn1.DerSequence()
        data = '\n'.join(f.read().strip().split('\n')[1:-1].decode(encoding))
        seq.decode(data)
        p, q, g, y, x = seq[1:]
        key = DSA.construct((y, g, p, q, x))
        return key
    def _fips_verify_positive(self, test_vectors):
        """Positive tests for signature verification"""

        for tv in test_vectors:
            self.description = tv.desc
            key = DSA.construct([tv.Y, tv.G, tv.P, tv.Q], False)
            hash_obj = tv.hashmod.new(tv.Msg)
            signer = DSS.new(key, 'fips-186-3')
            signer.verify(hash_obj, tv.Signature)
Example #46
0
def test_key():
    global key2
    k = [int(test_data[_], 16) for _ in ["y", "g", "p", "q", "x"]]
    key2 = key = DSA.construct(k)
    M = "This is a test message, OK?"
    K = bytes_to_long(os.urandom(19)) + 2
    H = SHA256.new(M)
    signature = key.sign(H.digest(), K)
    assert key.verify(H.digest(), signature)
Example #47
0
def import_dsa_private_key(str):
    from Crypto.Util import asn1
    from Crypto.PublicKey import DSA
    seq2 = asn1.DerSequence()
    data = "\n".join(str.strip().split("\n")[1:-1]).decode("base64")
    seq2.decode(data)
    p, q, g, y, x = seq2[1:]
    key2 = DSA.construct((y, g, p, q, x))
    return key2
Example #48
0
 def receive_dsa_key(self):
     message = self.splitter_socket.recv(struct.calcsize("256s256s256s40s"))
     y, g, p, q = struct.unpack("256s256s256s40s", message)
     y = self.convert_to_long(y)
     g = self.convert_to_long(g)
     p = self.convert_to_long(p)
     q = self.convert_to_long(q)
     self.dsa_key = DSA.construct((y, g, p, q))
     _print_("DSA key received")
    def test5(self):
        """Verify that unknown modes/encodings are rejected"""

        self.description = "Unknown mode test"
        key = DSA.construct((self.Y, self.G, self.P, self.Q))
        self.assertRaises(ValueError, DSS.new, key, 'fips-186-0')

        self.description = "Unknown encoding test"
        self.assertRaises(ValueError, DSS.new, key, 'fips-186-3', 'xml')
Example #50
0
 def testExportKey8(self):
     tup = (self.y, self.g, self.p, self.q, self.x)
     key = DSA.construct(tup)
     encoded = key.export_key('PEM', pkcs8=False, passphrase="PWDTEST")
     key = DSA.importKey(encoded, "PWDTEST")
     self.assertEqual(self.y, key.y)
     self.assertEqual(self.p, key.p)
     self.assertEqual(self.q, key.q)
     self.assertEqual(self.g, key.g)
     self.assertEqual(self.x, key.x)
Example #51
0
    def test2(self):

        for sig in self.signatures:
            tk = sig.test_key
            key = DSA.construct([tk.y, tk.g, tk.p, tk.q, tk.x], False)
            signer = DSS.new(key, 'deterministic-rfc6979')

            hash_obj = sig.module.new(sig.message)
            result = signer.sign(hash_obj)
            self.assertEqual(sig.result, result)
Example #52
0
def generateDSA(p, q, g):
    power = (p - 1) / q
    while 1:
        h = 2
        g = pow(h, power, p)
        x = bytes_to_long(os.urandom(20))
        if 0 < x < q:
            break
    y = pow(g, x, p)
    key = DSA.construct((y, g, p, q, x))
    return key
Example #53
0
File: qa_p2p.py Project: JD-P/mrc
 def base64_pub_decode(self, base64_pub):
     """Return a tuple with the variables y g p q given a base64 representation
     of a DSA public key."""
     base64_pub_bytes = self.base64_pub.encode('utf-8')
     pubkey_text = base64.b64decode(base64_pub_bytes)
     pubkey_vars = pubkey_text.split(":")
     y = int(pubkey_vars[0])
     g = int(pubkey_vars[1])
     p = int(pubkey_vars[2])
     q = int(pubkey_vars[3])
     return DSA.construct((y,g,p,q))
Example #54
0
    def decode_pkcs8_public(cls, alg_params, data):
        try:
            y = der_decode(data)
        except ASN1DecodeError:
            y = None

        if len(alg_params) == 3 and all_ints(alg_params) and isinstance(y, int):
            p, q, g = alg_params
            return cls(DSA.construct((y, g, p, q)))
        else:
            raise KeyImportError('Invalid DSA public key')
Example #55
0
 def sign(self, message):
     p, q, g, y, x = self.private_key
     dsa_obj = DSA.construct( (y, g, p, q, x) )
     message_hash = hashlib.sha1(message).digest()
     # Get a random number that is greater than 2 and less than q.
     random_number = random.get_random_number_from_range(2, q)
     random_data = number.long_to_bytes(random_number)
     r, s = dsa_obj.sign(message_hash, random_data)
     signature = number.long_to_bytes(r, 20) + number.long_to_bytes(s, 20)
     return packet.pack_payload(DSS_SIG_PAYLOAD,
                         ('ssh-dss',
                          signature))