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)
示例#2
0
    def decrypt_store_message(self, encrypted_message):
        key = self.private_key
        if not key.startswith("-----BEGIN RSA PRIVATE KEY-----"):
            key = "-----BEGIN RSA PRIVATE KEY-----\n" + key + "\n-----END RSA PRIVATE KEY-----"
        key = RSA.importKey(key)
        entc_list = []
        i = 0
        for x in (key.size_in_bytes(), 16, 16, -1):
            if i == 3:
                entc_list.append(message)
            else:
                entc_list.append(message[:x])
            i += 1
            message = message[x:]
        enc_session_key, nonce, tag, ciphertext = entc_list
        # Decrypt the session key with the private RSA key

        cipher_rsa = PKCS1_OAEP.new(key)
        session_key = cipher_rsa.decrypt(enc_session_key)

        # Decrypt the data with the AES session key
        cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
        encoded_message = cipher_aes.decrypt_and_verify(ciphertext, tag)
        decoded_message = encoded_message.decode("utf-8")

        # add to log and return
        self.log_messages.append(decoded_message)
        return decoded_message
 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 decrypt(self, ciphertext, keyfile=os.path.expanduser('KEY_FILES/SimulatorNew.pem')):

        input = open(keyfile)
        key = RSA.importKey(input.read())
        input.close()
        cipher = PKCS1_v1_5.new(key)
        plaintext = cipher.decrypt(ciphertext, None)
        return plaintext
示例#5
0
 def testVerify1(self):
     for test in self._testData:
         # Build the key
         key = RSA.importKey(test[0])
         # The real test
         cipher = PKCS.new(key)
         pt = cipher.decrypt(t2b(test[2]), "---")
         self.assertEqual(pt, b(test[1]))
 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 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 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 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 main():
    """主函数"""
    # 生成密钥对
    key_pair = RSA.generate(1024)
    # 导入公钥
    pub_key = RSA.importKey(key_pair.publickey().exportKey())
    # 导入私钥
    pri_key = RSA.importKey(key_pair.exportKey())
    message1 = 'hello, world!'
    # 加密数据
    data = pub_key.encrypt(message1.encode(), None)
    # 对加密数据进行BASE64编码
    message2 = base64.b64encode(data[0])
    print(message2)
    # 对加密数据进行BASE64解码
    data = base64.b64decode(message2)
    # 解密数据
    message3 = pri_key.decrypt(data)
    print(message3.decode())
 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)
示例#12
0
    def runTest(self):
        key = RSA.importKey(PKCS1_15_NoParams.rsakey)
        hashed = SHA1.new(b("Test"))
        good_signature = PKCS1_v1_5.new(key).sign(hashed)
        verifier = PKCS1_v1_5.new(key.publickey())

        self.assertEqual(verifier.verify(hashed, good_signature), True)

        # Flip a few bits in the signature
        bad_signature = strxor(good_signature, bchr(1) * len(good_signature))
        self.assertEqual(verifier.verify(hashed, bad_signature), False)
 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 test_x509v3(self):

        # Sample V3 certificate with a 1024 bit RSA key
        x509_v3_cert = """
-----BEGIN CERTIFICATE-----
MIIEcjCCAlqgAwIBAgIBATANBgkqhkiG9w0BAQsFADBhMQswCQYDVQQGEwJVUzEL
MAkGA1UECAwCTUQxEjAQBgNVBAcMCUJhbHRpbW9yZTEQMA4GA1UEAwwHVGVzdCBD
QTEfMB0GCSqGSIb3DQEJARYQdGVzdEBleGFtcGxlLmNvbTAeFw0xNDA3MTIwOTM1
MTJaFw0xNzA0MDcwOTM1MTJaMEQxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJNRDES
MBAGA1UEBwwJQmFsdGltb3JlMRQwEg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pWJ6vvRUbRiNRo
9cIbt/ya9Y9u0Ja8GLXv6dwX0l0IdJMkL8KifXUFAVCujp1FBrr/gdmwQn8itANy
+qbnWSxmOvtaY0zcaFAcONuHva0h51/WqXOMO1eb8PhR4HIIYU8p1oBwQp7dSni8
THDi1F+GG5PsymMDj5cWK42f+QzjVw5PrVmFqqrrEoMlx8DWh5Y=
-----END CERTIFICATE-----
""".strip()

        # RSA public key as dumped by openssl
        exponent = 65537
        modulus_str = """
00:fd:2e:c6:25:5d:8e:70:57:72:34:c4:38:2b:be:
4a:ad:81:6d:30:49:f7:56:71:05:74:f1:da:8f:24:
b7:ed:79:4c:c5:28:74:a1:2e:06:79:31:95:50:22:
48:9e:5e:42:a6:cb:fc:59:07:61:d3:71:5f:78:e7:
6f:ce:9e:48:67:8e:8e:72:37:8e:3e:25:a7:9a:38:
25:d8:6e:63:ed:ed:9b:0c:7e:d1:49:c8:46:57:e3:
83:e8:56:f5:02:0b:ee:bb:6f:fd:8b:2f:1f:75:fd:
eb:3d:0f:fb:78:07:5d:cc:a5:2b:cf:06:9c:55:b9:
d6:fa:d8:36:42:d4:97:29:17
        """
        modulus = int(re.sub("[^0-9a-f]", "", modulus_str), 16)

        key = RSA.importKey(x509_v3_cert)
        self.assertEqual(key.e, exponent)
        self.assertEqual(key.n, modulus)
        self.assertFalse(key.has_private())
 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)
示例#16
0
    def encrypt_message(self, plaintext, public_key):
        if not public_key.startswith("-----BEGIN RSA PUBLIC KEY-----"):
            public_key = "-----BEGIN RSA PUBLIC KEY-----\n" + public_key + "\n-----END RSA PUBLIC KEY-----"
        recipient_key = RSA.importKey(public_key)
        session_key = get_random_bytes(16)

        # Encrypt the session key with the public RSA key
        cipher_rsa = PKCS1_OAEP.new(recipient_key)
        enc_session_key = cipher_rsa.encrypt(session_key)

        # Encrypt the data with the AES session key
        cipher_aes = AES.new(session_key, AES.MODE_EAX)
        ciphertext, tag = cipher_aes.encrypt_and_digest(
            plaintext.encode("UTF-8"))
        encrypted_message = b"".join(
            [x for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext)])
        return encrypted_message
示例#17
0
    def testEncrypt1(self):
        for test in self._testData:
            # Build the key
            key = RSA.importKey(test[0])

            # RNG that takes its random numbers from a pool given
            # at initialization
            class randGen:
                def __init__(self, data):
                    self.data = data
                    self.idx = 0

                def __call__(self, N):
                    r = self.data[self.idx:self.idx + N]
                    self.idx += N
                    return r

            # The real test
            cipher = PKCS.new(key, randfunc=randGen(t2b(test[3])))
            ct = cipher.encrypt(b(test[1]))
            self.assertEqual(ct, t2b(test[2]))
    def test_x509v1(self):

        # Sample V1 certificate with a 1024 bit RSA key
        x509_v1_cert = """
-----BEGIN CERTIFICATE-----
MIICOjCCAaMCAQEwDQYJKoZIhvcNAQEEBQAwfjENMAsGA1UEChMEQWNtZTELMAkG
A1UECxMCUkQxHDAaBgkqhkiG9w0BCQEWDXNwYW1AYWNtZS5vcmcxEzARBgNVBAcT
Ck1ldHJvcG9saXMxETAPBgNVBAgTCE5ldyBZb3JrMQswCQYDVQQGEwJVUzENMAsG
A1UEAxMEdGVzdDAeFw0xNDA3MTExOTU3MjRaFw0xNzA0MDYxOTU3MjRaME0xCzAJ
BgNVBAYTAlVTMREwDwYDVQQIEwhOZXcgWW9yazENMAsGA1UEChMEQWNtZTELMAkG
A1UECxMCUkQxDzANBgNVBAMTBmxhdHZpYTCBnzANBgkqhkiG9w0BAQEFAAOBjQAw
gYkCgYEAyG+kytdRj3TFbRmHDYp3TXugVQ81chew0qeOxZWOz80IjtWpgdOaCvKW
NCuc8wUR9BWrEQW+39SaRMLiQfQtyFSQZijc3nsEBu/Lo4uWZ0W/FHDRVSvkJA/V
Ex5NL5ikI+wbUeCV5KajGNDalZ8F1pk32+CBs8h1xNx5DyxuEHUCAwEAATANBgkq
hkiG9w0BAQQFAAOBgQCVQF9Y//Q4Psy+umEM38pIlbZ2hxC5xNz/MbVPwuCkNcGn
KYNpQJP+JyVTsPpO8RLZsAQDzRueMI3S7fbbwTzAflN0z19wvblvu93xkaBytVok
9VBAH28olVhy9b1MMeg2WOt5sUEQaFNPnwwsyiY9+HsRpvpRnPSQF+kyYVsshQ==
-----END CERTIFICATE-----
        """.strip()

        # RSA public key as dumped by openssl
        exponent = 65537
        modulus_str = """
00:c8:6f:a4:ca:d7:51:8f:74:c5:6d:19:87:0d:8a:
77:4d:7b:a0:55:0f:35:72:17:b0:d2:a7:8e:c5:95:
8e:cf:cd:08:8e:d5:a9:81:d3:9a:0a:f2:96:34:2b:
9c:f3:05:11:f4:15:ab:11:05:be:df:d4:9a:44:c2:
e2:41:f4:2d:c8:54:90:66:28:dc:de:7b:04:06:ef:
cb:a3:8b:96:67:45:bf:14:70:d1:55:2b:e4:24:0f:
d5:13:1e:4d:2f:98:a4:23:ec:1b:51:e0:95:e4:a6:
a3:18:d0:da:95:9f:05:d6:99:37:db:e0:81:b3:c8:
75:c4:dc:79:0f:2c:6e:10:75
        """
        modulus = int(re.sub("[^0-9a-f]", "", modulus_str), 16)

        key = RSA.importKey(x509_v1_cert)
        self.assertEqual(key.e, exponent)
        self.assertEqual(key.n, modulus)
        self.assertFalse(key.has_private())
示例#19
0
 def runTest(self):
     verifier = pkcs1_15.new(RSA.importKey(self.rsakey))
     hashed = SHA1.new(self.msg)
     verifier.verify(hashed, self.signature)
 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)
示例#21
0
import crypto
import sys

sys.modules['Crypto'] = crypto
from crypto.PublicKey import RSA
from crypto.Hash import SHA

signature = int(open('sig', 'rb').read().hex(), 16)
print(signature)
pubkey = RSA.importKey(open('key.pub').read())
from Crypto.PublicKey import RSA
print("{:0128x}".format(pow(signature, pubkey.e, pubkey.n)))
print(SHA.new(b"CSE 127 rul3z!").hexdigest())
 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)  # failIf
     self.assertEqual(key.n, self.n)
     self.assertEqual(key.e, self.e)
 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 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)  # failIf
     self.assertEqual(key.n, self.n)
     self.assertEqual(key.e, self.e)
 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)
示例#26
0
import math
import time


def roundup(x):
    return int(math.ceil(x / 10.0)) * 10


cid = sys.argv[1]
SERVER = sys.argv[2]
PORT = sys.argv[3]
BYZANTINE = sys.argv[4]

key = False
with open("keys.pem", "r") as myfile:
    key = RSA.importKey(myfile.read())

public_key = key.publickey()
verifier = PKCS1_v1_5.new(public_key)

client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

intro = "REGISTER_REQUEST " + str(cid)
intro = intro.encode()

client.sendto(intro, (SERVER, int(PORT)))

response, address = client.recvfrom(1024)
neighbors = pickle.loads(response)
print(neighbors)
 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)