def test_rsa(empoent, module, passwd):
    key_length = common.byte_size(int(module, 16))
    print(key_length)
    pubkey, privkey = rsa.newkeys(512)
    key_length1 = common.byte_size(pubkey.n)
    # print(pubkey.n)
    # print(type(pubkey.n))
    # print(key_length1)
    reverseSize = 11
    maxlength = key_length - reverseSize
    # originempoent = "10001"
    # originmodule = "c5539e0f93bfc2f0f070353b473c8417c8593089d7b3c475f85760401c3f4aaf0e90206715d1d9fa7a51ab423eedd782b2bda94d9bf372587d01a23d88aab6ef114ba58256858c80f50e6a1f10f91b7cafc4a3e910b5dfec1fdf2f743e6575d97dc712300a83c19851c3f70339048793ba8af077f732bf14191766e6247f495f"
    myempoent = int(empoent, 16)
    mymodule = int(module, 16)
    mypubkey = rsa.PublicKey(mymodule, myempoent)
    testRSA = encryptRsa(passwd, myempoent, mymodule)
    # print("^^^^^^^^^^")
    # print(testRSA)
    # mypubkey = rsa.PublicKey(module, empoent)
    # print("--------------")
    # print(mypubkey)
    # myprikey = rsa.PrivateKey(myempoent,mymodule)
    # mypubkey1 = rsa.PublicKey(originmodule,originempoent)
    message = passwd.encode('utf8')
    # message = "Hello,Bob!".encode('utf8')
    cryinfo = rsa.encrypt(message, pubkey)
    cryinfo1 = rsa.encrypt(message, mypubkey)
    print("**********")
    # print(cryinfo)
    print(cryinfo1.hex())
    myinfo = rsa.decrypt(cryinfo, privkey)
    print(myinfo)
    return testRSA
Example #2
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
Example #3
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
Example #4
0
def _int2bytes(number, block_size=None):
    if not is_integer(number):
        raise TypeError("You must pass an integer for 'number', not %s" %
                        number.__class__)
    if number < 0:
        raise ValueError('Negative numbers cannot be used: %i' % number)
    if number == 0:
        needed_bytes = 1
        raw_bytes = [ZERO_BYTE]
    else:
        needed_bytes = common.byte_size(number)
        raw_bytes = []
    if block_size and block_size > 0:
        if needed_bytes > block_size:
            raise OverflowError(
                'Needed %i bytes for number, but block size is %i' %
                (needed_bytes, block_size))
    while number > 0:
        raw_bytes.insert(0, byte(number & 255))
        number >>= 8

    if block_size and block_size > 0:
        padding = (block_size - needed_bytes) * ZERO_BYTE
    else:
        padding = EMPTY_BYTE
    return padding + EMPTY_BYTE.join(raw_bytes)
Example #5
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
Example #6
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')
Example #7
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
Example #8
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
Example #9
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
Example #10
0
def _int2bytes(number, block_size=None):
    r"""Converts a number to a string of bytes.

    Usage::

        >>> _int2bytes(123456789)
        '\x07[\xcd\x15'
        >>> bytes2int(_int2bytes(123456789))
        123456789

        >>> _int2bytes(123456789, 6)
        '\x00\x00\x07[\xcd\x15'
        >>> bytes2int(_int2bytes(123456789, 128))
        123456789

        >>> _int2bytes(123456789, 3)
        Traceback (most recent call last):
        ...
        OverflowError: Needed 4 bytes for number, but block size is 3

    @param number: the number to convert
    @param block_size: the number of bytes to output. If the number encoded to
        bytes is less than this, the block will be zero-padded. When not given,
        the returned block is not padded.

    @throws OverflowError when block_size is given and the number takes up more
        bytes than fit into the block.
    """
    # Type checking
    if not is_integer(number):
        raise TypeError("You must pass an integer for 'number', not %s" % number.__class__)

    if number < 0:
        raise ValueError("Negative numbers cannot be used: %i" % number)

    # Do some bounds checking
    if number == 0:
        needed_bytes = 1
        raw_bytes = [ZERO_BYTE]
    else:
        needed_bytes = common.byte_size(number)
        raw_bytes = []

    # You cannot compare None > 0 in Python 3x. It will fail with a TypeError.
    if block_size and block_size > 0:
        if needed_bytes > block_size:
            raise OverflowError("Needed %i bytes for number, but block size " "is %i" % (needed_bytes, block_size))

    # Convert the number to bytes.
    while number > 0:
        raw_bytes.insert(0, byte(number & 0xFF))
        number >>= 8

    # Pad with zeroes to fill the block
    if block_size and block_size > 0:
        padding = (block_size - needed_bytes) * ZERO_BYTE
    else:
        padding = EMPTY_BYTE

    return padding + EMPTY_BYTE.join(raw_bytes)
Example #11
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')
Example #12
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
Example #13
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
Example #14
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
Example #15
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
Example #16
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
Example #17
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
Example #18
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
Example #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
Example #20
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
Example #21
0
def _int2bytes(number, block_size=None):
    r"""Converts a number to a string of bytes.
    Usage::
        >>> _int2bytes(123456789)
        b'\x07[\xcd\x15'
        >>> bytes2int(_int2bytes(123456789))
        123456789
        >>> _int2bytes(123456789, 6)
        b'\x00\x00\x07[\xcd\x15'
        >>> bytes2int(_int2bytes(123456789, 128))
        123456789
        >>> _int2bytes(123456789, 3)
        Traceback (most recent call last):
        ...
        OverflowError: Needed 4 bytes for number, but block size is 3
    @param number: the number to convert
    @param block_size: the number of bytes to output. If the number encoded to
        bytes is less than this, the block will be zero-padded. When not given,
        the returned block is not padded.
    @throws OverflowError when block_size is given and the number takes up more
        bytes than fit into the block.
    """

    # Type checking
    if not is_integer(number):
        raise TypeError("You must pass an integer for 'number', not %s" %
                        number.__class__)

    if number < 0:
        raise ValueError('Negative numbers cannot be used: %i' % number)

    # Do some bounds checking
    if number == 0:
        needed_bytes = 1
        raw_bytes = [b'\x00']
    else:
        needed_bytes = common.byte_size(number)
        raw_bytes = []

    # You cannot compare None > 0 in Python 3x. It will fail with a TypeError.
    if block_size and block_size > 0:
        if needed_bytes > block_size:
            raise OverflowError('Needed %i bytes for number, but block size '
                                'is %i' % (needed_bytes, block_size))

    # Convert the number to bytes.
    while number > 0:
        raw_bytes.insert(0, byte(number & 0xFF))
        number >>= 8

    # Pad with zeroes to fill the block
    if block_size and block_size > 0:
        padding = (block_size - needed_bytes) * b'\x00'
    else:
        padding = b''

    return padding + b''.join(raw_bytes)
Example #22
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
Example #23
0
def int2bytes(number, block_size=None):
    r'''Converts a number to a string of bytes.

    @param number: the number to convert
    @param block_size: the number of bytes to output. If the number encoded to
        bytes is less than this, the block will be zero-padded. When not given,
        the returned block is not padded.

    @throws OverflowError when block_size is given and the number takes up more
        bytes than fit into the block.


    >>> int2bytes(123456789)
    '\x07[\xcd\x15'
    >>> bytes2int(int2bytes(123456789))
    123456789

    >>> int2bytes(123456789, 6)
    '\x00\x00\x07[\xcd\x15'
    >>> bytes2int(int2bytes(123456789, 128))
    123456789

    >>> int2bytes(123456789, 3)
    Traceback (most recent call last):
    ...
    OverflowError: Needed 4 bytes for number, but block size is 3

    '''

    # Type checking
    if type(number) not in (types.LongType, types.IntType):
        raise TypeError("You must pass an integer for 'number', not %s" %
            number.__class__)

    if number < 0:
        raise ValueError('Negative numbers cannot be used: %i' % number)

    # Do some bounds checking
    if block_size is not None:
        needed_bytes = common.byte_size(number)
        if needed_bytes > block_size:
            raise OverflowError('Needed %i bytes for number, but block size '
                'is %i' % (needed_bytes, block_size))

    # Convert the number to bytes.
    bytes = []
    while number > 0:
        bytes.insert(0, chr(number & 0xFF))
        number >>= 8

    # Pad with zeroes to fill the block
    if block_size is not None:
        padding = (block_size - needed_bytes) * '\x00'
    else:
        padding = ''

    return padding + ''.join(bytes)
Example #24
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")
Example #26
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
Example #27
0
    def get_max_length(self, rsa_key, encrypt=True):
        '''如果加密内容过长,就分段加密,换算每一段的长度.
			:param rsa_key: 密钥
			:param encrypt: 是否加密
		'''
        blocksize = common.byte_size(rsa_key.n)
        reserve_size = 11  #预留位
        if not encrypt:
            reserve_size = 0  #解密不需要预留位
        maxlength = blocksize - reserve_size
        return maxlength
Example #28
0
 def get_max_length(self, rsa_key, encrypt=True):
     """加密内容过长时 需要分段加密 换算每一段的长度.
         :param rsa_key: 钥匙.
         :param encrypt: 是否是加密.
     """
     blocksize = common.byte_size(rsa_key.n)
     reserve_size = 11  # 预留位为11
     if not encrypt:  # 解密时不需要考虑预留位
         reserve_size = 0
     maxlength = blocksize - reserve_size
     return maxlength
Example #29
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 _int2bytes(number, block_size=None):
    r"""Converts a number to a string of bytes.
    
    Usage::
    
        >>> _int2bytes(123456789)
        '\x07[\xcd\x15'
        >>> bytes2int(_int2bytes(123456789))
        123456789
    
        >>> _int2bytes(123456789, 6)
        '\x00\x00\x07[\xcd\x15'
        >>> bytes2int(_int2bytes(123456789, 128))
        123456789
    
        >>> _int2bytes(123456789, 3)
        Traceback (most recent call last):
        ...
        OverflowError: Needed 4 bytes for number, but block size is 3
    
    @param number: the number to convert
    @param block_size: the number of bytes to output. If the number encoded to
        bytes is less than this, the block will be zero-padded. When not given,
        the returned block is not padded.
    
    @throws OverflowError when block_size is given and the number takes up more
        bytes than fit into the block.
    """
    if not is_integer(number):
        raise TypeError("You must pass an integer for 'number', not %s" %
                        number.__class__)
    if number < 0:
        raise ValueError('Negative numbers cannot be used: %i' % number)
    if number == 0:
        needed_bytes = 1
        raw_bytes = [ZERO_BYTE]
    else:
        needed_bytes = common.byte_size(number)
        raw_bytes = []
    if block_size and block_size > 0:
        if needed_bytes > block_size:
            raise OverflowError(
                'Needed %i bytes for number, but block size is %i' %
                (needed_bytes, block_size))
    while number > 0:
        raw_bytes.insert(0, byte(number & 255))
        number >>= 8

    if block_size and block_size > 0:
        padding = (block_size - needed_bytes) * ZERO_BYTE
    else:
        padding = EMPTY_BYTE
    return padding + EMPTY_BYTE.join(raw_bytes)
Example #31
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
Example #32
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
Example #33
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:]
Example #34
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:]
Example #35
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:]
Example #36
0
def encrypt(message: str):
    if not os.path.isfile('key.pub'):
        print(
            "Error: File \"key.pub\" does not appear to exist. Generate it first."
        )
        exit(0)

    with open('key.pub', 'rb') as key_pub_file:
        key_pub = pickle.load(key_pub_file)

    max_block_size = common.byte_size(key_pub.n) - 11
    for i in range(0, len(message), max_block_size):
        cipher = rsa.encrypt(message[i:max_block_size + i].encode(), key_pub)
        int_form = int.from_bytes(cipher, byteorder='big')
        print(int_form)
Example #37
0
def decryptSignature(signature, pub_key):
    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)
    if clearsig[0:2] != b'\x00\x02':
        raise DecryptionError('Decryption failed')

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

    return clearsig[sep_idx + 1:]
Example #38
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)
Example #39
0
def verify(message, signature, pub_key, hasher='SHA-1', salt_len=None):
    # type: (bytes, bytes, PublicKey, str, int) -> bool
    # Determine the size of the hash output (hLen)
    try:
        h_len = 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()))))
    # Determine the size of the public key in bytes (k)
    k = common.byte_size(pub_key.n)
    mod_bits = k * 8 - 1
    em_len = math.ceil(mod_bits / 8)
    s = transform.bytes2int(signature)
    m = core.decrypt_int(
        s, pub_key.e,
        pub_key.n)  # Use encrypt_int because of the additional range-checking
    em = transform.int2bytes(m, em_len)
    # EMSA-PSS-VERIFY (m, em, mod_bits)
    if len(message) > 2**61 - 1:
        raise VerificationError('Incorrect signature')
    m_hash = pkcs1.compute_hash(message, hasher)
    s_len = salt_len if salt_len is not None else h_len
    if em_len < h_len + s_len + 2:
        raise VerificationError('Incorrect signature')
    if em[-1] != 0xbc:
        raise VerificationError('Incorrect signature')

    masked_db, h = em[:em_len - h_len - 1], em[em_len - h_len - 1:-1]

    for i in range(8 * em_len - mod_bits):
        if masked_db[0] & (1 << (7 - i)) != 0:
            raise VerificationError('Incorrect signature')
    db_mask = mgf1(h, em_len - h_len - 1, hasher)
    db = bytearray(common.xor(masked_db, db_mask))
    a = 0xff
    for _ in range(8 * em_len - mod_bits):
        a = a >> 1
    db[0] &= a
    for i in range(em_len - h_len - s_len - 2):
        if db[i] != 0:
            raise VerificationError('Incorrect signature')
    if db[em_len - h_len - s_len - 2] != 0x01:
        raise VerificationError('Incorrect signature')
    salt = db[-s_len:] if s_len > 0 else b''
    m2 = b''.join((b'\x00' * 8, m_hash, salt))
    h2 = pkcs1.compute_hash(m2, hasher)
    return h == h2
Example #40
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')
Example #41
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')
Example #42
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
Example #43
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)
Example #44
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:]
Example #45
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
Example #46
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
Example #47
0
 def test_zero(self):
     self.assertEqual(byte_size(0), 1)
Example #48
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:]
Example #49
0
 def test_values(self):
     self.assertEqual(byte_size(1 << 1023), 128)
     self.assertEqual(byte_size((1 << 1024) - 1), 128)
     self.assertEqual(byte_size(1 << 1024), 129)
     self.assertEqual(byte_size(255), 1)
     self.assertEqual(byte_size(256), 2)
     self.assertEqual(byte_size(0xffff), 2)
     self.assertEqual(byte_size(0xffffff), 3)
     self.assertEqual(byte_size(0xffffffff), 4)
     self.assertEqual(byte_size(0xffffffffff), 5)
     self.assertEqual(byte_size(0xffffffffffff), 6)
     self.assertEqual(byte_size(0xffffffffffffff), 7)
     self.assertEqual(byte_size(0xffffffffffffffff), 8)
	epochs = int(sys.argv[1])
else:
	epochs = 500
	
with open('public.pem', mode='rb') as publicfile:
	keydata = publicfile.read()
pubkey = rsa.PublicKey.load_pkcs1(keydata)

with open('private.pem', mode='rb') as privatefile:
	keydata = privatefile.read()
privkey = rsa.PrivateKey.load_pkcs1(keydata)

n = pubkey.n
p, q = privkey.p, privkey.q

key_bytes = common.byte_size(pubkey.n) * BITS

nb = BitArray(uint=n, length=key_bytes).bin
pb = BitArray(uint=p, length=key_bytes).bin
qb = BitArray(uint=q, length=key_bytes).bin

inp = np.array(map(int, nb))
tar = np.array(map(int, pb + qb))

num_input_units = len(inp)
num_output_units = len(tar)
minmax = [[0, 1]] * num_input_units
# One of the thumb rule to set nh = 2/3 * (ni + no)
size = [(num_input_units + num_output_units) * 3 / 5, num_output_units]

inp = inp.reshape(1, num_input_units)