Example #1
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 #2
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 #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 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 #5
0
def encrypt_with_private_key(message, priv_key):
    """Encrypts the given message using PKCS#1 v1.5's private key

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

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

    """

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

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

    return block
Example #6
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 #7
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 #8
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
Example #9
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 #10
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 #11
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 #12
0
    def sign(self, string_to_sign):
        """Sign the data in a emulation of the OpenSSL private_encrypt method

        :param str string_to_sign: The string to Sign using the RSA private_encrypt method
        :rtype: str
        """
        string_to_sign = make_bytes(string_to_sign)
        hashed = sha512(string_to_sign).hexdigest().encode('US-ASCII')
        keylength = common.byte_size(self.pk.n)
        padded = self.pad_for_signing(hashed, keylength)
        padded = make_bytes(padded)
        payload = transform.bytes2int(padded)
        encrypted = core.encrypt_int(payload, self.pk.d, self.pk.n)
        signature = transform.int2bytes(encrypted, keylength)
        signature = base64.b64encode(signature).decode('US-ASCII').replace('\n', '')
        return signature
    def __rsa_encrypt(self, message, key):
        """加密方法"""
        # 判断密钥类型
        if isinstance(key, PublicKey):
            a = key.e
            b = key.n
        elif isinstance(key, PrivateKey):
            a = key.d
            b = key.n
        else:
            raise TypeError("'key' must be PublicKey or PrivateKey")

        key_length = common.byte_size(b)
        # 得到信息字节
        message_bytes = bytes(message, encoding='utf-8')
        padded = self.__pad_for_encrypt(message_bytes, key_length)
        num = transform.bytes2int(padded)
        decryto = core.encrypt_int(num, a, b)
        out = transform.int2bytes(decryto)
        return out
Example #14
0
def sign(message, priv_key, hasher='SHA-1', salt_len=None):
    # type: (bytes, PrivateKey, str, int) -> bytes
    # 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(priv_key.n)
    mod_bits = k * 8 - 1
    em_len = math.ceil(mod_bits / 8)
    if len(message) > 2**61 - 1:
        raise OverflowError('message too long')
    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 SigningError('Encoding error')
    salt = b'' if s_len == 0 else randnum.read_random_bits(s_len * 8)
    m2 = b''.join((b'\x00' * 8, m_hash, salt))
    h = pkcs1.compute_hash(m2, hasher)
    ps = b'\x00' * (em_len - s_len - h_len - 2)
    db = b'\x01'.join((ps, salt))
    db_mask = mgf1(h, em_len - h_len - 1, hasher)
    masked_db = bytearray(common.xor(db, db_mask))

    a = 0xff
    for _ in range(8 * em_len - mod_bits):
        a = a >> 1
    masked_db[0] &= a
    # for i in range(8*em_len - mod_bits + 1):
    #     masked_db[0] &= ~(1 << (7-i))
    em = b''.join((masked_db, h, b'\xbc'))
    m = transform.bytes2int(em)
    # s = priv_key.blinded_encrypt(m)
    s = core.encrypt_int(m, priv_key.d, priv_key.n)
    sig = transform.int2bytes(s, k)
    return sig
 def encrypt_with_pubkey(self, message):
     """
     通过公钥加密信息
     :param message: 被加密的信息
     :return: 已加密的base64编码字符串
     """
     encrypt_result = b''
     max_length = self.get_max_length()
     pubkey = rsa.PublicKey(int(self.module, 16), int(self.empoent, 16))
     # print(pubkey)
     message = self.passwd[::-1]
     randomNo = max_length - len(message) - 3
     randompadding = (b"\x00") * randomNo
     # print(randompadding)
     # print(randomNo)
     if len(message) < max_length:
         message = (b'\x00\x00') + randompadding + (
             b"\x00") + message.encode('utf-8')
         # print(message)
         pass
     else:
         pass
     # print(max_length)
     # print(message)
     # print(pubkey)
     testmessage = rsa.transform.bytes2int(message)
     encrypt_result_test = core.encrypt_int(testmessage, pubkey.e, pubkey.n)
     test_rts = rsa.transform.int2bytes(encrypt_result_test, max_length)
     # print(test_rts.hex())
     # print("^^^^^^^^^^^^^^^^^^^^^^^^^^")
     # while message:
     #     input = message[:max_length]
     #     message = message[max_length:]
     #     print(input)
     #     out = rsa.encrypt(input, pubkey)
     #     encrypt_result += out
     #encrypt_result = base64.b64encode(encrypt_result)
     return test_rts.hex()
Example #16
0
def OAEP_encrypt(message, pub_key, label=b'', hash_method="SHA-1",
                 mgf1_hash_method=None):
    """Encrypts the given message using PKCS#1 v2 RSA-OEAP.

    :param bytes message: the message to encrypt.
    :param rsa.PublicKey pub_key: the public key to encrypt with.
    :param bytes label: optional RSA-OAEP label.
    :param str hash_method: hash function to be used.  'SHA-1' (default),
        'SHA-256', 'SHA-384', and 'SHA-512' can be used.
    """
    # NOTE: Some hash method other than listed in the docstring can be used
    # for hash_method.  But the RFC 8017 recommends only them.
    if mgf1_hash_method is None:
        mgf1_hash_method = hash_method
    keylength = common.byte_size(pub_key.n)

    em = _OAEP_encode(message, keylength, label, hash_method, mgf1_hash_method)

    m = transform.bytes2int(em)
    encrypted = core.encrypt_int(m, pub_key.e, pub_key.n)
    c = transform.int2bytes(encrypted, keylength)

    return c
Example #17
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 #18
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 #19
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 #20
0
def rsa_encrypt_key(data):
    data = transform.bytes2int(data)
    encrypted = core.encrypt_int(data, constants.RSA_E, constants.RSA_N)
    print(constants.RSA_N)
    block = transform.int2bytes(encrypted, 64)
    return block
Example #21
0
 def encrypt(data_bytes, rsa_private_key):
     data_int = transform.bytes2int(data_bytes)
     encrypted_int = core.encrypt_int(data_int, rsa_private_key.e,
                                      rsa_private_key.n)
     block = transform.int2bytes(encrypted_int)
     return block
Example #22
0
def encrypt(message, pub_key, label=b'', hasher='SHA-1', **kwargs):
    # type: (bytes, PublicKey, bytes, str, dict) -> bytes
    """
    Encrypts the given message using OAEP.
    For a complete documentation see https://tools.ietf.org/html/rfc8017#section-7.1.1

    :param message: Message to be encrypted. The length must be smaller than or equal to k - 2hLen - 2.
        Where hLen denotes the length in octets of the hash function output and k denotes the length on octets
        of the RSA modulus n.
    :param pub_key: Recipient's RSA public key
    :param label: Optional label to be associated with the message
    :param hasher: The hash function's name
    :param kwargs: Used internally for testing-purposes
    :return: The ciphertext of length k
    """

    # The following code implements RSAES-OAEP-ENCRYPT (rfc8017 7.1.1). The variable names of the specification are
    # put in parentheses. Also, the corresponding step# from the document is included in the comments.

    # 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 length of the message in bytes (mLen)
    m_len = len(message)

    # Step 1: Length checking:
    # a.)   The label cannot be longer than the maximum input-length of the hash-function
    #       Hardcoded the maximum input-length to 2**61 - 1 (SHA-1)
    if len(label) > 2**61 - 1:
        raise OverflowError('Label too long')

    # Determine the size of the public key in bytes (k)
    k = common.byte_size(pub_key.n)

    # b.)   The message length can be at most k - 2hLen - 2
    if m_len > k - 2 * h_len - 2:
        raise OverflowError('Message too long')

    # Step 2: EME-OAEP encoding
    # a.)   l_hash = Hash(label)
    l_hash = pkcs1.compute_hash(label, hasher)

    # b.)   Generate a padding string (ps)
    ps = b'\x00' * (k - m_len - 2 * h_len - 2)

    # c.)   Construct the data block (db)
    #       db = l_hash || ps || 0x01 || message
    db = b''.join((l_hash, ps, b'\x01', message))

    # d.)   Generate a random hash
    # Used only for testing-purposes. This should NEVER be set in production as it might compromise security!
    if 'test_seed' in kwargs:
        seed = kwargs['test_seed']
    else:
        seed = randnum.read_random_bits(h_len * 8)

    # e-h.) Calculate the masks
    db_mask = mgf1(seed, k - h_len - 1, hasher)
    masked_db = common.xor(db, db_mask)
    seed_mask = mgf1(masked_db, h_len, hasher)
    masked_seed = common.xor(seed, seed_mask)

    # i.)   Construct the encoded message
    #       em = 0x00 || masked_seed || masked_db
    em = b''.join((b'\x00', masked_seed, masked_db))

    # Step 3: RSA encryption
    # a.)   Convert em to an integer
    #       m = OS2IP(em)
    m = transform.bytes2int(em)

    # b.)   Apply the RSAEP encryption primitive
    #       c = RSAEP(pub_key, m)
    c = core.encrypt_int(m, pub_key.e, pub_key.n)

    # c.)   Convert c to bytes (the ciphertext C)
    #       ct = I2OSP(c, k)
    ct = transform.int2bytes(c, k)
    return ct
Example #23
0
if __name__ == '__main__':
    choice = sys.argv[1]
    p = 97
    n = 400
    if choice == 'g':
        public_key, private_key = rsa.newkeys(int(sys.argv[2]))
        with open("private_key", "wb") as f:
            pickle.dump(private_key, f)
        with open("public_key", "wb") as f:
            pickle.dump(public_key, f)
    if choice == 'e':
        with open(sys.argv[2], "rb") as f:
            public_key = pickle.load(f)
        x = random.randint(10000, 20000)
        b = int(sys.argv[3])
        encrypted = core.encrypt_int(x, public_key.e, public_key.n)
        print "encrypt: {0}\nx: {1}\n".format(encrypted - b, x)
    if choice == 'd':
        with open(sys.argv[2], "rb") as f:
            private_key = pickle.load(f)
        c = int(sys.argv[3])
        a = int(sys.argv[4])
        d = []
        for i in range(c + 1, c + n + 1):
            d.append(private_key.blinded_decrypt(i) % p)
        for i in range(a, n):
            d[i] = d[i] + 1
        with open("compare", "wb") as f:
            pickle.dump(d, f)
    if choice == 'c':
        with open(sys.argv[2], "rb") as f:
Example #24
0
def sign_bytes(message, private_key):
    hash_int = int.from_bytes(md5(message).digest(), sys.byteorder)
    signature_int = encrypt_int(hash_int, private_key.d, private_key.n)

    key_length = byte_size(private_key.n)
    return signature_int.to_bytes(key_length, sys.byteorder)