Exemplo n.º 1
0
 def _test_signing(self, dsaObj):
     k = bytes_to_long(a2b_hex(self.k))
     m_hash = bytes_to_long(a2b_hex(self.m_hash))
     r = bytes_to_long(a2b_hex(self.r))
     s = bytes_to_long(a2b_hex(self.s))
     (r_out, s_out) = dsaObj._sign(m_hash, k)
     self.assertEqual((r, s), (r_out, s_out))
Exemplo n.º 2
0
    def _check_decryption(self, rsaObj):
        plaintext = bytes_to_long(a2b_hex(self.plaintext))
        ciphertext = bytes_to_long(a2b_hex(self.ciphertext))

        # Test plain decryption
        new_plaintext = rsaObj._decrypt(ciphertext)
        self.assertEqual(plaintext, new_plaintext)
    def _check_encryption(self, rsaObj):
        plaintext = a2b_hex(self.plaintext)
        ciphertext = a2b_hex(self.ciphertext)

        # Test encryption
        new_ciphertext2 = rsaObj._encrypt(bytes_to_long(plaintext))
        self.assertEqual(bytes_to_long(ciphertext), new_ciphertext2)
Exemplo n.º 4
0
    def _check_encryption(self, rsaObj):
        plaintext = a2b_hex(self.plaintext)
        ciphertext = a2b_hex(self.ciphertext)

        # Test encryption
        new_ciphertext2 = rsaObj._encrypt(bytes_to_long(plaintext))
        self.assertEqual(bytes_to_long(ciphertext), new_ciphertext2)
    def _check_decryption(self, rsaObj):
        plaintext = bytes_to_long(a2b_hex(self.plaintext))
        ciphertext = bytes_to_long(a2b_hex(self.ciphertext))

        # Test plain decryption
        new_plaintext = rsaObj._decrypt(ciphertext)
        self.assertEqual(plaintext, new_plaintext)
Exemplo n.º 6
0
    def _check_public_key(self, dsaObj):
        k = bytes_to_long(a2b_hex(self.k))
        m_hash = bytes_to_long(a2b_hex(self.m_hash))

        # Check capabilities
        self.assertEqual(0, dsaObj.has_private())
        self.assertEqual(1, dsaObj.can_sign())
        self.assertEqual(0, dsaObj.can_encrypt())

        # Check that private parameters are all missing
        self.assertEqual(0, hasattr(dsaObj, 'x'))

        # Sanity check key data
        self.assertEqual(1, dsaObj.p > dsaObj.q)  # p > q
        self.assertEqual(160, size(dsaObj.q))  # size(q) == 160 bits
        self.assertEqual(0, (dsaObj.p - 1) % dsaObj.q)  # q is a divisor of p-1

        # Public-only key objects should raise an error when .sign() is called
        self.assertRaises(TypeError, dsaObj._sign, m_hash, k)

        # Check __eq__ and __ne__
        self.assertEqual(dsaObj.publickey() == dsaObj.publickey(),
                         True)  # assert_
        self.assertEqual(dsaObj.publickey() != dsaObj.publickey(),
                         False)  # failIf
Exemplo n.º 7
0
 def _test_signing(self, dsaObj):
     k = bytes_to_long(a2b_hex(self.k))
     m_hash = bytes_to_long(a2b_hex(self.m_hash))
     r = bytes_to_long(a2b_hex(self.r))
     s = bytes_to_long(a2b_hex(self.s))
     (r_out, s_out) = dsaObj._sign(m_hash, k)
     self.assertEqual((r, s), (r_out, s_out))
Exemplo n.º 8
0
    def setUp(self):
        global RSA, Random, bytes_to_long
        from Cryptodome.PublicKey import RSA
        from Cryptodome import Random
        from Cryptodome.Util.number import bytes_to_long, inverse
        self.n = bytes_to_long(a2b_hex(self.modulus))
        self.p = bytes_to_long(a2b_hex(self.prime_factor))

        # Compute q, d, and u from n, e, and p
        self.q = self.n // self.p
        self.d = inverse(self.e, (self.p-1)*(self.q-1))
        self.u = inverse(self.p, self.q)    # u = e**-1 (mod q)

        self.rsa = RSA
    def setUp(self):
        global RSA, Random, bytes_to_long
        from Cryptodome.PublicKey import RSA
        from Cryptodome import Random
        from Cryptodome.Util.number import bytes_to_long, inverse
        self.n = bytes_to_long(a2b_hex(self.modulus))
        self.p = bytes_to_long(a2b_hex(self.prime_factor))

        # Compute q, d, and u from n, e, and p
        self.q = self.n // self.p
        self.d = inverse(self.e, (self.p-1)*(self.q-1))
        self.u = inverse(self.p, self.q)    # u = e**-1 (mod q)

        self.rsa = RSA
Exemplo n.º 10
0
def t2b(t):
    """Convert a text string with bytes in hex form to a byte string"""
    clean = b(rws(t))
    if len(clean) % 2 == 1:
        print clean
        raise ValueError("Even number of characters expected")
    return a2b_hex(clean)
Exemplo n.º 11
0
    def _check_public_key(self, rsaObj):
        ciphertext = a2b_hex(self.ciphertext)

        # Check capabilities
        self.assertEqual(0, rsaObj.has_private())

        # Check rsaObj.[ne] -> rsaObj.[ne] mapping
        self.assertEqual(rsaObj.n, rsaObj.n)
        self.assertEqual(rsaObj.e, rsaObj.e)

        # Check that private parameters are all missing
        self.assertEqual(0, hasattr(rsaObj, 'd'))
        self.assertEqual(0, hasattr(rsaObj, 'p'))
        self.assertEqual(0, hasattr(rsaObj, 'q'))
        self.assertEqual(0, hasattr(rsaObj, 'u'))

        # Sanity check key data
        self.assertEqual(1, rsaObj.e > 1)   # e > 1

        # Public keys should not be able to sign or decrypt
        self.assertRaises(TypeError, rsaObj._decrypt,
                bytes_to_long(ciphertext))

        # Check __eq__ and __ne__
        self.assertEqual(rsaObj.publickey() == rsaObj.publickey(),True) # assert_
        self.assertEqual(rsaObj.publickey() != rsaObj.publickey(),False) # failIf
Exemplo n.º 12
0
 def test_repr(self):
     (y, g, p, q) = [
         bytes_to_long(a2b_hex(param))
         for param in (self.y, self.g, self.p, self.q)
     ]
     dsaObj = self.dsa.construct((y, g, p, q))
     repr(dsaObj)
    def _check_public_key(self, rsaObj):
        ciphertext = a2b_hex(self.ciphertext)

        # Check capabilities
        self.assertEqual(0, rsaObj.has_private())

        # Check rsaObj.[ne] -> rsaObj.[ne] mapping
        self.assertEqual(rsaObj.n, rsaObj.n)
        self.assertEqual(rsaObj.e, rsaObj.e)

        # Check that private parameters are all missing
        self.assertEqual(0, hasattr(rsaObj, 'd'))
        self.assertEqual(0, hasattr(rsaObj, 'p'))
        self.assertEqual(0, hasattr(rsaObj, 'q'))
        self.assertEqual(0, hasattr(rsaObj, 'u'))

        # Sanity check key data
        self.assertEqual(1, rsaObj.e > 1)   # e > 1

        # Public keys should not be able to sign or decrypt
        self.assertRaises(TypeError, rsaObj._decrypt,
                bytes_to_long(ciphertext))

        # Check __eq__ and __ne__
        self.assertEqual(rsaObj.publickey() == rsaObj.publickey(),True) # assert_
        self.assertEqual(rsaObj.publickey() != rsaObj.publickey(),False) # failIf
Exemplo n.º 14
0
    def test_construct_bad_key5(self):
        (y, g, p, q, x) = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q, self.x)]
        tup = (y, g, p, q, x+1)
        self.assertRaises(ValueError, self.dsa.construct, tup)

        tup = (y, g, p, q, q+10)
        self.assertRaises(ValueError, self.dsa.construct, tup)
def t2b(t):
    """Convert a text string with bytes in hex form to a byte string"""
    clean = b(rws(t))
    if len(clean)%2 == 1:
        print clean
        raise ValueError("Even number of characters expected")
    return a2b_hex(clean)
Exemplo n.º 16
0
 def test_construct_4tuple(self):
     """DSA (default implementation) constructed key (4-tuple)"""
     (y, g, p, q) = [
         bytes_to_long(a2b_hex(param))
         for param in (self.y, self.g, self.p, self.q)
     ]
     dsaObj = self.dsa.construct((y, g, p, q))
     self._test_verification(dsaObj)
Exemplo n.º 17
0
    def test_construct_bad_key4(self):
        (y, g, p, q) = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q)]
        tup = (y, g, p+1, q)
        self.assertRaises(ValueError, self.dsa.construct, tup)

        tup = (y, g, p, q+1)
        self.assertRaises(ValueError, self.dsa.construct, tup)

        tup = (y, 1L, p, q)
        self.assertRaises(ValueError, self.dsa.construct, tup)
    def _exercise_primitive(self, rsaObj):
        # Since we're using a randomly-generated key, we can't check the test
        # vector, but we can make sure encryption and decryption are inverse
        # operations.
        ciphertext = bytes_to_long(a2b_hex(self.ciphertext))

        # Test decryption
        plaintext = rsaObj._decrypt(ciphertext)

        # Test encryption (2 arguments)
        new_ciphertext2 = rsaObj._encrypt(plaintext)
        self.assertEqual(ciphertext, new_ciphertext2)
Exemplo n.º 19
0
    def _exercise_primitive(self, rsaObj):
        # Since we're using a randomly-generated key, we can't check the test
        # vector, but we can make sure encryption and decryption are inverse
        # operations.
        ciphertext = bytes_to_long(a2b_hex(self.ciphertext))

        # Test decryption
        plaintext = rsaObj._decrypt(ciphertext)

        # Test encryption (2 arguments)
        new_ciphertext2 = rsaObj._encrypt(plaintext)
        self.assertEqual(ciphertext, new_ciphertext2)
 def convert_tv(self, tv, as_longs=0):
     """Convert a test vector from textual form (hexadecimal ascii
     to either integers or byte strings."""
     key_comps = 'p', 'g', 'y', 'x'
     tv2 = {}
     for c in tv.keys():
         tv2[c] = a2b_hex(tv[c])
         if as_longs or c in key_comps or c in ('sig1', 'sig2'):
             tv2[c] = bytes_to_long(tv2[c])
     tv2['key'] = []
     for c in key_comps:
         tv2['key'] += [tv2[c]]
         del tv2[c]
     return tv2
 def convert_tv(self, tv, as_longs=0):
     """Convert a test vector from textual form (hexadecimal ascii
     to either integers or byte strings."""
     key_comps = 'p','g','y','x'
     tv2 = {}
     for c in tv.keys():
         tv2[c] = a2b_hex(tv[c])
         if as_longs or c in key_comps or c in ('sig1','sig2'):
             tv2[c] = bytes_to_long(tv2[c])
     tv2['key']=[]
     for c in key_comps:
         tv2['key'] += [tv2[c]]
         del tv2[c]
     return tv2
Exemplo n.º 22
0
    def _check_public_key(self, dsaObj):
        k = bytes_to_long(a2b_hex(self.k))
        m_hash = bytes_to_long(a2b_hex(self.m_hash))

        # Check capabilities
        self.assertEqual(0, dsaObj.has_private())
        self.assertEqual(1, dsaObj.can_sign())
        self.assertEqual(0, dsaObj.can_encrypt())

        # Check that private parameters are all missing
        self.assertEqual(0, hasattr(dsaObj, 'x'))

        # Sanity check key data
        self.assertEqual(1, dsaObj.p > dsaObj.q)            # p > q
        self.assertEqual(160, size(dsaObj.q))               # size(q) == 160 bits
        self.assertEqual(0, (dsaObj.p - 1) % dsaObj.q)      # q is a divisor of p-1

        # Public-only key objects should raise an error when .sign() is called
        self.assertRaises(TypeError, dsaObj._sign, m_hash, k)

        # Check __eq__ and __ne__
        self.assertEqual(dsaObj.publickey() == dsaObj.publickey(),True) # assert_
        self.assertEqual(dsaObj.publickey() != dsaObj.publickey(),False) # failIf
Exemplo n.º 23
0
class ImportKeyTests(unittest.TestCase):
    # 512-bit RSA key generated with openssl
    rsaKeyPEM = u'''-----BEGIN RSA PRIVATE KEY-----
MIIBOwIBAAJBAL8eJ5AKoIsjURpcEoGubZMxLD7+kT+TLr7UkvEtFrRhDDKMtuII
q19FrL4pUIMymPMSLBn3hJLe30Dw48GQM4UCAwEAAQJACUSDEp8RTe32ftq8IwG8
Wojl5mAd1wFiIOrZ/Uv8b963WJOJiuQcVN29vxU5+My9GPZ7RA3hrDBEAoHUDPrI
OQIhAPIPLz4dphiD9imAkivY31Rc5AfHJiQRA7XixTcjEkojAiEAyh/pJHks/Mlr
+rdPNEpotBjfV4M4BkgGAA/ipcmaAjcCIQCHvhwwKVBLzzTscT2HeUdEeBMoiXXK
JACAr3sJQJGxIQIgarRp+m1WSKV1MciwMaTOnbU7wxFs9DP1pva76lYBzgUCIQC9
n0CnZCJ6IZYqSt0H5N7+Q+2Ro64nuwV/OSQfM6sBwQ==
-----END RSA PRIVATE KEY-----'''

    # As above, but this is actually an unencrypted PKCS#8 key
    rsaKeyPEM8 = u'''-----BEGIN PRIVATE KEY-----
MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAvx4nkAqgiyNRGlwS
ga5tkzEsPv6RP5MuvtSS8S0WtGEMMoy24girX0WsvilQgzKY8xIsGfeEkt7fQPDj
wZAzhQIDAQABAkAJRIMSnxFN7fZ+2rwjAbxaiOXmYB3XAWIg6tn9S/xv3rdYk4mK
5BxU3b2/FTn4zL0Y9ntEDeGsMEQCgdQM+sg5AiEA8g8vPh2mGIP2KYCSK9jfVFzk
B8cmJBEDteLFNyMSSiMCIQDKH+kkeSz8yWv6t080Smi0GN9XgzgGSAYAD+KlyZoC
NwIhAIe+HDApUEvPNOxxPYd5R0R4EyiJdcokAICvewlAkbEhAiBqtGn6bVZIpXUx
yLAxpM6dtTvDEWz0M/Wm9rvqVgHOBQIhAL2fQKdkInohlipK3Qfk3v5D7ZGjrie7
BX85JB8zqwHB
-----END PRIVATE KEY-----'''

    # The same RSA private key as in rsaKeyPEM, but now encrypted
    rsaKeyEncryptedPEM = (

        # PEM encryption
        # With DES and passphrase 'test'
        ('test', u'''-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-CBC,AF8F9A40BD2FA2FC

Ckl9ex1kaVEWhYC2QBmfaF+YPiR4NFkRXA7nj3dcnuFEzBnY5XULupqQpQI3qbfA
u8GYS7+b3toWWiHZivHbAAUBPDIZG9hKDyB9Sq2VMARGsX1yW1zhNvZLIiVJzUHs
C6NxQ1IJWOXzTew/xM2I26kPwHIvadq+/VaT8gLQdjdH0jOiVNaevjWnLgrn1mLP
BCNRMdcexozWtAFNNqSzfW58MJL2OdMi21ED184EFytIc1BlB+FZiGZduwKGuaKy
9bMbdb/1PSvsSzPsqW7KSSrTw6MgJAFJg6lzIYvR5F4poTVBxwBX3+EyEmShiaNY
IRX3TgQI0IjrVuLmvlZKbGWP18FXj7I7k9tSsNOOzllTTdq3ny5vgM3A+ynfAaxp
dysKznQ6P+IoqML1WxAID4aGRMWka+uArOJ148Rbj9s=
-----END RSA PRIVATE KEY-----'''),

        # PKCS8 encryption
        ('winter', u'''-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIBpjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIeZIsbW3O+JcCAggA
MBQGCCqGSIb3DQMHBAgSM2p0D8FilgSCAWBhFyP2tiGKVpGj3mO8qIBzinU60ApR
3unvP+N6j7LVgnV2lFGaXbJ6a1PbQXe+2D6DUyBLo8EMXrKKVLqOMGkFMHc0UaV6
R6MmrsRDrbOqdpTuVRW+NVd5J9kQQh4xnfU/QrcPPt7vpJvSf4GzG0n666Ki50OV
M/feuVlIiyGXY6UWdVDpcOV72cq02eNUs/1JWdh2uEBvA9fCL0c07RnMrdT+CbJQ
NjJ7f8ULtp7xvR9O3Al/yJ4Wv3i4VxF1f3MCXzhlUD4I0ONlr0kJWgeQ80q/cWhw
ntvgJwnCn2XR1h6LA8Wp+0ghDTsL2NhJpWd78zClGhyU4r3hqu1XDjoXa7YCXCix
jCV15+ViDJzlNCwg+W6lRg18sSLkCT7alviIE0U5tHc6UPbbHwT5QqAxAABaP+nZ
CGqJGyiwBzrKebjgSm/KRd4C91XqcsysyH2kKPfT51MLAoD4xelOURBP
-----END ENCRYPTED PRIVATE KEY-----'''),
    )

    rsaPublicKeyPEM = u'''-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAL8eJ5AKoIsjURpcEoGubZMxLD7+kT+T
Lr7UkvEtFrRhDDKMtuIIq19FrL4pUIMymPMSLBn3hJLe30Dw48GQM4UCAwEAAQ==
-----END PUBLIC KEY-----'''

    # Obtained using 'ssh-keygen -i -m PKCS8 -f rsaPublicKeyPEM'
    rsaPublicKeyOpenSSH = b(
        '''ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAQQC/HieQCqCLI1EaXBKBrm2TMSw+/pE/ky6+1JLxLRa0YQwyjLbiCKtfRay+KVCDMpjzEiwZ94SS3t9A8OPBkDOF comment\n'''
    )

    # The private key, in PKCS#1 format encoded with DER
    rsaKeyDER = a2b_hex(
        '''3082013b020100024100bf1e27900aa08b23511a5c1281ae6d93312c3efe
    913f932ebed492f12d16b4610c328cb6e208ab5f45acbe2950833298f312
    2c19f78492dedf40f0e3c190338502030100010240094483129f114dedf6
    7edabc2301bc5a88e5e6601dd7016220ead9fd4bfc6fdeb75893898ae41c
    54ddbdbf1539f8ccbd18f67b440de1ac30440281d40cfac839022100f20f
    2f3e1da61883f62980922bd8df545ce407c726241103b5e2c53723124a23
    022100ca1fe924792cfcc96bfab74f344a68b418df578338064806000fe2
    a5c99a023702210087be1c3029504bcf34ec713d877947447813288975ca
    240080af7b094091b12102206ab469fa6d5648a57531c8b031a4ce9db53b
    c3116cf433f5a6f6bbea5601ce05022100bd9f40a764227a21962a4add07
    e4defe43ed91a3ae27bb057f39241f33ab01c1
    '''.replace(" ", ""))

    # The private key, in unencrypted PKCS#8 format encoded with DER
    rsaKeyDER8 = a2b_hex(
        '''30820155020100300d06092a864886f70d01010105000482013f3082013
    b020100024100bf1e27900aa08b23511a5c1281ae6d93312c3efe913f932
    ebed492f12d16b4610c328cb6e208ab5f45acbe2950833298f3122c19f78
    492dedf40f0e3c190338502030100010240094483129f114dedf67edabc2
    301bc5a88e5e6601dd7016220ead9fd4bfc6fdeb75893898ae41c54ddbdb
    f1539f8ccbd18f67b440de1ac30440281d40cfac839022100f20f2f3e1da
    61883f62980922bd8df545ce407c726241103b5e2c53723124a23022100c
    a1fe924792cfcc96bfab74f344a68b418df578338064806000fe2a5c99a0
    23702210087be1c3029504bcf34ec713d877947447813288975ca240080a
    f7b094091b12102206ab469fa6d5648a57531c8b031a4ce9db53bc3116cf
    433f5a6f6bbea5601ce05022100bd9f40a764227a21962a4add07e4defe4
    3ed91a3ae27bb057f39241f33ab01c1
    '''.replace(" ", ""))

    rsaPublicKeyDER = a2b_hex(
        '''305c300d06092a864886f70d0101010500034b003048024100bf1e27900a
    a08b23511a5c1281ae6d93312c3efe913f932ebed492f12d16b4610c328c
    b6e208ab5f45acbe2950833298f3122c19f78492dedf40f0e3c190338502
    03010001
    '''.replace(" ", ""))

    n = int(
        'BF 1E 27 90 0A A0 8B 23 51 1A 5C 12 81 AE 6D 93 31 2C 3E FE 91 3F 93 2E BE D4 92 F1 2D 16 B4 61 0C 32 8C B6 E2 08 AB 5F 45 AC BE 29 50 83 32 98 F3 12 2C 19 F7 84 92 DE DF 40 F0 E3 C1 90 33 85'
        .replace(" ", ""), 16)
    e = 65537
    d = int(
        '09 44 83 12 9F 11 4D ED F6 7E DA BC 23 01 BC 5A 88 E5 E6 60 1D D7 01 62 20 EA D9 FD 4B FC 6F DE B7 58 93 89 8A E4 1C 54 DD BD BF 15 39 F8 CC BD 18 F6 7B 44 0D E1 AC 30 44 02 81 D4 0C FA C8 39'
        .replace(" ", ""), 16)
    p = int(
        '00 F2 0F 2F 3E 1D A6 18 83 F6 29 80 92 2B D8 DF 54 5C E4 07 C7 26 24 11 03 B5 E2 C5 37 23 12 4A 23'
        .replace(" ", ""), 16)
    q = int(
        '00 CA 1F E9 24 79 2C FC C9 6B FA B7 4F 34 4A 68 B4 18 DF 57 83 38 06 48 06 00 0F E2 A5 C9 9A 02 37'
        .replace(" ", ""), 16)

    # This is q^{-1} mod p). fastmath and slowmath use pInv (p^{-1}
    # mod q) instead!
    qInv = int(
        '00 BD 9F 40 A7 64 22 7A 21 96 2A 4A DD 07 E4 DE FE 43 ED 91 A3 AE 27 BB 05 7F 39 24 1F 33 AB 01 C1'
        .replace(" ", ""), 16)
    pInv = inverse(p, q)

    def testImportKey1(self):
        """Verify import of RSAPrivateKey DER SEQUENCE"""
        key = RSA.importKey(self.rsaKeyDER)
        self.assertTrue(key.has_private())
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)
        self.assertEqual(key.d, self.d)
        self.assertEqual(key.p, self.p)
        self.assertEqual(key.q, self.q)

    def testImportKey2(self):
        """Verify import of SubjectPublicKeyInfo DER SEQUENCE"""
        key = RSA.importKey(self.rsaPublicKeyDER)
        self.assertFalse(key.has_private())
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)

    def testImportKey3unicode(self):
        """Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as unicode"""
        key = RSA.importKey(self.rsaKeyPEM)
        self.assertEqual(key.has_private(), True)  # assert_
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)
        self.assertEqual(key.d, self.d)
        self.assertEqual(key.p, self.p)
        self.assertEqual(key.q, self.q)

    def testImportKey3bytes(self):
        """Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as byte string"""
        key = RSA.importKey(b(self.rsaKeyPEM))
        self.assertEqual(key.has_private(), True)  # assert_
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)
        self.assertEqual(key.d, self.d)
        self.assertEqual(key.p, self.p)
        self.assertEqual(key.q, self.q)

    def testImportKey4unicode(self):
        """Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as unicode"""
        key = RSA.importKey(self.rsaPublicKeyPEM)
        self.assertEqual(key.has_private(), False)  # assertFalse
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)

    def testImportKey4bytes(self):
        """Verify import of SubjectPublicKeyInfo DER SEQUENCE, encoded with PEM as byte string"""
        key = RSA.importKey(b(self.rsaPublicKeyPEM))
        self.assertEqual(key.has_private(), False)  # assertFalse
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)

    def testImportKey5(self):
        """Verifies that the imported key is still a valid RSA pair"""
        key = RSA.importKey(self.rsaKeyPEM)
        idem = key._encrypt(key._decrypt(89))
        self.assertEqual(idem, 89)

    def testImportKey6(self):
        """Verifies that the imported key is still a valid RSA pair"""
        key = RSA.importKey(self.rsaKeyDER)
        idem = key._encrypt(key._decrypt(65))
        self.assertEqual(idem, 65)

    def testImportKey7(self):
        """Verify import of OpenSSH public key"""
        key = RSA.importKey(self.rsaPublicKeyOpenSSH)
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)

    def testImportKey8(self):
        """Verify import of encrypted PrivateKeyInfo DER SEQUENCE"""
        for t in self.rsaKeyEncryptedPEM:
            key = RSA.importKey(t[1], t[0])
            self.assertTrue(key.has_private())
            self.assertEqual(key.n, self.n)
            self.assertEqual(key.e, self.e)
            self.assertEqual(key.d, self.d)
            self.assertEqual(key.p, self.p)
            self.assertEqual(key.q, self.q)

    def testImportKey9(self):
        """Verify import of unencrypted PrivateKeyInfo DER SEQUENCE"""
        key = RSA.importKey(self.rsaKeyDER8)
        self.assertTrue(key.has_private())
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)
        self.assertEqual(key.d, self.d)
        self.assertEqual(key.p, self.p)
        self.assertEqual(key.q, self.q)

    def testImportKey10(self):
        """Verify import of unencrypted PrivateKeyInfo DER SEQUENCE, encoded with PEM"""
        key = RSA.importKey(self.rsaKeyPEM8)
        self.assertTrue(key.has_private())
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)
        self.assertEqual(key.d, self.d)
        self.assertEqual(key.p, self.p)
        self.assertEqual(key.q, self.q)

    def testImportKey11(self):
        """Verify import of RSAPublicKey DER SEQUENCE"""
        der = asn1.DerSequence([17, 3]).encode()
        key = RSA.importKey(der)
        self.assertEqual(key.n, 17)
        self.assertEqual(key.e, 3)

    def testImportKey12(self):
        """Verify import of RSAPublicKey DER SEQUENCE, encoded with PEM"""
        der = asn1.DerSequence([17, 3]).encode()
        pem = der2pem(der)
        key = RSA.importKey(pem)
        self.assertEqual(key.n, 17)
        self.assertEqual(key.e, 3)

    def test_import_key_windows_cr_lf(self):
        pem_cr_lf = "\r\n".join(self.rsaKeyPEM.splitlines())
        key = RSA.importKey(pem_cr_lf)
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)
        self.assertEqual(key.d, self.d)
        self.assertEqual(key.p, self.p)
        self.assertEqual(key.q, self.q)

    def test_import_empty(self):
        self.assertRaises(ValueError, RSA.import_key, b"")

    ###
    def testExportKey1(self):
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        derKey = key.export_key("DER")
        self.assertEqual(derKey, self.rsaKeyDER)

    def testExportKey2(self):
        key = RSA.construct([self.n, self.e])
        derKey = key.export_key("DER")
        self.assertEqual(derKey, self.rsaPublicKeyDER)

    def testExportKey3(self):
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        pemKey = key.export_key("PEM")
        self.assertEqual(pemKey, b(self.rsaKeyPEM))

    def testExportKey4(self):
        key = RSA.construct([self.n, self.e])
        pemKey = key.export_key("PEM")
        self.assertEqual(pemKey, b(self.rsaPublicKeyPEM))

    def testExportKey5(self):
        key = RSA.construct([self.n, self.e])
        openssh_1 = key.export_key("OpenSSH").split()
        openssh_2 = self.rsaPublicKeyOpenSSH.split()
        self.assertEqual(openssh_1[0], openssh_2[0])
        self.assertEqual(openssh_1[1], openssh_2[1])

    def testExportKey7(self):
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        derKey = key.export_key("DER", pkcs=8)
        self.assertEqual(derKey, self.rsaKeyDER8)

    def testExportKey8(self):
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        pemKey = key.export_key("PEM", pkcs=8)
        self.assertEqual(pemKey, b(self.rsaKeyPEM8))

    def testExportKey9(self):
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        self.assertRaises(ValueError, key.export_key, "invalid-format")

    def testExportKey10(self):
        # Export and re-import the encrypted key. It must match.
        # PEM envelope, PKCS#1, old PEM encryption
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        outkey = key.export_key('PEM', 'test')
        self.assertTrue(tostr(outkey).find('4,ENCRYPTED') != -1)
        self.assertTrue(tostr(outkey).find('BEGIN RSA PRIVATE KEY') != -1)
        inkey = RSA.importKey(outkey, 'test')
        self.assertEqual(key.n, inkey.n)
        self.assertEqual(key.e, inkey.e)
        self.assertEqual(key.d, inkey.d)

    def testExportKey11(self):
        # Export and re-import the encrypted key. It must match.
        # PEM envelope, PKCS#1, old PEM encryption
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        outkey = key.export_key('PEM', 'test', pkcs=1)
        self.assertTrue(tostr(outkey).find('4,ENCRYPTED') != -1)
        self.assertTrue(tostr(outkey).find('BEGIN RSA PRIVATE KEY') != -1)
        inkey = RSA.importKey(outkey, 'test')
        self.assertEqual(key.n, inkey.n)
        self.assertEqual(key.e, inkey.e)
        self.assertEqual(key.d, inkey.d)

    def testExportKey12(self):
        # Export and re-import the encrypted key. It must match.
        # PEM envelope, PKCS#8, old PEM encryption
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        outkey = key.export_key('PEM', 'test', pkcs=8)
        self.assertTrue(tostr(outkey).find('4,ENCRYPTED') != -1)
        self.assertTrue(tostr(outkey).find('BEGIN PRIVATE KEY') != -1)
        inkey = RSA.importKey(outkey, 'test')
        self.assertEqual(key.n, inkey.n)
        self.assertEqual(key.e, inkey.e)
        self.assertEqual(key.d, inkey.d)

    def testExportKey13(self):
        # Export and re-import the encrypted key. It must match.
        # PEM envelope, PKCS#8, PKCS#8 encryption
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        outkey = key.export_key(
            'PEM',
            'test',
            pkcs=8,
            protection='PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC')
        self.assertTrue(tostr(outkey).find('4,ENCRYPTED') == -1)
        self.assertTrue(
            tostr(outkey).find('BEGIN ENCRYPTED PRIVATE KEY') != -1)
        inkey = RSA.importKey(outkey, 'test')
        self.assertEqual(key.n, inkey.n)
        self.assertEqual(key.e, inkey.e)
        self.assertEqual(key.d, inkey.d)

    def testExportKey14(self):
        # Export and re-import the encrypted key. It must match.
        # DER envelope, PKCS#8, PKCS#8 encryption
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        outkey = key.export_key('DER', 'test', pkcs=8)
        inkey = RSA.importKey(outkey, 'test')
        self.assertEqual(key.n, inkey.n)
        self.assertEqual(key.e, inkey.e)
        self.assertEqual(key.d, inkey.d)

    def testExportKey15(self):
        # Verify that that error an condition is detected when trying to
        # use a password with DER encoding and PKCS#1.
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        self.assertRaises(ValueError, key.export_key, 'DER', 'test', 1)

    def test_import_key(self):
        """Verify that import_key is an alias to importKey"""
        key = RSA.import_key(self.rsaPublicKeyDER)
        self.assertFalse(key.has_private())
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)

    def test_import_key_ba_mv(self):
        """Verify that import_key can be used on bytearrays and memoryviews"""
        key = RSA.import_key(bytearray(self.rsaPublicKeyDER))
        key = RSA.import_key(memoryview(self.rsaPublicKeyDER))

    def test_exportKey(self):
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        self.assertEqual(key.export_key(), key.exportKey())
    def _exercise_public_primitive(self, rsaObj):
        plaintext = a2b_hex(self.plaintext)

        # Test encryption (2 arguments)
        new_ciphertext2 = rsaObj._encrypt(bytes_to_long(plaintext))
Exemplo n.º 25
0
    def _exercise_public_primitive(self, rsaObj):
        plaintext = a2b_hex(self.plaintext)

        # Test encryption (2 arguments)
        new_ciphertext2 = rsaObj._encrypt(bytes_to_long(plaintext))
Exemplo n.º 26
0
 def test_construct_5tuple(self):
     """DSA (default implementation) constructed key (5-tuple)"""
     (y, g, p, q, x) = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q, self.x)]
     dsaObj = self.dsa.construct((y, g, p, q, x))
     self._test_signing(dsaObj)
     self._test_verification(dsaObj)
Exemplo n.º 27
0
 def _test_verification(self, dsaObj):
     m_hash = bytes_to_long(a2b_hex(self.m_hash))
     r = bytes_to_long(a2b_hex(self.r))
     s = bytes_to_long(a2b_hex(self.s))
     self.failUnless(dsaObj._verify(m_hash, (r, s)))
     self.failIf(dsaObj._verify(m_hash + 1, (r, s)))
Exemplo n.º 28
0
 def _test_verification(self, dsaObj):
     m_hash = bytes_to_long(a2b_hex(self.m_hash))
     r = bytes_to_long(a2b_hex(self.r))
     s = bytes_to_long(a2b_hex(self.s))
     self.failUnless(dsaObj._verify(m_hash, (r, s)))
     self.failIf(dsaObj._verify(m_hash + 1, (r, s)))
Exemplo n.º 29
0
 def _test_verification(self, dsaObj):
     m_hash = bytes_to_long(a2b_hex(self.m_hash))
     r = bytes_to_long(a2b_hex(self.r))
     s = bytes_to_long(a2b_hex(self.s))
     self.assertTrue(dsaObj._verify(m_hash, (r, s)))
     self.assertFalse(dsaObj._verify(m_hash + 1, (r, s)))