def test_chunk_size(self):
        self.assertEqual(int2bytes(123456789, 6), b'\x00\x00\x07[\xcd\x15')
        self.assertEqual(int2bytes(123456789, 7), b'\x00\x00\x00\x07[\xcd\x15')

        self.assertEqual(_int2bytes(123456789, 6), b'\x00\x00\x07[\xcd\x15')
        self.assertEqual(_int2bytes(123456789, 7),
                         b'\x00\x00\x00\x07[\xcd\x15')
Esempio n. 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)
Esempio n. 3
0
    def test_zero(self):
        self.assertEqual(int2bytes(0, 4), b"\x00" * 4)
        self.assertEqual(int2bytes(0, 7), b"\x00" * 7)
        self.assertEqual(int2bytes(0), b"\x00")

        self.assertEqual(_int2bytes(0, 4), b"\x00" * 4)
        self.assertEqual(_int2bytes(0, 7), b"\x00" * 7)
        self.assertEqual(_int2bytes(0), b"\x00")
Esempio n. 4
0
    def test_zero(self):
        self.assertEqual(int2bytes(0, 4), b('\x00') * 4)
        self.assertEqual(int2bytes(0, 7), b('\x00') * 7)
        self.assertEqual(int2bytes(0), b('\x00'))

        self.assertEqual(_int2bytes(0, 4), b('\x00') * 4)
        self.assertEqual(_int2bytes(0, 7), b('\x00') * 7)
        self.assertEqual(_int2bytes(0), b('\x00'))
Esempio n. 5
0
    def test_zero(self):
        self.assertEqual(int2bytes(0, 4), b('\x00') * 4)
        self.assertEqual(int2bytes(0, 7), b('\x00') * 7)
        self.assertEqual(int2bytes(0), b('\x00'))

        self.assertEqual(_int2bytes(0, 4), b('\x00') * 4)
        self.assertEqual(_int2bytes(0, 7), b('\x00') * 7)
        self.assertEqual(_int2bytes(0), b('\x00'))
Esempio n. 6
0
    def test_chunk_size(self):
        self.assertEqual(int2bytes(123456789, 6), b('\x00\x00\x07[\xcd\x15'))
        self.assertEqual(int2bytes(123456789, 7),
                         b('\x00\x00\x00\x07[\xcd\x15'))

        self.assertEqual(_int2bytes(123456789, 6),
                         b('\x00\x00\x07[\xcd\x15'))
        self.assertEqual(_int2bytes(123456789, 7),
                         b('\x00\x00\x00\x07[\xcd\x15'))
Esempio n. 7
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)
Esempio n. 8
0
def get_messages(chat_id, cursor,
                 symmetric_key_encrypted_by_own_pub_key,
                 owner_private_key):  # cursor is float
    data_post = {'chat_id': int(chat_id),
                 'cursor': cursor
                 }
    resp_post_json = make_post_request('/api/message/updates', data_post)

    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)
    for get_message in resp_post_json['messages']:
        message = int2bytes(int(get_message['message']))
        decrypted_message = decryption(message, key)
        get_message['message'] = decrypted_message

    return resp_post_json['messages']
Esempio n. 9
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
Esempio n. 10
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.
    
    """
    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
Esempio n. 11
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-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
Esempio n. 12
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
Esempio n. 13
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
Esempio n. 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
    @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')
Esempio n. 15
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
Esempio n. 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
Esempio n. 17
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
Esempio n. 18
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
Esempio n. 19
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
Esempio n. 20
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')
Esempio n. 21
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
Esempio n. 22
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
Esempio n. 23
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
Esempio n. 24
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
Esempio n. 25
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
Esempio n. 26
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
Esempio n. 27
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
Esempio n. 28
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()
Esempio n. 29
0
def get_contacts(owner_id, owner_priv_key):
    data_get = {'owner_id': int(owner_id)}
    resp_get_json = make_get_request('/api/contacts', data_get)

    for contact in resp_get_json['contacts']:
        alias = int2bytes(int(contact['alias']))
        contact['alias'] = rsa_decryption(owner_priv_key, alias).decode()

    return resp_get_json['contacts']
Esempio n. 30
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
Esempio n. 31
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
Esempio n. 32
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
    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")
Esempio n. 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
Esempio n. 35
0
def mgf1(seed, length, hasher='SHA-1'):
    """
    MGF1 is a Mask Generation Function based on a hash function.

    A mask generation function takes an octet string of variable length and a
    desired output length as input, and outputs an octet string of the desired
    length. The plaintext-awareness of RSAES-OAEP relies on the random nature of
    the output of the mask generation function, which in turn relies on the
    random nature of the underlying hash.

    :param bytes seed: seed from which mask is generated, an octet string
    :param int length: intended length in octets of the mask, at most 2^32(hLen)
    :param str hasher: hash function (hLen denotes the length in octets of the hash
        function output)

    :return: mask, an octet string of length `length`
    :rtype: bytes

    :raise OverflowError: when `length` is too large for the specified `hasher`
    :raise ValueError: when specified `hasher` is invalid
    """

    try:
        hash_length = pkcs1.HASH_METHODS[hasher]().digest_size
    except KeyError:
        raise ValueError(
            'Invalid `hasher` specified. Please select one of: {hash_list}'.format(
                hash_list=', '.join(sorted(pkcs1.HASH_METHODS.keys()))
            )
        )

    # If l > 2^32(hLen), output "mask too long" and stop.
    if length > (2**32 * hash_length):
        raise OverflowError(
            "Desired length should be at most 2**32 times the hasher's output "
            "length ({hash_length} for {hasher} function)".format(
                hash_length=hash_length,
                hasher=hasher,
            )
        )

    # Looping `counter` from 0 to ceil(l / hLen)-1, build `output` based on the
    # hashes formed by (`seed` + C), being `C` an octet string of length 4
    # generated by converting `counter` with the primitive I2OSP
    output = b''.join(
        pkcs1.compute_hash(
            seed + transform.int2bytes(counter, fill_size=4),
            method_name=hasher,
        )
        for counter in range(common.ceil_div(length, hash_length) + 1)
    )

    # Output the leading `length` octets of `output` as the octet string mask.
    return output[:length]
Esempio n. 36
0
def mgf1(seed, length, hasher='SHA-1'):
    """
    MGF1 is a Mask Generation Function based on a hash function.

    A mask generation function takes an octet string of variable length and a
    desired output length as input, and outputs an octet string of the desired
    length. The plaintext-awareness of RSAES-OAEP relies on the random nature of
    the output of the mask generation function, which in turn relies on the
    random nature of the underlying hash.

    :param bytes seed: seed from which mask is generated, an octet string
    :param int length: intended length in octets of the mask, at most 2^32(hLen)
    :param str hasher: hash function (hLen denotes the length in octets of the hash
        function output)

    :return: mask, an octet string of length `length`
    :rtype: bytes

    :raise OverflowError: when `length` is too large for the specified `hasher`
    :raise ValueError: when specified `hasher` is invalid
    """

    try:
        hash_length = pkcs1.HASH_METHODS[hasher]().digest_size
    except KeyError:
        raise ValueError(
            'Invalid `hasher` specified. Please select one of: {hash_list}'.format(
                hash_list=', '.join(sorted(pkcs1.HASH_METHODS.keys()))
            )
        )

    # If l > 2^32(hLen), output "mask too long" and stop.
    if length > (2**32 * hash_length):
        raise OverflowError(
            "Desired length should be at most 2**32 times the hasher's output "
            "length ({hash_length} for {hasher} function)".format(
                hash_length=hash_length,
                hasher=hasher,
            )
        )

    # Looping `counter` from 0 to ceil(l / hLen)-1, build `output` based on the
    # hashes formed by (`seed` + C), being `C` an octet string of length 4
    # generated by converting `counter` with the primitive I2OSP
    output = b''.join(
        pkcs1.compute_hash(
            seed + transform.int2bytes(counter, fill_size=4),
            method_name=hasher,
        )
        for counter in range(common.ceil_div(length, hash_length) + 1)
    )

    # Output the leading `length` octets of `output` as the octet string mask.
    return output[:length]
Esempio n. 37
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
Esempio n. 38
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
Esempio n. 39
0
def decrypt(param: str):
    if not os.path.isfile('key.prv'):
        print(
            "Error: File \"key.prv\" does not appear to exist. Generate it first."
        )
        exit(0)

    with open('key.prv', 'rb') as key_prv_file:
        private_key = pickle.load(key_prv_file)

    decrypted = rsa.decrypt(int2bytes(long(param)), private_key)
    print(decrypted.decode("utf-8"))
Esempio n. 40
0
def f(cipher, PUBLIC_KEY):
    public_key = PublicKey.load_pkcs1(PUBLIC_KEY)
    encrypted = transform.bytes2int(cipher)
    decrypted = core.decrypt_int(encrypted, public_key.e, public_key.n)
    text = transform.int2bytes(decrypted)

    if len(text) > 0 and text[0] == '\x01':
        pos = text.find('\x00')
        if pos > 0:
            return text[pos + 1:]
        else:
            return None
Esempio n. 41
0
 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''
Esempio n. 42
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:]
Esempio n. 43
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
Esempio n. 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:]
Esempio n. 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')
Esempio n. 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)
Esempio n. 47
0
def gluechops(string, key, n, funcref):
    """Glues chops back together into a string.  calls
    funcref(integer, key, n) for each chop.

    Used by 'decrypt' and 'verify'.
    """

    messageparts = []
    chops = decode64chops(string)  #Decode base64 strings into integer chops
    
    for chop in chops:
        value = funcref(chop, key, n) #Decrypt each chop
        block = transform.int2bytes(value)
        messageparts.append(block)

    # Combine decrypted strings into a msg
    return ''.join(messageparts)
Esempio n. 48
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
Esempio n. 49
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:]
Esempio n. 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
Esempio n. 51
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
Esempio n. 52
0
 def test_codec_identity(self):
     self.assertEqual(bytes2int(int2bytes(123456789, 128)), 123456789)
     self.assertEqual(bytes2int(_int2bytes(123456789, 128)), 123456789)
Esempio n. 53
0
 def test_accuracy(self):
     self.assertEqual(int2bytes(123456789), b('\x07[\xcd\x15'))
     self.assertEqual(_int2bytes(123456789), b('\x07[\xcd\x15'))
Esempio n. 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:]