Exemple #1
0
 def test_correctness_against_base_implementation(self):
     # Slow test.
     values = [1 << 512, 1 << 8192, 1 << 77]
     for value in values:
         self.assertEqual(int2bytes(value), _int2bytes(value), "Boom %d" % value)
         self.assertEqual(bytes2int(int2bytes(value)), value, "Boom %d" % value)
         self.assertEqual(bytes2int(_int2bytes(value)), value, "Boom %d" % value)
Exemple #2
0
 def test_correctness_against_base_implementation(self):
     # Slow test.
     values = [
         1 << 512,
         1 << 8192,
         1 << 77,
     ]
     for value in values:
         self.assertEqual(int2bytes(value), _int2bytes(value),
                          "Boom %d" % value)
         self.assertEqual(bytes2int(int2bytes(value)), value,
                          "Boom %d" % value)
         self.assertEqual(bytes2int(_int2bytes(value)), value,
                          "Boom %d" % value)
Exemple #3
0
def chopstring(message, key, n, int_op):
    """Chops the 'message' into integers that fit into n.
    
    Leaves room for a safebit to be added to ensure that all messages fold
    during exponentiation. The MSB of the number n is not independent modulo n
    (setting it could cause overflow), so use the next lower bit for the
    safebit. Therefore this function reserves 2 bits in the number n for
    non-data bits.

    Calls specified encryption function 'int_op' for each chop before storing.

    Used by 'encrypt' and 'sign'.
    """

    nbytes = block_size(n)

    msglen = len(message)
    blocks = msglen // nbytes

    if msglen % nbytes > 0:
        blocks += 1

    cypher = []

    for bindex in range(blocks):
        offset = bindex * nbytes
        block = message[offset:offset + nbytes]

        value = transform.bytes2int(block)
        to_store = int_op(value, key, n)

        cypher.append(to_store)

    return encode64chops(cypher)  #Encode encrypted ints to base64 strings
def sign(message, priv_key, hash):
    """Signs the message with the private key.
    
    Hashes the message, then signs the hash with the given key. This is known
    as a "detached signature", because the message itself isn't altered.
    
    :param message: the message to sign. Can be an 8-bit string or a file-like
        object. If ``message`` has a ``read()`` method, it is assumed to be a
        file-like object.
    :param priv_key: the :py:class:`rsa.PrivateKey` to sign with
    :param hash: the hash method used on the message. Use 'MD5', 'SHA-1',
        'SHA-256', 'SHA-384' or 'SHA-512'.
    :return: a message signature block.
    :raise OverflowError: if the private key is too small to contain the
        requested hash.
    
    """
    if hash not in HASH_ASN1:
        raise ValueError('Invalid hash method: %s' % hash)
    asn1code = HASH_ASN1[hash]
    hash = _hash(message, hash)
    cleartext = asn1code + hash
    keylength = common.byte_size(priv_key.n)
    padded = _pad_for_signing(cleartext, keylength)
    payload = transform.bytes2int(padded)
    encrypted = core.encrypt_int(payload, priv_key.d, priv_key.n)
    block = transform.int2bytes(encrypted, keylength)
    return block
Exemple #5
0
def encrypt_with_private_key(message, priv_key):
    """Encrypts the given message using PKCS#1 v1.5's private key

    :param message: the message to encrypt. Must be a byte string no longer than
        ``k-11`` bytes, where ``k`` is the number of bytes needed to encode
        the ``n`` component of the public key.
    :param priv_key: the :py:class:`rsa.PrivateKey` to encrypt with.
    :raise OverflowError: when the message is too large to fit in the padded
        block.

    >>> from rsa import key, common
    >>> (pub_key, priv_key) = key.newkeys(256)
    >>> message = b'hello'
    >>> crypto = encrypt_with_private_key(message, priv_key)

    """

    keylength = common.byte_size(priv_key.n)
    padded = _pad_for_signing(message, keylength)

    payload = transform.bytes2int(padded)
    encrypted = core.encrypt_int(payload, priv_key.d, priv_key.n)
    block = transform.int2bytes(encrypted, keylength)

    return block
def sign_hash(hash_value, priv_key, hash_method):
    """Signs a precomputed hash with the private key.

    Hashes the message, then signs the hash with the given key. This is known
    as a "detached signature", because the message itself isn't altered.

    :param hash_value: A precomputed hash to sign (ignores message). Should be set to
        None if needing to hash and sign message.
    :param priv_key: the :py:class:`rsa.PrivateKey` to sign with
    :param hash_method: the hash method used on the message. Use 'MD5', 'SHA-1',
        'SHA-224', SHA-256', 'SHA-384' or 'SHA-512'.
    :return: a message signature block.
    :raise OverflowError: if the private key is too small to contain the
        requested hash.

    """

    # Get the ASN1 code for this hash method
    if hash_method not in HASH_ASN1:
        raise ValueError('Invalid hash method: %s' % hash_method)
    asn1code = HASH_ASN1[hash_method]

    # Encrypt the hash with the private key
    cleartext = asn1code + hash_value
    keylength = common.byte_size(priv_key.n)
    padded = _pad_for_signing(cleartext, keylength)

    payload = transform.bytes2int(padded)
    encrypted = priv_key.blinded_encrypt(payload)
    block = transform.int2bytes(encrypted, keylength)

    return block
Exemple #7
0
def sign_hash(hash_value, priv_key, hash_method):
    """Signs a precomputed hash with the private key.

    Hashes the message, then signs the hash with the given key. This is known
    as a "detached signature", because the message itself isn't altered.

    :param hash_value: A precomputed hash to sign (ignores message). Should be set to
        None if needing to hash and sign message.
    :param priv_key: the :py:class:`rsa.PrivateKey` to sign with
    :param hash_method: the hash method used on the message. Use 'MD5', 'SHA-1',
        'SHA-256', 'SHA-384' or 'SHA-512'.
    :return: a message signature block.
    :raise OverflowError: if the private key is too small to contain the
        requested hash.

    """

    # Get the ASN1 code for this hash method
    if hash_method not in HASH_ASN1:
        raise ValueError('Invalid hash method: %s' % hash_method)
    asn1code = HASH_ASN1[hash_method]

    # Encrypt the hash with the private key
    cleartext = asn1code + hash_value
    keylength = common.byte_size(priv_key.n)
    padded = _pad_for_signing(cleartext, keylength)

    payload = transform.bytes2int(padded)
    encrypted = priv_key.blinded_encrypt(payload)
    block = transform.int2bytes(encrypted, keylength)

    return block
Exemple #8
0
def verify(message, signature, pub_key):
    """Verifies that the signature matches the message.

    The hash method is detected automatically from the signature.

    :param message: the signed message. Can be an 8-bit string or a file-like
        object. If ``message`` has a ``read()`` method, it is assumed to be a
        file-like object.
    :param signature: the signature block, as created with :py:func:`rsa.sign`.
    :param pub_key: the :py:class:`rsa.PublicKey` of the person signing the message.
    :raise VerificationError: when the signature doesn't match the message.
    :returns: the name of the used hash.

    """

    keylength = common.byte_size(pub_key.n)
    encrypted = transform.bytes2int(signature)
    decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n)
    clearsig = transform.int2bytes(decrypted, keylength)

    # Get the hash method
    method_name = _find_method_hash(clearsig)
    message_hash = compute_hash(message, method_name)

    # Reconstruct the expected padded hash
    cleartext = HASH_ASN1[method_name] + message_hash
    expected = _pad_for_signing(cleartext, keylength)

    # Compare with the signed one
    if expected != clearsig:
        raise VerificationError('Verification failed')

    return method_name
Exemple #9
0
def chopstring(message, key, n, int_op):
    """Chops the 'message' into integers that fit into n.
    
    Leaves room for a safebit to be added to ensure that all messages fold
    during exponentiation. The MSB of the number n is not independent modulo n
    (setting it could cause overflow), so use the next lower bit for the
    safebit. Therefore this function reserves 2 bits in the number n for
    non-data bits.

    Calls specified encryption function 'int_op' for each chop before storing.

    Used by 'encrypt' and 'sign'.
    """


    nbytes = block_size(n)

    msglen = len(message)
    blocks = msglen // nbytes

    if msglen % nbytes > 0:
        blocks += 1

    cypher = []
    
    for bindex in range(blocks):
        offset = bindex * nbytes
        block = message[offset:offset + nbytes]

        value = transform.bytes2int(block)
        to_store = int_op(value, key, n)

        cypher.append(to_store)

    return encode64chops(cypher)   #Encode encrypted ints to base64 strings
Exemple #10
0
def extract_raw_hash(signature, pub_key, is_sha256):
    hash_size = SHA256_HASH_SIZE if is_sha256 else SHA1_HASH_SIZE
    keylength = common.byte_size(pub_key.n)
    encrypted = transform.bytes2int(signature)
    decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n)
    clearsig = transform.int2bytes(decrypted, keylength)
    # unpad
    if (clearsig[0] != '\x00' or clearsig[1] != '\x01'):
        raise Exception('Invalid signature format')

    null_idx = clearsig.find('\x00', 2)
    if null_idx < 0:
        raise Exception('Invalid signature format')

    padding = clearsig[2:null_idx]
    if len(padding) != keylength - 2 - 1 - hash_size:
        raise Exception('Invalid signature format')
    if not all(p == '\xff' for p in padding):
        raise Exception('Invalid signature format')

    raw_hash = clearsig[null_idx + 1:]
    if len(raw_hash) != hash_size:
        raise Exception('Invalid signature format.')

    return raw_hash
Exemple #11
0
def encrypt(data: bytes, d, n):
    keylength = common.byte_size(n)
    padded = _pad_for_encryption(data, keylength)
    num = transform.bytes2int(padded)
    decrypto = core.encrypt_int(num, d, n)
    out = transform.int2bytes(decrypto)
    return out
Exemple #12
0
 def GetPassword(self,password,servertime,nonce):
     #得到加密后的密码
     pkey=int(self.pubkey, 16)
     pub_key  = rsa.PublicKey(pkey, int('10001', 16))
     password = '******' % (servertime, nonce, password)
     password =  (self.dec2hex(transform.bytes2int(rsa.encrypt(password.encode('utf-8'), pub_key))))
     return password
Exemple #13
0
def encrypt(message, pub_key):
    '''Encrypts the given message using PKCS#1 v1.5
    
    :param message: the message to encrypt. Must be a byte string no longer than
        ``k-11`` bytes, where ``k`` is the number of bytes needed to encode
        the ``n`` component of the public key.
    :param pub_key: the :py:class:`rsa.PublicKey` to encrypt with.
    :raise OverflowError: when the message is too large to fit in the padded
        block.
        
    >>> from rsa import key, common
    >>> (pub_key, priv_key) = key.newkeys(256)
    >>> message = 'hello'
    >>> crypto = encrypt(message, pub_key)
    
    The crypto text should be just as long as the public key 'n' component:

    >>> len(crypto) == common.byte_size(pub_key.n)
    True
    
    '''

    keylength = common.byte_size(pub_key.n)
    padded = _pad_for_encryption(message, keylength)

    payload = transform.bytes2int(padded)
    encrypted = core.encrypt_int(payload, pub_key.e, pub_key.n)
    block = transform.int2bytes(encrypted, keylength)

    return block
Exemple #14
0
def verify(message, signature, pub_key):
    """Verifies that the signature matches the message.

    The hash method is detected automatically from the signature.

    :param message: the signed message. Can be an 8-bit string or a file-like
        object. If ``message`` has a ``read()`` method, it is assumed to be a
        file-like object.
    :param signature: the signature block, as created with :py:func:`rsa.sign`.
    :param pub_key: the :py:class:`rsa.PublicKey` of the person signing the message.
    :raise VerificationError: when the signature doesn't match the message.

    """

    keylength = common.byte_size(pub_key.n)
    encrypted = transform.bytes2int(signature)
    decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n)
    clearsig = transform.int2bytes(decrypted, keylength)

    # Get the hash method
    method_name = _find_method_hash(clearsig)
    message_hash = _hash(message, method_name)

    # Reconstruct the expected padded hash
    cleartext = HASH_ASN1[method_name] + message_hash
    expected = _pad_for_signing(cleartext, keylength)

    # Compare with the signed one
    if expected != clearsig:
        raise VerificationError('Verification failed')

    return True
Exemple #15
0
def verify(message, signature, pubkey, encoding='utf8'):
    assert isinstance(message, str), 'message must be a sting!'
    assert isinstance(signature, str), 'signature must be a sting!'

    message = message.encode(encoding)
    signature_full = base64.b64decode(signature)
    pubder = base64.b64decode(pubkey)
    pub_key = rsa.PublicKey.load_pkcs1(pubder, 'DER')

    message_hash = hashlib.md5(message).digest()

    keylength = common.byte_size(pub_key.n)

    decrypted_hash = b''
    while signature_full:
        signature = signature_full[:keylength]
        signature_full = signature_full[keylength:]

        # ===== copy from rsa.pkcs1:verify =====
        encrypted = transform.bytes2int(signature)
        decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n)
        clearsig = transform.int2bytes(decrypted, keylength)

        if clearsig[0:2] != b'\x00\x01':
            return False
        clearsig = clearsig[2:]
        if b'\x00' not in clearsig:
            return False
        sep_idx = clearsig.index(b'\x00')
        clearsig = clearsig[sep_idx + 1:]

        decrypted_hash += clearsig

    return decrypted_hash == message_hash
Exemple #16
0
def sign(message, prikey, encoding='utf8'):
    assert isinstance(message, str), 'message must be a sting!'
    assert isinstance(prikey, str), 'prikey must be a sting!'

    message = message.encode(encoding)
    prider = base64.b64decode(prikey)
    priv_key = rsa.PrivateKey.load_pkcs1(prider, 'DER')

    message_hash = hashlib.md5(message).digest()

    keylength = common.byte_size(priv_key.n)
    block_length = keylength - 11
    assert block_length > 0, 'nbits of key is to small, please set bigger then 128!'

    signature = b''
    while message_hash:
        cleartext = message_hash[:block_length]
        message_hash = message_hash[block_length:]

        # ===== copy from rsa.pkcs1:sign_hash =====
        padded = _pad_for_signing(cleartext, keylength)
        payload = transform.bytes2int(padded)
        encrypted = priv_key.blinded_encrypt(payload)
        block = transform.int2bytes(encrypted, keylength)

        signature += block

    signature = base64.b64encode(signature).decode()
    return signature
Exemple #17
0
def verify(message, signature, pub_key):
    '''Verifies that the signature matches the message.
    
    The hash method is detected automatically from the signature.
    
    @param message: the signed message
    @param signature: the signature block, as created with ``sign(...)``.
    @param pub_key: the public key of the person signing the message.
    
    @raise VerificationError: when the signature doesn't match the message.
    '''

    blocksize = common.byte_size(pub_key['n'])
    encrypted = transform.bytes2int(signature)
    decrypted = core.decrypt_int(encrypted, pub_key['e'], pub_key['n'])
    clearsig = transform.int2bytes(decrypted, blocksize)

    # If we can't find the signature  marker, verification failed.
    if clearsig[0:2] != '\x00\x01':
        raise VerificationError('Verification failed')

    # Find the 00 separator between the padding and the payload
    try:
        sep_idx = clearsig.index('\x00', 2)
    except ValueError:
        raise VerificationError('Verification failed')

    # Get the hash and the hash method
    (method_name, signature_hash) = _find_method_hash(clearsig[sep_idx + 1:])
    message_hash = _hash(message, method_name)

    # Compare the real hash to the hash in the signature
    if message_hash != signature_hash:
        raise VerificationError('Verification failed')
Exemple #18
0
def encrypt(message, pub_key):
    keylength = common.byte_size(pub_key.n)
    padded = _pad_for_encryption(message, keylength)
    payload = transform.bytes2int(padded)
    encrypted = core.encrypt_int(payload, pub_key.e, pub_key.n)
    block = transform.int2bytes(encrypted, keylength)
    return block
Exemple #19
0
def encrypt(message, pub_key):
    '''Encrypts the given message using PKCS#1 v1.5
    
    :param message: the message to encrypt. Must be a byte string no longer than
        ``k-11`` bytes, where ``k`` is the number of bytes needed to encode
        the ``n`` component of the public key.
    :param pub_key: the :py:class:`rsa.PublicKey` to encrypt with.
    :raise OverflowError: when the message is too large to fit in the padded
        block.
        
    >>> from rsa import key, common
    >>> (pub_key, priv_key) = key.newkeys(256)
    >>> message = 'hello'
    >>> crypto = encrypt(message, pub_key)
    
    The crypto text should be just as long as the public key 'n' component:

    >>> len(crypto) == common.byte_size(pub_key.n)
    True
    
    '''
    
    keylength = common.byte_size(pub_key.n)
    padded = _pad_for_encryption(message, keylength)
    
    payload = transform.bytes2int(padded)
    encrypted = core.encrypt_int(payload, pub_key.e, pub_key.n)
    block = transform.int2bytes(encrypted, keylength)
    
    return block
Exemple #20
0
def pub_decode(message, pub_key):
    from rsa import common, transform, core
    keylength = common.byte_size(pub_key.n)
    encrypted = transform.bytes2int(message)
    decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n)
    clearsig = transform.int2bytes(decrypted, keylength)
    return clearsig
Exemple #21
0
def encrypt(message, pub_key):
    keylength = common.byte_size(pub_key.n)
    padded = _pad_for_encryption(message, keylength)
    payload = transform.bytes2int(padded)
    encrypted = core.encrypt_int(payload, pub_key.e, pub_key.n)
    block = transform.int2bytes(encrypted, keylength)
    return block
Exemple #22
0
def decrypt(data: bytes, d, n):
    num = transform.bytes2int(data)
    decrypto = core.decrypt_int(num, d, n)
    out = transform.int2bytes(decrypto)
    sep_idx = out.index(b"\x00", 2)
    out = out[sep_idx + 1:]
    return out
Exemple #23
0
def verify(message, signature, pub_key):
    '''Verifies that the signature matches the message.
    
    The hash method is detected automatically from the signature.
    
    @param message: the signed message
    @param signature: the signature block, as created with ``sign(...)``.
    @param pub_key: the public key of the person signing the message.
    
    @raise VerificationError: when the signature doesn't match the message.
    '''
    
    blocksize = common.byte_size(pub_key['n']) 
    encrypted = transform.bytes2int(signature)
    decrypted = core.decrypt_int(encrypted, pub_key['e'], pub_key['n'])
    clearsig = transform.int2bytes(decrypted, blocksize)

    # If we can't find the signature  marker, verification failed.
    if clearsig[0:2] != '\x00\x01':
        raise VerificationError('Verification failed')
    
    # Find the 00 separator between the padding and the payload
    try:
        sep_idx = clearsig.index('\x00', 2)
    except ValueError:
        raise VerificationError('Verification failed')
    
    # Get the hash and the hash method
    (method_name, signature_hash) = _find_method_hash(clearsig[sep_idx+1:])
    message_hash = _hash(message, method_name)

    # Compare the real hash to the hash in the signature
    if message_hash != signature_hash:
        raise VerificationError('Verification failed')
Exemple #24
0
 def get_pwd(self, pwd, servertime, nonce):
     p = int(self.pubkey, 16)
     pub_key = rsa.PublicKey(p, int('10001', 16))
     pwd = '%s\t%s\n%s' % (servertime, nonce, pwd)
     pwd = (self.dec2hex(transform.bytes2int(rsa.encrypt(pwd.encode('utf-8'), 
                                                         pub_key))))
     
     return pwd
Exemple #25
0
 def decrypt(self, data: bytes):
     num = transform.bytes2int(data)
     decrypto = core.decrypt_int(num, self.pub_key.e, self.pub_key.n)
     out = transform.int2bytes(decrypto)
     logger.info(out)
     sep_idx = out.index(b"\x00", 2)
     out = out[sep_idx + 1:]
     return out
Exemple #26
0
def decrypt_by_public_key(publickey, message):
    rsa_public_key = PublicKey.load_pkcs1_openssl_der(
        base64.b64decode(publickey))
    text_str = transform.bytes2int(base64.b64decode(message))
    final_text = transform.int2bytes(
        core.decrypt_int(text_str, rsa_public_key.e, rsa_public_key.n))
    final_qr_code = final_text[final_text.index(0) + 1:]
    return final_qr_code.decode()
Exemple #27
0
 def decrypt(rsa_key, rsa_str):
     rsa_bytes = base64.decodebytes(rsa_str.encode())
     rsa_key = PublicKey.load_pkcs1_openssl_pem(rsa_key.encode())
     num = transform.bytes2int(rsa_bytes)
     decry = core.decrypt_int(num, rsa_key.e, rsa_key.n)
     out = transform.int2bytes(decry)
     sep_idx = out.index(b"\x00", 2)
     out = out[sep_idx + 1:]
     return out
Exemple #28
0
def read_random_int(nbits: int) -> int:
    randomdata = read_random_bits(nbits)
    value = transform.bytes2int(randomdata)

    # Ensure that the number is large enough to just fill out the required
    # number of bits.
    value |= 1 << (nbits - 1)

    return value
Exemple #29
0
def extract_hash(pub_key,data):
    hashlen = 32 #SHA256
    keylen = common.byte_size(pub_key.n)
    encrypted = transform.bytes2int(data)
    decrypted = transform.int2bytes(core.decrypt_int(encrypted, pub_key.e, pub_key.n),keylen)
    hash = decrypted[-hashlen:]
    if (decrypted[0:2] != b'\x00\x01') or (len(hash) != hashlen):
        raise Exception('Signature error')
    return hash
Exemple #30
0
def create_contacts(owner_id, user_id, alias, owner_pub_key):
    encrypted_alias = rsa_encryption(owner_pub_key, alias)
    encrypted_alias = bytes2int(encrypted_alias)

    data_post = {'owner_id': int(owner_id),
                 'user_id': int(user_id),
                 'encrypted_alias': str(encrypted_alias)}
    resp_post_json = make_post_request('/api/contacts', data_post)

    return resp_post_json
Exemple #31
0
    def sign(self, string_to_sign):
        """Sign the data in a emulation of the OpenSSL private_encrypt method"""
        hashed = sha512(string_to_sign.encode('US-ASCII')).hexdigest()
        keylength = common.byte_size(self.pk.n)
        padded = self.pad_for_signing(hashed, keylength)

        payload = transform.bytes2int(padded)
        encrypted = core.encrypt_int(payload, self.pk.d,  self.pk.n)
        signature = transform.int2bytes(encrypted, keylength).encode('base64').replace('\n','')
        return signature
Exemple #32
0
def send_message(chat_id, sender_id, message,
                 symmetric_key_encrypted_by_own_pub_key, owner_private_key):
    symmetric_key_encrypted_by_own_pub_key = int2bytes(int(symmetric_key_encrypted_by_own_pub_key))

    key = rsa_decryption(owner_private_key, symmetric_key_encrypted_by_own_pub_key)
    encrypted_message = encryption(message, key)
    encrypted_message = bytes2int(encrypted_message)

    hash = hashlib.sha256((str(chat_id) + str(sender_id) + str(encrypted_message)).encode()).hexdigest()

    signedHash = bytes2int(rsa_signing(owner_private_key, hash))

    data_post = {'chat_id': int(chat_id),
                 'sender_id': int(sender_id),
                 'message': str(encrypted_message),
                 'hash': signedHash}
    resp_post_json = make_post_request('/api/message/new', data_post)

    return resp_post_json
    def encrypt(self, message, file):
        self._load_key_file(file)
        keylength = common.byte_size(self._private_key.n)
        padded = pkcs1._pad_for_signing(bytes(message, encoding="utf-8"),
                                        keylength)

        payload = transform.bytes2int(padded)
        encrypted = self._private_key.blinded_encrypt(payload)
        block = transform.int2bytes(encrypted, keylength)
        return base64.urlsafe_b64encode(block).decode("utf-8")
Exemple #34
0
def encryptSignature(signature, priv_key):
    cleartext = signature
    keylength = common.byte_size(priv_key.n)
    padded = cry._pad_for_encryption(cleartext, keylength)

    payload = transform.bytes2int(padded)
    encrypted = priv_key.blinded_encrypt(payload)
    block = transform.int2bytes(encrypted, keylength)

    return block
Exemple #35
0
def read_random_int(nbits: int) -> int:
    """Reads a random integer of approximately nbits bits."""

    randomdata = read_random_bits(nbits)
    value = transform.bytes2int(randomdata)

    # Ensure that the number is large enough to just fill out the required
    # number of bits.
    value |= 1 << (nbits - 1)

    return value
 def get_pwd(self, pwd, servertime, nonce):
     #pwd1 = hashlib.sha1(pwd).hexdigest()
     #pwd2 = hashlib.sha1(pwd1).hexdigest()
     #pwd3_ = pwd2 + servertime + nonce
     #pwd3 = hashlib.sha1(pwd3_).hexdigest()
     #return pwd3
     p = int(self.pubkey, 16)
     pub_key  = rsa.PublicKey(p, int('10001', 16))
     pwd = '%s\t%s\n%s' % (servertime, nonce, pwd)
     pwd =  (self.dec2hex(transform.bytes2int(rsa.encrypt(pwd.encode('utf-8'), pub_key))))
     return pwd
 def decrypt(encrypted_bytes, rsa_public_key):
     # public_key = PublicKey.load_pkcs1(rsa_public_key)
     encrypted = transform.bytes2int(encrypted_bytes)
     decrypted_int = core.decrypt_int(encrypted, rsa_public_key.e,
                                      rsa_public_key.n)
     decrypted_bytes = transform.int2bytes(decrypted_int)
     if len(decrypted_bytes) > 0 and decrypted_bytes[0] == 1:
         pos = decrypted_bytes.find(b'\x00')
         if pos > 0:
             return decrypted_bytes[pos + 1:]
     print("公钥解密异常:", decrypted_bytes)
     return b''
Exemple #38
0
def read_random_int(nbits):
    """Reads a random integer of approximately nbits bits.
    """

    randomdata = read_random_bits(nbits)
    value = transform.bytes2int(randomdata)

    # Ensure that the number is large enough to just fill out the required
    # number of bits.
    value |= 1 << (nbits - 1)

    return value
Exemple #39
0
def sign(message, priv_key, hash):
    if hash not in HASH_ASN1:
        raise ValueError('Invalid hash method: %s' % hash)
    asn1code = HASH_ASN1[hash]
    hash = _hash(message, hash)
    cleartext = asn1code + hash
    keylength = common.byte_size(priv_key.n)
    padded = _pad_for_signing(cleartext, keylength)
    payload = transform.bytes2int(padded)
    encrypted = core.encrypt_int(payload, priv_key.d, priv_key.n)
    block = transform.int2bytes(encrypted, keylength)
    return block
Exemple #40
0
def decrypt(crypto, priv_key):
    r"""Decrypts the given message using PKCS#1 v1.5
    The decryption is considered 'failed' when the resulting cleartext doesn't
    start with the bytes 00 02, or when the 00 byte between the padding and
    the message cannot be found.
    :param crypto: the crypto text as returned by :py:func:`rsa.encrypt`
    :param priv_key: the :py:class:`rsa.PrivateKey` to decrypt with.
    :raise DecryptionError: when the decryption fails. No details are given as
        to why the code thinks the decryption fails, as this would leak
        information about the private key.
    >>> import rsa
    >>> (pub_key, priv_key) = rsa.newkeys(256)
    It works with strings:
    >>> crypto = encrypt(b'hello', pub_key)
    >>> decrypt(crypto, priv_key)
    b'hello'
    And with binary data:
    >>> crypto = encrypt(b'\x00\x00\x00\x00\x01', pub_key)
    >>> decrypt(crypto, priv_key)
    b'\x00\x00\x00\x00\x01'
    Altering the encrypted information will *likely* cause a
    :py:class:`rsa.pkcs1.DecryptionError`. If you want to be *sure*, use
    :py:func:`rsa.sign`.
    .. warning::
        Never display the stack trace of a
        :py:class:`rsa.pkcs1.DecryptionError` exception. It shows where in the
        code the exception occurred, and thus leaks information about the key.
        It's only a tiny bit of information, but every bit makes cracking the
        keys easier.
    >>> crypto = encrypt(b'hello', pub_key)
    >>> crypto = crypto[0:5] + b'X' + crypto[6:] # change a byte
    >>> decrypt(crypto, priv_key)
    Traceback (most recent call last):
    ...
    rsa.pkcs1.DecryptionError: Decryption failed
    """

    blocksize = common.byte_size(priv_key.n)
    encrypted = transform.bytes2int(crypto)
    decrypted = priv_key.blinded_decrypt(encrypted)
    cleartext = transform.int2bytes(decrypted, blocksize)

    # If we can't find the cleartext marker, decryption failed.
    if cleartext[0:2] != b'\x00\x02':
        raise DecryptionError('Decryption failed')

    # Find the 00 separator between the padding and the message
    try:
        sep_idx = cleartext.index(b'\x00', 2)
    except ValueError:
        raise DecryptionError('Decryption failed')

    return cleartext[sep_idx + 1:]
Exemple #41
0
def encrypt_zero_padding(message, pub_key):
    '''Encrypts the given message without random padding    
    '''
    
    keylength = common.byte_size(pub_key.n)
    padded = _pad_zero(message, keylength)
    
    payload = transform.bytes2int(padded)
    encrypted = core.encrypt_int(payload, pub_key.e, pub_key.n)
    block = transform.int2bytes(encrypted, keylength)
    
    return block
Exemple #42
0
def sign(message, priv_key, hash):
    if hash not in HASH_ASN1:
        raise ValueError('Invalid hash method: %s' % hash)
    asn1code = HASH_ASN1[hash]
    hash = _hash(message, hash)
    cleartext = asn1code + hash
    keylength = common.byte_size(priv_key.n)
    padded = _pad_for_signing(cleartext, keylength)
    payload = transform.bytes2int(padded)
    encrypted = core.encrypt_int(payload, priv_key.d, priv_key.n)
    block = transform.int2bytes(encrypted, keylength)
    return block
 def get_pwd(self, pwd, servertime, nonce):
     #pwd1 = hashlib.sha1(pwd).hexdigest()
     #pwd2 = hashlib.sha1(pwd1).hexdigest()
     #pwd3_ = pwd2 + servertime + nonce
     #pwd3 = hashlib.sha1(pwd3_).hexdigest()
     #return pwd3
     p = int(self.pubkey, 16)
     pub_key = rsa.PublicKey(p, int('10001', 16))
     pwd = '%s\t%s\n%s' % (servertime, nonce, pwd)
     pwd = (self.dec2hex(
         transform.bytes2int(rsa.encrypt(pwd.encode('utf-8'), pub_key))))
     return pwd
Exemple #44
0
def decrypt(crypto, priv_key):
    blocksize = common.byte_size(priv_key.n)
    encrypted = transform.bytes2int(crypto)
    decrypted = core.decrypt_int(encrypted, priv_key.d, priv_key.n)
    cleartext = transform.int2bytes(decrypted, blocksize)
    if cleartext[0:2] != b('\x00\x02'):
        raise DecryptionError('Decryption failed')
    try:
        sep_idx = cleartext.index(b('\x00'), 2)
    except ValueError:
        raise DecryptionError('Decryption failed')

    return cleartext[sep_idx + 1:]
Exemple #45
0
def verify(message, signature, pub_key):
    blocksize = common.byte_size(pub_key.n)
    encrypted = transform.bytes2int(signature)
    decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n)
    clearsig = transform.int2bytes(decrypted, blocksize)
    if clearsig[0:2] != b('\x00\x01'):
        raise VerificationError('Verification failed')
    try:
        sep_idx = clearsig.index(b('\x00'), 2)
    except ValueError:
        raise VerificationError('Verification failed')

    method_name, signature_hash = _find_method_hash(clearsig[sep_idx + 1:])
    message_hash = _hash(message, method_name)
    if message_hash != signature_hash:
        raise VerificationError('Verification failed')
Exemple #46
0
def find_signature_hash(signature, pub_key):
    """Returns the hash name detected from the signature.

    If you also want to verify the message, use :py:func:`rsa.verify()` instead.
    It also returns the name of the used hash.

    :param signature: the signature block, as created with :py:func:`rsa.sign`.
    :param pub_key: the :py:class:`rsa.PublicKey` of the person signing the message.
    :returns: the name of the used hash.
    """

    keylength = common.byte_size(pub_key.n)
    encrypted = transform.bytes2int(signature)
    decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n)
    clearsig = transform.int2bytes(decrypted, keylength)

    return _find_method_hash(clearsig)
Exemple #47
0
def verify(message, signature, pub_key):
    '''Verifies that the signature matches the message.
    
    The hash method is detected automatically from the signature.
    
    :param message: the signed message. Can be an 8-bit string or a file-like
        object. If ``message`` has a ``read()`` method, it is assumed to be a
        file-like object.
    :param signature: the signature block, as created with :py:func:`rsa.sign`.
    :param pub_key: the :py:class:`rsa.PublicKey` of the person signing the message.
    :raise VerificationError: when the signature doesn't match the message.

    .. warning::

        Never display the stack trace of a
        :py:class:`rsa.pkcs1.VerificationError` exception. It shows where in
        the code the exception occurred, and thus leaks information about the
        key. It's only a tiny bit of information, but every bit makes cracking
        the keys easier.

    '''
    
    blocksize = common.byte_size(pub_key.n)
    encrypted = transform.bytes2int(signature)
    decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n)
    clearsig = transform.int2bytes(decrypted, blocksize)

    # If we can't find the signature  marker, verification failed.
    if clearsig[0:2] != b('\x00\x01'):
        raise VerificationError('Verification failed')
    
    # Find the 00 separator between the padding and the payload
    try:
        sep_idx = clearsig.index(b('\x00'), 2)
    except ValueError:
        raise VerificationError('Verification failed')
    
    # Get the hash and the hash method
    (method_name, signature_hash) = _find_method_hash(clearsig[sep_idx+1:])
    message_hash = _hash(message, method_name)

    # Compare the real hash to the hash in the signature
    if message_hash != signature_hash:
        raise VerificationError('Verification failed')

    return True
Exemple #48
0
def decrypt(crypto, priv_key):
    r'''Decrypts the given message using PKCS1 v1.5
    
    The decryption is considered 'failed' when the resulting cleartext doesn't
    start with the bytes 00 02, or when the 00 byte between the padding and
    the message cannot be found.
    
    @param crypto: the crypto text as returned by ``encrypt(message, pub_key)``
    @param priv_key: the private key to decrypt with.
    
    @raise DecryptionError: when the decryption fails. No details are given as
        to why the code thinks the decryption fails, as this would leak
        information about the private key.

    >>> from rsa import key, common
    >>> (pub_key, priv_key) = key.newkeys(256)

    It works with strings:
    >>> decrypt(encrypt('hello', pub_key), priv_key)
    'hello'
    
    And with binary data:
    >>> decrypt(encrypt('\x00\x00\x00\x00\x01', pub_key), priv_key)
    '\x00\x00\x00\x00\x01'
    
    '''
    
    blocksize = common.byte_size(priv_key['n']) 
    encrypted = transform.bytes2int(crypto)
    decrypted = core.decrypt_int(encrypted, priv_key['d'], priv_key['n'])
    cleartext = transform.int2bytes(decrypted, blocksize)

    # If we can't find the cleartext marker, decryption failed.
    if cleartext[0:2] != '\x00\x02':
        raise DecryptionError('Decryption failed')
    
    # Find the 00 separator between the padding and the message
    try:
        sep_idx = cleartext.index('\x00', 2)
    except ValueError:
        raise DecryptionError('Decryption failed')
    
    return cleartext[sep_idx+1:]
Exemple #49
0
def sign(message, priv_key, hash):
    '''Signs the message with the private key.

    Hashes the message, then signs the hash with the given key. This is known
    as a "detached signature", because the message itself isn't altered.
    
    :param message: the message to sign. Can be an 8-bit string or a file-like
        object. If ``message`` has a ``read()`` method, it is assumed to be a
        file-like object.
    :param priv_key: the :py:class:`rsa.PrivateKey` to sign with
    :param hash: the hash method used on the message. Use 'MD5', 'SHA-1',
        'SHA-256', 'SHA-384' or 'SHA-512'.
    :return: a message signature block.
    :raise OverflowError: if the private key is too small to contain the
        requested hash.

    '''

    # Get the ASN1 code for this hash method
    if hash not in HASH_ASN1:
        raise ValueError('Invalid hash method: %s' % hash)
    asn1code = HASH_ASN1[hash]
    
    # Calculate the hash
    hash = _hash(message, hash)

    # Encrypt the hash with the private key
    cleartext = asn1code + hash
    keylength = common.byte_size(priv_key.n)
    padded = _pad_for_signing(cleartext, keylength)
    
    payload = transform.bytes2int(padded)
    encrypted = core.encrypt_int(payload, priv_key.d, priv_key.n)
    block = transform.int2bytes(encrypted, keylength)
    
    return block
Exemple #50
0
def sign(message, priv_key, hash):
    '''Signs the message with the private key.

    Hashes the message, then signs the hash with the given key. This is known
    as a "detached signature", because the message itself isn't signed.
    
    @param message: the message to sign
    @param priv_key: the private key to sign with
    @param hash: the hash method used on the message. Use 'MD5', 'SHA-1',
        'SHA-256', 'SHA-384' or 'SHA-512'.
    
    @return: a message signature block.
    
    @raise OverflowError: if the private key is too small to contain the
        requested hash.

    '''

    # Get the ASN1 code for this hash method
    if hash not in HASH_ASN1:
        raise ValueError('Invalid hash method: %s' % hash)
    asn1code = HASH_ASN1[hash]
    
    # Calculate the hash
    hash = _hash(message, hash)

    # Encrypt the hash with the private key
    cleartext = asn1code + hash
    keylength = common.byte_size(priv_key['n'])
    padded = _pad_for_signing(cleartext, keylength)
    
    payload = transform.bytes2int(padded)
    encrypted = core.encrypt_int(payload, priv_key['d'], priv_key['n'])
    block = transform.int2bytes(encrypted, keylength)
    
    return block
Exemple #51
0
 def encode_password(password, servertime, nonce, pubkey):
     public_key = rsa.PublicKey(int(pubkey, 16), int('10001', 16))
     data = '%s\t%s\n%s' % (servertime, nonce, password)
     encoded = transform.bytes2int(rsa.encrypt(bytes(data, 'utf-8'), public_key))
     return hex(encoded).split('x')[1]
Exemple #52
0
 def test_codec_identity(self):
     self.assertEqual(bytes2int(int2bytes(123456789, 128)), 123456789)
     self.assertEqual(bytes2int(_int2bytes(123456789, 128)), 123456789)
def read_random_int(nbits):
    randomdata = read_random_bits(nbits)
    value = transform.bytes2int(randomdata)
    value |= 1 << nbits - 1
    return value
Exemple #54
0
def decrypt(crypto, priv_key):
    r'''Decrypts the given message using PKCS#1 v1.5
    
    The decryption is considered 'failed' when the resulting cleartext doesn't
    start with the bytes 00 02, or when the 00 byte between the padding and
    the message cannot be found.
    
    :param crypto: the crypto text as returned by :py:func:`rsa.encrypt`
    :param priv_key: the :py:class:`rsa.PrivateKey` to decrypt with.
    :raise DecryptionError: when the decryption fails. No details are given as
        to why the code thinks the decryption fails, as this would leak
        information about the private key.


    >>> import rsa
    >>> (pub_key, priv_key) = rsa.newkeys(256)

    It works with strings:

    >>> crypto = encrypt('hello', pub_key)
    >>> decrypt(crypto, priv_key)
    'hello'
    
    And with binary data:

    >>> crypto = encrypt('\x00\x00\x00\x00\x01', pub_key)
    >>> decrypt(crypto, priv_key)
    '\x00\x00\x00\x00\x01'

    Altering the encrypted information will *likely* cause a
    :py:class:`rsa.pkcs1.DecryptionError`. If you want to be *sure*, use
    :py:func:`rsa.sign`.


    .. warning::

        Never display the stack trace of a
        :py:class:`rsa.pkcs1.DecryptionError` exception. It shows where in the
        code the exception occurred, and thus leaks information about the key.
        It's only a tiny bit of information, but every bit makes cracking the
        keys easier.

    >>> crypto = encrypt('hello', pub_key)
    >>> crypto = crypto[0:5] + 'X' + crypto[6:] # change a byte
    >>> decrypt(crypto, priv_key)
    Traceback (most recent call last):
    ...
    DecryptionError: Decryption failed

    '''
    
    blocksize = common.byte_size(priv_key.n)
    encrypted = transform.bytes2int(crypto)
    decrypted = core.decrypt_int(encrypted, priv_key.d, priv_key.n)
    cleartext = transform.int2bytes(decrypted, blocksize)

    # If we can't find the cleartext marker, decryption failed.
    if cleartext[0:2] != b('\x00\x02'):
        raise DecryptionError('Decryption failed')
    
    # Find the 00 separator between the padding and the message
    try:
        sep_idx = cleartext.index(b('\x00'), 2)
    except ValueError:
        raise DecryptionError('Decryption failed')
    
    return cleartext[sep_idx+1:]