Пример #1
2
def encode(m, embits, hash_class=hashlib.sha1,
        mgf=mgf.mgf1, salt=None, s_len=None, random=random.SystemRandom):

    m_hash = hash_class(m).digest()
    h_len = len(m_hash)
    if salt is not None:
        s_len = len(salt)
    else:
        if s_len is None:
            s_len = h_len
        salt = primitives.i2osp(random().getrandbits(s_len*8), s_len)
    em_len = primitives.integer_ceil(embits, 8)
    if em_len < len(m_hash) + s_len + 2:
        raise exceptions.EncodingError
    m_prime = ('\x00' * 8) + m_hash + salt
    h = hash_class(m_prime).digest()
    ps = '\x00' * (em_len - s_len - h_len - 2)
    db = ps + '\x01' + salt
    db_mask = mgf(h, em_len - h_len - 1)
    masked_db = primitives.string_xor(db, db_mask)
    octets, bits = (8 * em_len - embits) / 8, (8*em_len-embits) % 8
    # replace first `octets' bytes
    masked_db = ('\x00' * octets) + masked_db[octets:]
    new_byte = chr(ord(masked_db[octets]) & (255 >> bits))
    masked_db = masked_db[:octets] + new_byte + masked_db[octets+1:]
    return masked_db + h + '\xbc'
Пример #2
0
def verify(public_key, message, signature, hash_class=hashlib.sha1):
    '''Verify a signature of a message using a RSA public key and PKCS#1.5
       padding.

       Parameters:

       public_key - a RSA public key
       message - the signed string
       signature - the signature string

       Result:
       True if the signature matches the message, False otherwise.
    '''
    if len(signature) != public_key.byte_size:
        raise exceptions.InvalidSignature
    s = primitives.os2ip(signature)
    try:
        m = public_key.rsavp1(s)
    except ValueError:
        raise exceptions.InvalidSignature
    try:
        em = primitives.i2osp(m, public_key.byte_size)
    except ValueError:
        raise exceptions.InvalidSignature
    try:
        em_prime = emsa_pkcs1_v15.encode(message, public_key.byte_size,
                hash_class=hash_class)
    except ValueError:
        raise exceptions.RSAModulusTooShort
    return primitives.constant_time_cmp(em, em_prime)
Пример #3
0
def sign(private_key,
         message,
         emsa_pss_encode=emsa_pss.encode,
         hash_class=hashlib.sha1,
         mgf1=mgf.mgf1,
         rnd=default_crypto_random):
    '''Sign message using private_key and the PKCS#1 2.0 RSASSA-PSS
       algorithm.

       private_key - the private key to use
       message - the byte string to sign
       emsa_pss_encode - the encoding to use, default to EMSA-PSS encoding
       hash_class - the hash algorithme to use, default to SHA-1 from the
         Python hashlib package.
       mgf1 - the mask generating function to use, default to MGF1
       rnd - a random number generator to use for the PSS encoding,
       default to a Python SystemRandom instance.
    '''
    mod_bits = private_key.bit_size
    embits = mod_bits - 1
    em = emsa_pss_encode(message,
                         embits,
                         hash_class=hash_class,
                         mgf=mgf1,
                         rnd=rnd)
    m = primitives.os2ip(em)
    s = private_key.rsasp1(m)
    return primitives.i2osp(s, private_key.byte_size)
Пример #4
0
def verify(public_key,
           message,
           signature,
           emsa_pss_verify=emsa_pss.verify,
           hash_class=hashlib.sha1,
           mgf1=mgf.mgf1):
    '''Verify the signature of message signed using private_key and the
       PKCS#1 2.0 RSASSA-PSS algorithm.

       private_key - the private key to use
       message - the signed byte string
       signature - the byte string of the signature of the message
       emsa_pss_verify - the verify function for the used encoding,
         default to EMSA-PSS verification function
       hash_class - the hash algorithme to use, default to SHA-1 from the
         Python hashlib package.
       mgf1 - the mask generating function to use, default to MGF1
    '''
    mod_bits = public_key.bit_size
    s = primitives.os2ip(signature)
    m = public_key.rsavp1(s)
    embits = mod_bits - 1
    em_len = primitives.integer_ceil(embits, 8)
    em = primitives.i2osp(m, em_len)
    return emsa_pss_verify(message,
                           em,
                           embits,
                           hash_class=hash_class,
                           mgf=mgf1)
Пример #5
0
def verify(public_key, message, signature):
    '''Verify a signature of a message using a RSA public key and PKCS#1.5
       padding.

       Parameters:

       public_key - a RSA public key
       message - the signed string
       signature - the signature string

       Result:
       True if the signature matches the message, False otherwise.
    '''
    if len(signature) != public_key.byte_size:
        raise exceptions.InvalidSignature
    s = primitives.os2ip(signature)
    try:
        m = public_key.rsavp1(s)
    except ValueError:
        raise exceptions.InvalidSignature
    try:
        em = primitives.i2osp(m, public_key.byte_size)
    except ValueError:
        raise exceptions.InvalidSignature
    try:
        em_prime = emsa_pkcs1_v15.encode(message, public_key.byte_size)
    except ValueError:
        raise exceptions.RSAModulusTooShort
    return primitives.constant_time_cmp(em, em_prime)
Пример #6
0
def encrypt(public_key,
            message,
            label='',
            hash_class=hashlib.sha1,
            mgf=mgf.mgf1,
            seed=None,
            rnd=default_crypto_random):
    '''Encrypt a byte message using a RSA public key and the OAEP wrapping
       algorithm,

       Parameters:
       public_key - an RSA public key
       message - a byte string
       label - a label a per-se PKCS#1 standard
       hash_class - a Python class for a message digest algorithme respecting
         the hashlib interface
       mgf1 - a mask generation function
       seed - a seed to use instead of generating it using a random generator
       rnd - a random generator class, respecting the random generator
       interface from the random module, if seed is None, it is used to
       generate it.

       Return value:
       the encrypted string of the same length as the public key
    '''

    hash = hash_class()
    h_len = hash.digest_size
    k = public_key.byte_size
    max_message_length = k - 2 * h_len - 2
    if len(message) > max_message_length:
        raise exceptions.MessageTooLong
    hash.update(label)
    label_hash = hash.digest()
    ps = '\0' * int(max_message_length - len(message))
    db = ''.join((label_hash, ps, '\x01', message))
    if not seed:
        seed = primitives.i2osp(rnd.getrandbits(h_len * 8), h_len)
    db_mask = mgf(seed, k - h_len - 1, hash_class=hash_class)
    masked_db = primitives.string_xor(db, db_mask)
    seed_mask = mgf(masked_db, h_len, hash_class=hash_class)
    masked_seed = primitives.string_xor(seed, seed_mask)
    em = ''.join(('\x00', masked_seed, masked_db))
    m = primitives.os2ip(em)
    c = public_key.rsaep(m)
    output = primitives.i2osp(c, k)
    return output
Пример #7
0
def sign(private_key, message,
        emsa_pss_encode=emsa_pss.encode):
    mod_bits = private_key.bit_size
    embits = mod_bits - 1
    em = emsa_pss_encode(message, embits)
    m = primitives.os2ip(em)
    s = private_key.rsasp1(m)
    return primitives.i2osp(s, private_key.byte_size)
Пример #8
0
def verify(public_key, message, signature,
        emsa_pss_verify=emsa_pss.verify):
    mod_bits = public_key.bit_size
    s = primitives.os2ip(signature)
    m = public_key.rsavp1(s)
    embits = mod_bits - 1
    em_len = primitives.integer_ceil(embits, 8)
    em = primitives.i2osp(m, em_len)
    return emsa_pss_verify(message, em, embits)
Пример #9
0
def mgf1(mgf_seed, mask_len, hash_class=hashlib.sha1):
    '''Mask Generation Function v1'''
    h_len = hash_class().digest_size
    if mask_len > 0x10000:
        raise ValueError('mask too long')
    T = ''
    for i in xrange(0, integer_ceil(mask_len, h_len)):
        C = i2osp(i, 4)
        T = T + hash_class(mgf_seed + C).digest()
    return T[:mask_len]
Пример #10
0
def encrypt(public_key, message, label='', hash_class=hashlib.sha1,
        mgf=mgf.mgf1, seed=None, random=random.SystemRandom):
    '''Encrypt a byte message using a RSA public key and the OAEP wrapping
       algorithm,

       Parameters:
       public_key - an RSA public key
       message - a byte string
       label - a label a per-se PKCS#1 standard
       hash_class - a Python class for a message digest algorithme respecting
         the hashlib interface
       mgf1 - a mask generation function
       seed - a seed to use instead of generating it using a random generator
       random - a random generator class, respecting the random generator
       interface from the random module, if seed is None, it is used to
       generate it.

       Return value:
       the encrypted string of the same length as the public key
    '''

    hash = hash_class()
    h_len = hash.digest_size
    k = public_key.byte_size
    max_message_length = k - 2 * h_len - 2
    if len(message) > max_message_length:
        raise exceptions.MessageTooLong
    hash.update(label)
    label_hash = hash.digest()
    ps = '\0' * int(max_message_length - len(message))
    db = ''.join((label_hash, ps, '\x01', message))
    if not seed:
        seed = primitives.i2osp(random().getrandbits(h_len*8), h_len)
    db_mask = mgf(seed, k - h_len - 1, hash_class=hash_class)
    masked_db = primitives.string_xor(db, db_mask)
    seed_mask = mgf(masked_db, h_len, hash_class=hash_class)
    masked_seed = primitives.string_xor(seed, seed_mask)
    em = ''.join(('\x00', masked_seed, masked_db))
    m = primitives.os2ip(em)
    c = public_key.rsaep(m)
    output = primitives.i2osp(c, k)
    return output
Пример #11
0
def decrypt(private_key, encryption):
    '''Decrypt encryption of a message using private_key and using PKCS#1 v1.5
       padding scheme.
    '''
    k = private_key.byte_size
    if len(encryption) != k:
        raise exceptions.DecryptionError
    c = primitives.os2ip(encryption)
    m = private_key.rsadp(c)
    em = primitives.i2osp(m, k)
    return eme_pkcs1_v15.decode(em)
Пример #12
0
def decrypt(private_key, encryption):
    '''Decrypt encryption of a message using private_key and using PKCS#1 v1.5
       padding scheme.
    '''
    k = private_key.byte_size
    if len(encryption) != k:
        raise exceptions.DecryptionError
    c = primitives.os2ip(encryption)
    m = private_key.rsadp(c)
    em = primitives.i2osp(m, k)
    return eme_pkcs1_v15.decode(em)
Пример #13
0
def encrypt(public_key, message, ps=None, rnd=random.SystemRandom):
    '''Encrypt message using public_key applying PKCS#1 v1.5 padding

       If ps is not None it is used as the pseudo-random padding bytes,
       otherwise random is used to generate them
    '''
    k = public_key.byte_size
    m_len = len(message)
    if m_len > k - 11:
        raise exceptions.MessageTooLong
    em = eme_pkcs1_v15.encode(message, k, ps=ps, rnd=rnd)
    m = primitives.os2ip(em)
    c = public_key.rsaep(m)
    return primitives.i2osp(c, k)
Пример #14
0
def encrypt(public_key, message, ps=None, rnd=default_crypto_random):
    '''Encrypt message using public_key applying PKCS#1 v1.5 padding

       If ps is not None it is used as the pseudo-random padding bytes,
       otherwise random is used to generate them
    '''
    k = public_key.byte_size
    m_len = len(message)
    if m_len > k - 11:
        raise exceptions.MessageTooLong
    em = eme_pkcs1_v15.encode(message, k, ps=ps, rnd=rnd)
    m = primitives.os2ip(em)
    c = public_key.rsaep(m)
    return primitives.i2osp(c, k)
Пример #15
0
def decrypt(private_key,
            message,
            label='',
            hash_class=hashlib.sha1,
            mgf=mgf.mgf1):
    '''Decrypt a byte message using a RSA private key and the OAEP wrapping algorithm,

       Parameters:
       public_key - an RSA public key
       message - a byte string
       label - a label a per-se PKCS#1 standard
       hash_class - a Python class for a message digest algorithme respecting
         the hashlib interface
       mgf1 - a mask generation function

       Return value:
       the string before encryption (decrypted)
    '''
    hash = hash_class()
    h_len = hash.digest_size
    k = private_key.byte_size
    # 1. check length
    if len(message) != k or k < 2 * h_len + 2:
        raise ValueError('decryption error')
    # 2. RSA decryption
    c = primitives.os2ip(message)
    m = private_key.rsadp(c)
    em = primitives.i2osp(m, k)
    # 4. EME-OAEP decoding
    hash.update(label)
    label_hash = hash.digest()
    y, masked_seed, masked_db = em[0], em[1:h_len + 1], em[1 + h_len:]
    if y != '\x00':
        raise ValueError('decryption error')
    seed_mask = mgf(masked_db, h_len, hash_class=hash_class)
    seed = primitives.string_xor(masked_seed, seed_mask)
    db_mask = mgf(seed, k - h_len - 1, hash_class=hash_class)
    db = primitives.string_xor(masked_db, db_mask)
    label_hash_prime, rest = db[:h_len], db[h_len:]
    i = rest.find('\x01')
    if i == -1:
        raise exceptions.DecryptionError
    if rest[:i].strip('\x00') != '':
        raise exceptions.DecryptionError
    m = rest[i + 1:]
    if label_hash_prime != label_hash:
        raise exceptions.DecryptionError
    return m
Пример #16
0
def sign(private_key, message):
    '''Produce a signature of string using a RSA private key and PKCS#1.5
       padding.

       Parameters:

       private_key - a RSA private key
       message - a string to sign

       Result:
       the signature string
    '''

    em = emsa_pkcs1_v15.encode(message, private_key.byte_size)
    m = primitives.os2ip(em)
    s = private_key.rsasp1(m)
    return primitives.i2osp(s, private_key.byte_size)
Пример #17
0
def encode(m,
           embits,
           hash_class=hashlib.sha1,
           mgf=mgf.mgf1,
           salt=None,
           s_len=None,
           rnd=default_crypto_random):
    '''Encode a message using the PKCS v2 PSS padding.

       m - the message to encode
       embits - the length of the padded message
       mgf - a masg generating function, default is mgf1 the mask generating
       function proposed in the PKCS#1 v2 standard.
       hash_class - the hash algorithm to use to compute the digest of the
       message, must conform to the hashlib class interface.
       salt - a fixed salt string to use, if None, a random string of length
       s_len is used instead, necessary for tests,
       s_len - the length of the salt string when using a random generator to
       create it, if None the length of the digest is used.
       rnd - the random generator used to compute the salt string

       Return value: the padded message
    '''
    m_hash = hash_class(m).digest()
    h_len = len(m_hash)
    if salt is not None:
        s_len = len(salt)
    else:
        if s_len is None:
            s_len = h_len
        salt = primitives.i2osp(rnd.getrandbits(s_len * 8), s_len)
    em_len = primitives.integer_ceil(embits, 8)
    if em_len < len(m_hash) + s_len + 2:
        raise exceptions.EncodingError
    m_prime = ('\x00' * 8) + m_hash + salt
    h = hash_class(m_prime).digest()
    ps = '\x00' * (em_len - s_len - h_len - 2)
    db = ps + '\x01' + salt
    db_mask = mgf(h, em_len - h_len - 1)
    masked_db = primitives.string_xor(db, db_mask)
    octets, bits = (8 * em_len - embits) / 8, (8 * em_len - embits) % 8
    # replace first `octets' bytes
    masked_db = ('\x00' * octets) + masked_db[octets:]
    new_byte = chr(ord(masked_db[octets]) & (255 >> bits))
    masked_db = masked_db[:octets] + new_byte + masked_db[octets + 1:]
    return masked_db + h + '\xbc'
Пример #18
0
def decrypt(private_key, message, label='', hash_class=hashlib.sha1,
        mgf=mgf.mgf1):
    '''Decrypt a byte message using a RSA private key and the OAEP wrapping algorithm,

       Parameters:
       public_key - an RSA public key
       message - a byte string
       label - a label a per-se PKCS#1 standard
       hash_class - a Python class for a message digest algorithme respecting
         the hashlib interface
       mgf1 - a mask generation function

       Return value:
       the string before encryption (decrypted)
    '''
    hash = hash_class()
    h_len = hash.digest_size
    k = private_key.byte_size
    # 1. check length
    if len(message) != k or k < 2 * h_len + 2:
        raise ValueError('decryption error')
    # 2. RSA decryption
    c = primitives.os2ip(message)
    m = private_key.rsadp(c)
    em = primitives.i2osp(m, k)
    # 4. EME-OAEP decoding
    hash.update(label)
    label_hash = hash.digest()
    y, masked_seed, masked_db = em[0], em[1:h_len+1], em[1+h_len:]
    if y != '\x00':
        raise ValueError('decryption error')
    seed_mask = mgf(masked_db, h_len)
    seed = primitives.string_xor(masked_seed, seed_mask)
    db_mask = mgf(seed, k - h_len - 1)
    db = primitives.string_xor(masked_db, db_mask)
    label_hash_prime, rest = db[:h_len], db[h_len:]
    i = rest.find('\x01')
    if i == -1:
        raise exceptions.DecryptionError
    if rest[:i].strip('\x00') != '':
        raise exceptions.DecryptionError
    m = rest[i+1:]
    if label_hash_prime != label_hash:
        raise exceptions.DecryptionError
    return m
Пример #19
0
def mgf1(mgf_seed, mask_len, hash_class=hashlib.sha1):
    '''
       Mask Generation Function v1 from the PKCS#1 v2.0 standard.

       mgs_seed - the seed, a byte string
       mask_len - the length of the mask to generate
       hash_class - the digest algorithm to use, default is SHA1

       Return value: a pseudo-random mask, as a byte string
       '''
    h_len = hash_class().digest_size
    if mask_len > 0x10000:
        raise ValueError('mask too long')
    T = ''
    for i in xrange(0, integer_ceil(mask_len, h_len)):
        C = i2osp(i, 4)
        T = T + hash_class(mgf_seed + C).digest()
    return T[:mask_len]
Пример #20
0
def mgf1(mgf_seed, mask_len, hash_class=hashlib.sha1):
    '''
       Mask Generation Function v1 from the PKCS#1 v2.0 standard.

       mgs_seed - the seed, a byte string
       mask_len - the length of the mask to generate
       hash_class - the digest algorithm to use, default is SHA1

       Return value: a pseudo-random mask, as a byte string
       '''
    h_len = hash_class().digest_size
    if mask_len > 0x10000:
        raise ValueError('mask too long')
    T = ''
    for i in xrange(0, integer_ceil(mask_len, h_len)):
        C = i2osp(i, 4)
        T = T + hash_class(mgf_seed + C).digest()
    return T[:mask_len]
Пример #21
0
def sign(private_key, message, hash_class=hashlib.sha1):
    '''Produce a signature of string using a RSA private key and PKCS#1.5
       padding.

       Parameters:

       private_key - a RSA private key
       message - a string to sign

       Result:
       the signature string
    '''

    em = emsa_pkcs1_v15.encode(message, private_key.byte_size,
            hash_class=hash_class)
    m = primitives.os2ip(em)
    s = private_key.rsasp1(m)
    return primitives.i2osp(s, private_key.byte_size)
Пример #22
0
def encode(m, embits, hash_class=hashlib.sha1,
        mgf=mgf.mgf1, salt=None, s_len=None, rnd=default_crypto_random):
    '''Encode a message using the PKCS v2 PSS padding.

       m - the message to encode
       embits - the length of the padded message
       mgf - a masg generating function, default is mgf1 the mask generating
       function proposed in the PKCS#1 v2 standard.
       hash_class - the hash algorithm to use to compute the digest of the
       message, must conform to the hashlib class interface.
       salt - a fixed salt string to use, if None, a random string of length
       s_len is used instead, necessary for tests,
       s_len - the length of the salt string when using a random generator to
       create it, if None the length of the digest is used.
       rnd - the random generator used to compute the salt string

       Return value: the padded message
    '''
    m_hash = hash_class(m).digest()
    h_len = len(m_hash)
    if salt is not None:
        s_len = len(salt)
    else:
        if s_len is None:
            s_len = h_len
        salt = primitives.i2osp(rnd.getrandbits(s_len*8), s_len)
    em_len = primitives.integer_ceil(embits, 8)
    if em_len < len(m_hash) + s_len + 2:
        raise exceptions.EncodingError
    m_prime = ('\x00' * 8) + m_hash + salt
    h = hash_class(m_prime).digest()
    ps = '\x00' * (em_len - s_len - h_len - 2)
    db = ps + '\x01' + salt
    db_mask = mgf(h, em_len - h_len - 1, hash_class=hash_class)
    masked_db = primitives.string_xor(db, db_mask)
    octets, bits = (8 * em_len - embits) / 8, (8*em_len-embits) % 8
    # replace first `octets' bytes
    masked_db = ('\x00' * octets) + masked_db[octets:]
    new_byte = chr(ord(masked_db[octets]) & (255 >> bits))
    masked_db = masked_db[:octets] + new_byte + masked_db[octets+1:]
    return masked_db + h + '\xbc'
Пример #23
0
def sign(private_key, message,
        emsa_pss_encode=emsa_pss.encode,
        hash_class=hashlib.sha1,
        mgf1=mgf.mgf1,
        rnd=default_crypto_random):
    '''Sign message using private_key and the PKCS#1 2.0 RSASSA-PSS
       algorithm.

       private_key - the private key to use
       message - the byte string to sign
       emsa_pss_encode - the encoding to use, default to EMSA-PSS encoding
       hash_class - the hash algorithme to use, default to SHA-1 from the
         Python hashlib package.
       mgf1 - the mask generating function to use, default to MGF1
       rnd - a random number generator to use for the PSS encoding,
       default to a Python SystemRandom instance.
    '''
    mod_bits = private_key.bit_size
    embits = mod_bits - 1
    em = emsa_pss_encode(message, embits, hash_class=hash_class,
            mgf=mgf1, rnd=rnd)
    m = primitives.os2ip(em)
    s = private_key.rsasp1(m)
    return primitives.i2osp(s, private_key.byte_size)
Пример #24
0
def verify(public_key, message, signature,
        emsa_pss_verify=emsa_pss.verify,
        hash_class=hashlib.sha1,
        mgf1=mgf.mgf1):
    '''Verify the signature of message signed using private_key and the
       PKCS#1 2.0 RSASSA-PSS algorithm.

       private_key - the private key to use
       message - the signed byte string
       signature - the byte string of the signature of the message
       emsa_pss_verify - the verify function for the used encoding,
         default to EMSA-PSS verification function
       hash_class - the hash algorithme to use, default to SHA-1 from the
         Python hashlib package.
       mgf1 - the mask generating function to use, default to MGF1
    '''
    mod_bits = public_key.bit_size
    s = primitives.os2ip(signature)
    m = public_key.rsavp1(s)
    embits = mod_bits - 1
    em_len = primitives.integer_ceil(embits, 8)
    em = primitives.i2osp(m, em_len)
    return emsa_pss_verify(message, em, embits, hash_class=hash_class,
            mgf=mgf1)