Ejemplo n.º 1
0
def rsa_public_from_der_certificate(certificate):
    # Extract subject_public_key_info field from X.509 certificate (see RFC3280)
    try:
        # try to extract pubkey from scapy.layers.x509 X509Cert type in case
        # der_certificate is of type X509Cert
        # Note: der_certificate may not be of type X509Cert if it wasn't
        # received completely, in that case, we'll try to extract it anyway
        # using the old method.
        # TODO: get rid of the old method and always expect X509Cert obj ?
        return RSA.importKey(str(certificate.tbsCertificate.subjectPublicKeyInfo))
    except AttributeError:
        pass

    # Fallback method, may pot. allow to extract pubkey from incomplete der streams
    cert = DerSequence()
    cert.decode(certificate)

    tbs_certificate = DerSequence()
    tbs_certificate.decode(cert[0])       # first DER SEQUENCE

    # search for pubkey OID: rsaEncryption: "1.2.840.113549.1.1.1"
    # hex: 06 09 2A 86 48 86 F7 0D 01 01 01
    subject_public_key_info = None
    for seq in tbs_certificate:
        if not isinstance(seq, basestring):
            continue     # skip numerics and non sequence stuff
        if "\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01" in seq:
            subject_public_key_info = seq

    if subject_public_key_info is None:
        raise ValueError("could not find OID rsaEncryption 1.2.840.113549.1.1.1 in certificate")

    # Initialize RSA key
    return RSA.importKey(subject_public_key_info)
Ejemplo n.º 2
0
 def from_key(cls, key, config, private_key=None):
     identity = cls(None, None, config)
     identity._keypair = (
         RSA.importKey(key),
         RSA.importKey(private_key) if private_key else None,
     )
     identity.state = IdentityState.INITIALIZED
     return identity
Ejemplo n.º 3
0
    def _load_key(self):
        # load private key
        content = self._app_private_key_string
        if not content:
            with open(self._app_private_key_path) as fp:
                content = fp.read()
        self._app_private_key = RSA.importKey(content)

        # load public key
        content = self._alipay_public_key_string
        if not content:
            with open(self._alipay_public_key_path) as fp:
                content = fp.read()
        self._alipay_public_key = RSA.importKey(content)
 def setUp(self):
     self.pem_priv_key = """-----BEGIN PRIVATE KEY-----
     MIIEwAIBADANBgkqhkiG9w0BAQEFAASCBKowggSmAgEAAoIBAQDDLrmt4lKRpm6P
     2blptwJsa1EBuxuuAayLjwNqKGvm5c1CAUEa/NtEpUMM8WYKRDwxzakUIGI/BdP3
     NOEMphcs5+OekgJLhzoSdtAIrXPy8JIidENZE6FzCJ2b6fHU5O4hoNvv1Bx5yoZr
     HVaWJIZMRRocJJ0Nf9oMaU8IE6m6OdBzQHEwcnL2/a8Q3VxstHufzjILmaZD9WL+
     6AESlQMKZPNQ+Xd7d4nvnVkY4ZV46tA+KvADGuotgovQwG+uiyQoGRrQUms21vHF
     zIvd3G9OCiyCTCHSyfsE3g7tks33NZ8O8gF8xa9OmU9TQPwwAyUr6JQXz0CW77o7
     Cr9LpHuNAgMBAAECggEBAJRbMbtfqc8XqDYjEfGur2Lld19Pb0yl7RbvD3NjYhDR
     X2DqPyhaRfg5fWubGSp4jyBz6C5qJwMsVN80DFNm83qoj7T52lC6aoOaV6og3V8t
     SIZzxLUyXKdpRxM5kR13HSHmeQYkPbi9HcrRM/1PqdzTMXNuyQl3wq9oZDAJchsf
     fmoh080htkaxhEb1bMXa2Lj7j2OIkHOsQeIu6BdbxIKRPIT+zrcklE6ocW8fTWAS
     Qi3IZ1FYLL+fs6TTxjx0VkC8QLaxWxY0pqTiwS7ndZiZKc3l3ARuvRk8buP+X3Jg
     BD86FQ18OXZC9boMbDbzv2cOLtdkq5pS3lJE4F9gjYECgYEA69ukU2pNWot2OPwK
     PuPwAXWNrvnvFzQgIc0qOiCmgKJU6wqunlop4Bx5XmetHExVyJVBEhaHoDr0F3Rs
     gt8IclKDsWGXoVcgfu3llMimiZ05hOf/XtcGTCZwZenMQ30cFh4ZRuUu7WCZ9tqO
     28P8jCXB3IcaRpRnNvVvmCr5NXECgYEA09nUzRW993SlohceRW2C9fT9HZ4BaPWO
     5wVlnoo5mlUfAyzl+AGT/WlKmrn/1gAHIznQJ8ZIABQvPaBXhvkANXZP5Ie0lObw
     jA7qFuKt7yV4GGlDnU1MOLh+acABMQBGSx8BJDaomH7glTiPEPTZjoP6wfAsd1uv
     Knjt7jH2ad0CgYEAx9ghknRd+rx0fbBBVix4riPW20324ihOmZVnlD0aF6B0Z3tz
     ncUz+irmQ7GBIpsjjIO60QK6BHAvZrhFQVaNp6B26ZORkSlr5WDZyImDYtMPa6fP
     36I+OcPQNOo3I3Acnjj+ne2PJ59Ula92oIudr3pGmv72qpsQIacw2TSAWGECgYEA
     sdNAN+HPMn68ZaGoLDjvW8uIB6tQnay5hhvWn8yA65YV0RGH+7Q/Z9BQ6i3EnPor
     A5uMqUZbu4011jHYJpiuXzHvf/GVWAO92KLQReOCgqHd/Aen1MtEdrwOiG+90Ebd
     ukLNL3ud61tc4oS2OlJ8p48LFm2mtY3FLA6UEYPoxhUCgYEAtsfWIGnBh7XC+HwI
     2higSgN92VpJHSPOyOi0aG/u5AEQ+fsCUIi3KakxzvmiGMAEvWItkKyz2Gu8smtn
     2HVsGxI5UW7aLw9s3qe8kyMSfUk6pGamVhJUQmDr77+5zEzykPBxwGwDwdeR43CR
     xVgf/Neb/avXgIgi6drj8dp1fWA=
     -----END PRIVATE KEY-----
             """
     self.rsa = RSA.importKey(self.pem_priv_key)
Ejemplo n.º 5
0
 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)
Ejemplo n.º 6
0
    def read(self):
        if self.state == IdentityState.INITIALIZING:
            raise IdentityStateError()

        if not os.path.exists(self.id_rsa_path) or not os.path.exists(
            self.id_rsa_pub_path
        ):
            self.state = IdentityState.UNINITIALIZED
            raise IdentityNotInitialized()

        with open(self.id_rsa_pub_path, "rb") as id_rsa_pub:
            public_key = RSA.importKey(id_rsa_pub.read())
        with open(self.id_rsa_path, "rb") as id_rsa:
            private_key = RSA.importKey(id_rsa.read())
        self._keypair = (public_key, private_key)
        self.state = IdentityState.INITIALIZED
Ejemplo n.º 7
0
 def sign_transaction(self, sender, recipient, amount):
     signer = PKCS1_v1_5.new(RSA.importKey(
         binascii.unhexlify(self.private_key)))
     h = SHA256.new((str(sender) + str(recipient) +
                     str(amount)).encode('utf8'))
     signature = signer.sign(h)
     return binascii.hexlify(signature).decode('ascii')
Ejemplo n.º 8
0
 def importKey(self, key, passphrase):
     passphrase = self.getProcessedPassphrase(passphrase)
     try:
         self.key = RSA.importKey(key, passphrase)
     except ValueError:
         raise ValueError(u"Wrong current password")
     return self.key
Ejemplo n.º 9
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]))
Ejemplo n.º 10
0
 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)
Ejemplo n.º 11
0
def test_dj_usage():
    key_string = open(full_path("./size2048.key"), 'r').read()
    key = RSA.importKey(key_string)
    payload = "Please take a moment to register today"
    keys = [RSAKey(key=key, kid=md5(key_string.encode('utf-8')).hexdigest())]
    _jws = JWS(payload, alg='RS256')
    sjwt = _jws.sign_compact(keys)
    _jwt = factory(sjwt)
    assert _jwt.jwt.headers['alg'] == 'RS256'
Ejemplo n.º 12
0
 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)
Ejemplo n.º 13
0
 def testImportKey1(self):
     """Verify import of RSAPrivateKey DER SEQUENCE"""
     key = RSA.importKey(self.rsaKeyDER)
     self.failUnless(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)
Ejemplo n.º 14
0
 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)
Ejemplo n.º 15
0
def test_import_rsa_key():
    _ckey = RSA.importKey(open(full_path(KEY), 'r').read())
    assert isinstance(_ckey, RsaKey)
    djwk = jwk_wrap(_ckey).to_dict()
    print(djwk)
    assert _eq(djwk.keys(), ["kty", "e", "n", "p", "q", "d"])
    assert djwk[
               "n"] == '5zbNbHIYIkGGJ3RGdRKkYmF4gOorv5eDuUKTVtuu3VvxrpOWvwnFV-NY0LgqkQSMMyVzodJE3SUuwQTUHPXXY5784vnkFqzPRx6bHgPxKz7XfwQjEBTafQTMmOeYI8wFIOIHY5i0RWR-gxDbh_D5TXuUqScOOqR47vSpIbUH-nc'
    assert djwk['e'] == 'AQAB'
Ejemplo n.º 16
0
 def testImportKey10(self):
     """Verify import of unencrypted PrivateKeyInfo DER SEQUENCE, encoded with PEM"""
     key = RSA.importKey(self.rsaKeyPEM8)
     self.failUnless(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)
Ejemplo n.º 17
0
def get_rsa_b64_from_der(public_key_der: bytes) -> bytes:
    """Get base64 encoded RSA from public key DER sequence"""
    public_key_rsa = RSA.importKey(public_key_der)
    rsa_bytes_n = Cryptodome.Util.number.long_to_bytes(public_key_rsa.n)
    rsa_bytes_e = Cryptodome.Util.number.long_to_bytes(public_key_rsa.e)
    keydata = bytearray()
    keydata.append(len(rsa_bytes_e))
    keydata.extend(rsa_bytes_e)
    keydata.extend(rsa_bytes_n)
    return base64.b64encode(keydata)
Ejemplo n.º 18
0
 def testImportKey8(self):
     """Verify import of encrypted PrivateKeyInfo DER SEQUENCE"""
     for t in self.rsaKeyEncryptedPEM:
         key = RSA.importKey(t[1], t[0])
         self.failUnless(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)
Ejemplo n.º 19
0
def der2rsa(der):
    # Extract subjectPublicKeyInfo field from X.509 certificate (see RFC3280)
    cert = DerSequence()
    cert.decode(der)
    tbs_certificate = DerSequence()
    tbs_certificate.decode(cert[0])
    subject_public_key_info = tbs_certificate[6]

    # Initialize RSA key
    return RSA.importKey(subject_public_key_info)
    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)
Ejemplo n.º 21
0
 def __generate_key_id(rsa_key):
     """
     Generates a key id to be used in JWE + JWT. It is based on the digest
     of the key.
     :param rsa_key: RSA private key in string format
     :return:
     """
     key = RSA.importKey(rsa_key)
     md5digest = md5(key.publickey().exportKey('DER')).hexdigest()
     return ":".join(
         md5digest[i:i + 2] for i in range(0, len(md5digest), 2))
Ejemplo n.º 22
0
 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.failUnless(tostr(outkey).find('4,ENCRYPTED')!=-1)
     self.failUnless(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)
Ejemplo n.º 23
0
 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.failUnless(tostr(outkey).find('4,ENCRYPTED')==-1)
     self.failUnless(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)
Ejemplo n.º 24
0
    def test_x509v3(self):

        # Sample V3 certificate with a 1024 bit RSA key
        x509_v3_cert = """
-----BEGIN CERTIFICATE-----
MIIEcjCCAlqgAwIBAgIBATANBgkqhkiG9w0BAQsFADBhMQswCQYDVQQGEwJVUzEL
MAkGA1UECAwCTUQxEjAQBgNVBAcMCUJhbHRpbW9yZTEQMA4GA1UEAwwHVGVzdCBD
QTEfMB0GCSqGSIb3DQEJARYQdGVzdEBleGFtcGxlLmNvbTAeFw0xNDA3MTIwOTM1
MTJaFw0xNzA0MDcwOTM1MTJaMEQxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJNRDES
MBAGA1UEBwwJQmFsdGltb3JlMRQwEgYDVQQDDAtUZXN0IFNlcnZlcjCBnzANBgkq
hkiG9w0BAQEFAAOBjQAwgYkCgYEA/S7GJV2OcFdyNMQ4K75KrYFtMEn3VnEFdPHa
jyS37XlMxSh0oS4GeTGVUCJInl5Cpsv8WQdh03FfeOdvzp5IZ46OcjeOPiWnmjgl
2G5j7e2bDH7RSchGV+OD6Fb1Agvuu2/9iy8fdf3rPQ/7eAddzKUrzwacVbnW+tg2
QtSXKRcCAwEAAaOB1TCB0jAdBgNVHQ4EFgQU/WwCX7FfWMIPDFfJ+I8a2COG+l8w
HwYDVR0jBBgwFoAUa0hkif3RMaraiWtsOOZZlLu9wJwwCQYDVR0TBAIwADALBgNV
HQ8EBAMCBeAwSgYDVR0RBEMwQYILZXhhbXBsZS5jb22CD3d3dy5leGFtcGxlLmNv
bYIQbWFpbC5leGFtcGxlLmNvbYIPZnRwLmV4YW1wbGUuY29tMCwGCWCGSAGG+EIB
DQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTANBgkqhkiG9w0BAQsF
AAOCAgEAvO6xfdsGbnoK4My3eJthodTAjMjPwFVY133LH04QLcCv54TxKhtUg1fi
PgdjVe1HpTytPBfXy2bSZbXAN0abZCtw1rYrnn7o1g2pN8iypVq3zVn0iMTzQzxs
zEPO3bpR/UhNSf90PmCsS5rqZpAAnXSaAy1ClwHWk/0eG2pYkhE1m1ABVMN2lsAW
e9WxGk6IFqaI9O37NYQwmEypMs4DC+ECJEvbPFiqi3n0gbXCZJJ6omDA5xJldaYK
Oa7KR3s/qjBsu9UAiWpLBuFoSTHIF2aeRKRFmUdmzwo43eVPep65pY6eQ4AdL2RF
rqEuINbGlzI5oQyYhu71IwB+iPZXaZZPlwjLgOsuad/p2hOgDb5WxUi8FnDPursQ
ujfpIpmrOP/zpvvQWnwePI3lI+5n41kTBSbefXEdv6rXpHk3QRzB90uPxnXPdxSC
16ASA8bQT5an/1AgoE3k9CrcD2K0EmgaX0YI0HUhkyzbkg34EhpWJ6vvRUbRiNRo
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.failIf(key.has_private())
Ejemplo n.º 25
0
    def encode(self, payload):
        """Encode the provided payload."""
        keys = KEYS()

        if self.asymmetric:
            keys.add(RSAKey(key=RSA.importKey(settings.JWT_PRIVATE_SIGNING_KEY)))
            algorithm = 'RS512'
        else:
            key = self.secret if self.secret else self.jwt_auth['JWT_SECRET_KEY']
            keys.add({'key': key, 'kty': 'oct'})
            algorithm = self.jwt_auth['JWT_ALGORITHM']

        data = json.dumps(payload)
        jws = JWS(data, alg=algorithm)
        return jws.sign_compact(keys=keys)
Ejemplo n.º 26
0
 def add_issuer_key(self, private_key):
     """
     Adds a private key to the list of keys available for decryption
     and signatures
     :return: Boolean - Whether the key is already in the list
     """
     new_key = RSAKey(key=import_rsa_key(private_key),
                      kid=self.__generate_key_id(private_key))
     for key in self.issuer_private_keys:
         if new_key.kid == key.kid:
             return False
     self.issuer_private_keys.append(new_key)
     self.loaded_issuer_private_keys[new_key.kid] = PKCS1_OAEP.new(
         RSA.importKey(private_key))
     return True
Ejemplo n.º 27
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]))
Ejemplo n.º 28
0
    def get(self, request, *args, **kwargs):
        dic = dict(keys=[])

        for rsakey in RSAKey.objects.all():
            public_key = RSA.importKey(rsakey.key).publickey()
            dic['keys'].append({
                'kty': 'RSA',
                'alg': 'RS256',
                'use': 'sig',
                'kid': rsakey.kid,
                'n': long_to_base64(public_key.n),
                'e': long_to_base64(public_key.e),
            })

        response = JsonResponse(dic)
        response['Access-Control-Allow-Origin'] = '*'

        return response
    def fromDict(self, msl_data):
        need_handshake = False
        rsa_key = None

        try:
            self.kodi_helper.log(msg='Parsing RSA Keys from Dict')
            self.encryption_key = base64.standard_b64decode(msl_data['encryption_key'])
            self.sign_key = base64.standard_b64decode(msl_data['sign_key'])
            rsa_key = base64.standard_b64decode(msl_data['rsa_key'])
            self.rsa_key = RSA.importKey(rsa_key)
        except:
            need_handshake = True

        if not rsa_key:
            need_handshake = True
            self.__init_generate_rsa_keys()

        if not (self.encryption_key and self.sign_key):
            need_handshake = True

        return need_handshake
    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.failIf(key.has_private())
Ejemplo n.º 31
0
    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.failIf(key.has_private())
Ejemplo n.º 32
0
def keys_load(privkey="privkey.der", pubkey="pubkey.der"):
    keyfile = "wallet.der"
    if os.path.exists("wallet.der"):
        print("Using modern wallet method")
        return keys_load_new("wallet.der")

    else:
        # print ("loaded",privkey, pubkey)
        # import keys
        try:  # unencrypted
            key = RSA.importKey(open(privkey).read())
            private_key_readable = key.exportKey().decode("utf-8")
            # public_key = key.publickey()
            encrypted = False
            unlocked = True

        except:  # encrypted
            encrypted = True
            unlocked = False
            key = None
            private_key_readable = open(privkey).read()

        # public_key_readable = str(key.publickey().exportKey())
        public_key_readable = open(pubkey.encode('utf-8')).read()

        if (len(public_key_readable)) != 271 and (
                len(public_key_readable)) != 799:
            raise ValueError("Invalid public key length: {}".format(
                len(public_key_readable)))

        public_key_hashed = base64.b64encode(
            public_key_readable.encode('utf-8'))
        address = hashlib.sha224(
            public_key_readable.encode('utf-8')).hexdigest()

        print("Upgrading wallet")
        keys_save(private_key_readable, public_key_readable, address, keyfile)

        return key, public_key_readable, private_key_readable, encrypted, unlocked, public_key_hashed, address, keyfile
Ejemplo n.º 33
0
    def __init__(self, secret, algorithm=None):
        if algorithm is None:
            algorithm = DEFAULT_SIGN_ALGORITHM

        assert algorithm in ALGORITHMS, "Unknown algorithm"
        if isinstance(secret, six.string_types):
            secret = secret.encode("ascii")

        self._rsa = None
        self._hash = None
        self.sign_algorithm, self.hash_algorithm = algorithm.split('-')

        if self.sign_algorithm == 'rsa':
            try:
                rsa_key = RSA.importKey(secret)
                self._rsa = PKCS1_v1_5.new(rsa_key)
                self._hash = HASHES[self.hash_algorithm]
            except ValueError:
                raise HttpSigException("Invalid key.")

        elif self.sign_algorithm == 'hmac':
            self._hash = HMAC.new(secret,
                                  digestmod=HASHES[self.hash_algorithm])
Ejemplo n.º 34
0
 def verify_bis_signature_raw(cls,
                              signature: bytes,
                              public_key: bytes,
                              buffer: bytes,
                              address: str = '') -> None:
     """Verify signature from bismuth tx bin stored format (b64 decoded)
     Returns None, but raises ValueError if needed."""
     # Will raise if does not match
     # TODO: Probably be better to use DER (bin) format there for rsa, instead of re-encode to PEM
     # However, if we want to check address... we need the PEM, see below.
     # move to ed25519 would free significant ressources.
     # pem = "-----BEGIN PUBLIC KEY-----\n" + b64encode(public_key).decode() + "\n-----END PUBLIC KEY-----"
     pem = cls.normalize_key(b64encode(public_key).decode())
     cls.validate_pem(pem)
     public_key_object = RSA.importKey(pem)
     verifier = PKCS1_v1_5.new(public_key_object)
     sha_hash = SHA.new(buffer)
     if not verifier.verify(sha_hash, signature):
         raise ValueError(f"Invalid signature from {address}")
     # Reconstruct address from pubkey to make sure it matches
     # print(address, pem, cls.public_key_to_address(pem))
     if address != cls.public_key_to_address(pem):
         raise ValueError("Attempt to spend from a wrong address")
Ejemplo n.º 35
0
def public_key_encrypt(plaintext, key):
    if not isinstance(plaintext, bytes):
        serial_pt = b'\1' + pickle.dumps(plaintext)
    else:
        serial_pt = b'\0' + plaintext
    alg = key['alg']
    k = key['key']
    if alg == 'rsa':
        pubk = RSA.importKey(k)
        oaep_cipher = PKCS1_OAEP.new(pubk)
        try:
            ciphertext = oaep_cipher.encrypt(serial_pt)
        except ValueError:  #Use Hybrid Encryption
            #print('**********: Using Hybrid Encryption!')
            shared_key = Random.new().read(32)
            iv = Random.new().read(16)
            sym_cipher = AES.new(shared_key, AES.MODE_CBC, iv)
            data_ct = sym_cipher.encrypt(pkcs7_pad(serial_pt))
            key_ct = oaep_cipher.encrypt(shared_key)
            ciphertext = key_ct + iv + data_ct
        return ciphertext
    else:
        print('SA_ERROR:', alg, 'not yet implemented.', flush=True)
Ejemplo n.º 36
0
    def __init__(self,
                 appid,
                 app_notify_url,
                 app_private_key_path,
                 alipay_public_key_path,
                 return_url,
                 debug=False):
        self.appid = appid
        self.app_notify_url = app_notify_url
        self.app_private_key_path = app_private_key_path
        self.app_private_key = None
        self.return_url = return_url
        with open(self.app_private_key_path) as fp:
            self.app_private_key = RSA.importKey(fp.read())

        self.alipay_public_key_path = alipay_public_key_path
        with open(self.alipay_public_key_path) as fp:
            self.alipay_public_key = RSA.import_key(fp.read())

        if debug is True:
            self.__gateway = "https://openapi.alipaydev.com/gateway.do"
        else:
            self.__gateway = "https://openapi.alipay.com/gateway.do"
Ejemplo n.º 37
0
    def verify_this():
        try:
            received_public_key = RSA.importKey(public_key_gui.get("1.0", END))
            verifier = PKCS1_v1_5.new(received_public_key)
            h = SHA.new(input_text.get("1.0", END).encode("utf-8"))
            received_signature_dec = base64.b64decode(output_signature.get("1.0", END))

            if verifier.verify(h, received_signature_dec):
                top2 = Toplevel()
                top2.title("Validation results")
                msg = Message(top2, text="Signature Valid", width=50)
                msg.pack()
                button = Button(top2, text="Dismiss", command=top2.destroy)
                button.pack()
            else:
                raise
        except:
            top2 = Toplevel()
            top2.title("Validation results")
            msg = Message(top2, text="Signature Invalid", width=50)
            msg.pack()
            button = Button(top2, text="Dismiss", command=top2.destroy)
            button.pack()
Ejemplo n.º 38
0
def main():
    import array
    from Cryptodome.PublicKey import RSA
    from Cryptodome.Util.number import long_to_bytes

    args = get_args()

    with open(args.key, 'r') as f:
        key = RSA.importKey(f.read())

    # Refuse public exponent with more than 32 bits. Otherwise the C
    # compiler may simply truncate the value and proceed.
    # This will lead to TAs seemingly having invalid signatures with a
    # possible security issue for any e = k*2^32 + 1 (for any integer k).
    if key.publickey().e > 0xffffffff:
        raise ValueError(
            'Unsupported large public exponent detected. ' +
            'OP-TEE handles only public exponents up to 2^32 - 1.')

    with open(args.out, 'w') as f:
        f.write("#include <stdint.h>\n")
        f.write("#include <stddef.h>\n\n")
        f.write("const uint32_t " + args.prefix + "_exponent = " +
                str(key.publickey().e) + ";\n\n")
        f.write("const uint8_t " + args.prefix + "_modulus[] = {\n")
        i = 0
        for x in array.array("B", long_to_bytes(key.publickey().n)):
            f.write("0x" + '{0:02x}'.format(x) + ",")
            i = i + 1
            if i % 8 == 0:
                f.write("\n")
            else:
                f.write(" ")
        f.write("};\n")
        f.write("const size_t " + args.prefix + "_modulus_size = sizeof(" +
                args.prefix + "_modulus);\n")
Ejemplo n.º 39
0
    def sigVerification(pubKey_fname, file):
        global signHex
        # Generating decrypted file's SHA-256

        h = SHA256.new()
        h.update(open(file, "r").read())

        # Reading public key to check signature with

        keyPair = RSA.importKey(open(pubKey_fname, "r").read())
        keyVerifier = PKCS1_v1_5.new(keyPair.publickey())

        # If signature is right, prints SHA-256. Otherwise states that the file is not authentic

        if keyVerifier.verify(h,
                              open(file.split('.')[0] + ".sig", "r").read()):
            # print "The signature is authentic."
            # print "SHA-256 -> %s" % h.hexdigest()
            signHex = h.hexdigest()
            # webbrowser.open_new('http://localhost:5000/signauth')

        else:
            # print "The signature is not authentic."
            return redirect("/error")
Ejemplo n.º 40
0
    def _encode_password(self,
                         password: Optional[str] = None) -> Optional[str]:
        """Encrypts the raw password into a form that Instagram accepts."""
        if not self.state.public_api_key:
            return
        if not any([password, self._raw_password]):
            return

        key = Random.get_random_bytes(32)
        iv = Random.get_random_bytes(12)
        time = int(datetime.datetime.now().timestamp())

        pubkey = base64.b64decode(self.state.public_api_key)

        rsa_key = RSA.importKey(pubkey)
        rsa_cipher = PKCS1_v1_5.new(rsa_key)
        encrypted_key = rsa_cipher.encrypt(key)

        aes = AES.new(key, AES.MODE_GCM, nonce=iv)
        aes.update(str(time).encode('utf-8'))

        encrypted_password, cipher_tag = aes.encrypt_and_digest(
            bytes(password or self._raw_password, 'utf-8'))

        encrypted = bytes([
            1,
            int(self.state.public_api_key_id), *list(iv),
            *list(struct.pack('<h', len(encrypted_key))), *list(encrypted_key),
            *list(cipher_tag), *list(encrypted_password)
        ])
        encrypted = base64.b64encode(encrypted).decode('utf-8')

        encrypted_password = f'#PWD_INSTAGRAM:4:{time}:{encrypted}'
        if password is not None:
            return encrypted_password
        self._encoded_password = encrypted_password
Ejemplo n.º 41
0
def public_key_import_from_x509_certificate_string(certificate_string):
    if certificate_string.find('-----BEGIN CERTIFICATE-----') \
            and not certificate_string.find('-----BEGIN CERTIFICATE-----\n') \
            and not certificate_string.find('-----BEGIN CERTIFICATE-----\r\n'):
        certificate_string = certificate_string.replace(
            '-----BEGIN CERTIFICATE-----', '-----BEGIN CERTIFICATE-----\n')
    if certificate_string.find('\n-----END CERTIFICATE-----') \
            and not certificate_string.find('\n-----END CERTIFICATE-----') \
            and not certificate_string.find('\r\n-----END CERTIFICATE-----'):
        certificate_string = certificate_string.replace(
            '-----END CERTIFICATE-----', '\n-----END CERTIFICATE-----')
    lines = certificate_string.replace(" ", '').split()
    der = a2b_base64(''.join(lines[1:-1]))

    # Extract subjectPublicKeyInfo field from X.509 certificate (see RFC3280)
    cert = DerSequence()
    cert.decode(der)
    tbs_certificate = DerSequence()
    tbs_certificate.decode(cert[0])
    subject_public_key_info = tbs_certificate[6]

    # Initialize RSA key
    public_key = RSA.importKey(subject_public_key_info)
    return public_key.publickey()
Ejemplo n.º 42
0
 def __init__(self, context_, hostAddress, dbaseLoc):
     '''
     Construct the dht  object.
     '''
     super().__init__(context_, dbaseLoc)
     global theDiscoBase
     theDiscoBase = self
     self.context = context_
     self.hostAddress = hostAddress
     self.root = dbaseLoc
     self.dht = None
     self.dhtPort = None
     self.updates = []
     self.updateLock = RLock()
     self.clients = {}
     self.listeners = {}
     self.riapsHome = os.getenv('RIAPSHOME', './')
     self.republisher = sched.scheduler(time.time, time.sleep)
     self.republishMap = {}
     self.republisherStart = threading.Event()
     self.republisherThread = threading.Thread(
         name='dhtRepublisher', target=self.dhtRepublishWorker, daemon=True)
     self.republisherStop = False
     self.republishLock = RLock()
     self.deletedMap = {}
     self.regDb = DhtBackup()
     self.private_key = None
     self.cipher_rsa = None
     if Config.SECURITY:
         private_key_name = join(self.riapsHome,
                                 "keys/" + str(const.ctrlPrivateKey))
         with open(private_key_name, 'rb') as f:
             key = f.read()
         self.private_key = RSA.importKey(key)
         self.cipher_rsa = PKCS1_OAEP.new(self.private_key)
     self.peerMon = None
    def load(self, wallet_file='wallet.der'):
        """
        Loads the wallet.der file

        :param wallet_file: string, a wallet file path
        """
        if self.verbose:
            print("Load", wallet_file)
        self._wallet_file = None
        self._address = None
        self._infos = {"address": '', 'file': wallet_file, 'encrypted': False}
        if not path.isfile(wallet_file):
            return

        self._wallet_file = wallet_file
        with open(wallet_file, 'r') as f:
            content = json.load(f)
            self._infos['address'] = content['Address']  # Warning case change!!!
            self._address = content['Address']
        try:
            self.key = RSA.importKey(content['Private Key'])
            self.public_key = content['Public Key']
        except:  # encrypted
            self._infos['encrypted'] = True
Ejemplo n.º 44
0
def RSADecrypt(privkey,
               ciphertext,
               passphrase=None,
               sentinel="ERROR",
               input="base64"):
    """RSA私钥解密

    :param privkey: str,bytes: pkcs1格式私钥

    :param ciphertext: str,bytes: 已加密的消息

    :param passphrase: str,bytes: 私钥保护的密码短语

    :param sentinel: any type: 检测到错误时返回的标记,默认返回ERROR字符串

    :param input: str: Input format: base64 (default) or hex (hexadecimal), refer to the output parameter of :func:`RSAEncrypt`

    :returns: str,unicode: 消息原文
    """
    privkey = RSA.importKey(privkey, passphrase=passphrase)
    ciphertext = a2b_hex(ciphertext) if input == "hex" else base64.b64decode(
        ciphertext)
    plaintext = PKCS1_v1_5.new(privkey).decrypt(ciphertext, sentinel)
    return plaintext
Ejemplo n.º 45
0
 def callback_public_key():
     if Client.cached_callback_public_key is None:
         f = open(COINBASE_CALLBACK_PUBLIC_KEY_PATH, 'r')
         Client.cached_callback_public_key = RSA.importKey(f.read())
     return Client.cached_callback_public_key
Ejemplo n.º 46
0
def import_rsa_key_from_file(filename, passphrase=None):
    return RSA.importKey(open(filename, 'r').read(), passphrase=passphrase)
Ejemplo n.º 47
0
import base64
import os.path
from pathlib import Path
from Cryptodome.PublicKey import RSA
from Cryptodome.Signature import PKCS1_v1_5
from Cryptodome.Hash import SHA256
from Cryptodome.Cipher import PKCS1_OAEP

ServerAddress = ("127.0.0.1", 5503)
#from ecdsa import VerifyingKey, BadSignatureError
#vk = VerifyingKey.from_pem(open("PublicKey.pem").read())

CertPath = str(Path(os.path.dirname(
    os.path.abspath(__file__))).parent) + "\\Certificate\\CA\\"

vk = RSA.importKey(open(CertPath + "PublicKeyRSACA3.pem").read())
sk = RSA.importKey(open(CertPath + "PrivateKeyRSACA3.pem").read())
decryptor = PKCS1_OAEP.new(sk)


class PKQueryRequestHandler(socketserver.DatagramRequestHandler):
    def handle(self):
        print("A query received. The Time in milliseconds: " +
              str(int(round(time.time() * 1000))))
        datagram = self.request[0]
        #print("The message in Ciphertext: ");
        #print(datagram.hex());
        decrypted = decryptor.decrypt(datagram)
        print("The message in plaintext: ")
        print(decrypted)
Ejemplo n.º 48
0
 def test_sign_message(self):
     key = RSA.importKey(PRIVKEY_DATA)
     with patch('salt.crypt.get_rsa_key', return_value=key):
         self.assertEqual(
             SIG, salt.crypt.sign_message('/keydir/keyname.pem', MSG))
Ejemplo n.º 49
0
def pem_cert2rsa(pem_file):
    # Convert from PEM to DER
    pem = open(pem_file).read()
    _rsa = RSA.importKey(pem)
    lines = pem.replace(" ", '').split()
    return der2rsa(a2b_base64(''.join(lines[1:-1])))
Ejemplo n.º 50
0
 def load_key(key_path: AnyStr):
     with open(key_path, 'r') as key:
         _key = RSA.importKey(key.read())
     return _key
Ejemplo n.º 51
0
    def _auth(self, load):
        '''
        Authenticate the client, use the sent public key to encrypt the AES key
        which was generated at start up.

        This method fires an event over the master event manager. The event is
        tagged "auth" and returns a dict with information about the auth
        event

        # Verify that the key we are receiving matches the stored key
        # Store the key if it is not there
        # Make an RSA key with the pub key
        # Encrypt the AES key as an encrypted salt.payload
        # Package the return and return it
        '''

        if not salt.utils.verify.valid_id(self.opts, load['id']):
            log.info(
                'Authentication request from invalid id {id}'.format(**load)
                )
            return {'enc': 'clear',
                    'load': {'ret': False}}
        log.info('Authentication request from {id}'.format(**load))

        # 0 is default which should be 'unlimited'
        if self.opts['max_minions'] > 0:
            # use the ConCache if enabled, else use the minion utils
            if self.cache_cli:
                minions = self.cache_cli.get_cached()
            else:
                minions = self.ckminions.connected_ids()
                if len(minions) > 1000:
                    log.info('With large numbers of minions it is advised '
                             'to enable the ConCache with \'con_cache: True\' '
                             'in the masters configuration file.')

            if not len(minions) <= self.opts['max_minions']:
                # we reject new minions, minions that are already
                # connected must be allowed for the mine, highstate, etc.
                if load['id'] not in minions:
                    msg = ('Too many minions connected (max_minions={0}). '
                           'Rejecting connection from id '
                           '{1}'.format(self.opts['max_minions'],
                                        load['id']))
                    log.info(msg)
                    eload = {'result': False,
                             'act': 'full',
                             'id': load['id'],
                             'pub': load['pub']}

                    if self.opts.get('auth_events') is True:
                        self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
                    return {'enc': 'clear',
                            'load': {'ret': 'full'}}

        # Check if key is configured to be auto-rejected/signed
        auto_reject = self.auto_key.check_autoreject(load['id'])
        auto_sign = self.auto_key.check_autosign(load['id'])

        pubfn = os.path.join(self.opts['pki_dir'],
                             'minions',
                             load['id'])
        pubfn_pend = os.path.join(self.opts['pki_dir'],
                                  'minions_pre',
                                  load['id'])
        pubfn_rejected = os.path.join(self.opts['pki_dir'],
                                      'minions_rejected',
                                      load['id'])
        pubfn_denied = os.path.join(self.opts['pki_dir'],
                                    'minions_denied',
                                    load['id'])
        if self.opts['open_mode']:
            # open mode is turned on, nuts to checks and overwrite whatever
            # is there
            pass
        elif os.path.isfile(pubfn_rejected):
            # The key has been rejected, don't place it in pending
            log.info('Public key rejected for {0}. Key is present in '
                     'rejection key dir.'.format(load['id']))
            eload = {'result': False,
                     'id': load['id'],
                     'pub': load['pub']}
            if self.opts.get('auth_events') is True:
                self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
            return {'enc': 'clear',
                    'load': {'ret': False}}

        elif os.path.isfile(pubfn):
            # The key has been accepted, check it
            with salt.utils.fopen(pubfn, 'r') as pubfn_handle:
                if pubfn_handle.read().strip() != load['pub'].strip():
                    log.error(
                        'Authentication attempt from {id} failed, the public '
                        'keys did not match. This may be an attempt to compromise '
                        'the Salt cluster.'.format(**load)
                    )
                    # put denied minion key into minions_denied
                    with salt.utils.fopen(pubfn_denied, 'w+') as fp_:
                        fp_.write(load['pub'])
                    eload = {'result': False,
                             'id': load['id'],
                             'act': 'denied',
                             'pub': load['pub']}
                    if self.opts.get('auth_events') is True:
                        self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
                    return {'enc': 'clear',
                            'load': {'ret': False}}

        elif not os.path.isfile(pubfn_pend):
            # The key has not been accepted, this is a new minion
            if os.path.isdir(pubfn_pend):
                # The key path is a directory, error out
                log.info(
                    'New public key {id} is a directory'.format(**load)
                )
                eload = {'result': False,
                         'id': load['id'],
                         'pub': load['pub']}
                if self.opts.get('auth_events') is True:
                    self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
                return {'enc': 'clear',
                        'load': {'ret': False}}

            if auto_reject:
                key_path = pubfn_rejected
                log.info('New public key for {id} rejected via autoreject_file'
                         .format(**load))
                key_act = 'reject'
                key_result = False
            elif not auto_sign:
                key_path = pubfn_pend
                log.info('New public key for {id} placed in pending'
                         .format(**load))
                key_act = 'pend'
                key_result = True
            else:
                # The key is being automatically accepted, don't do anything
                # here and let the auto accept logic below handle it.
                key_path = None

            if key_path is not None:
                # Write the key to the appropriate location
                with salt.utils.fopen(key_path, 'w+') as fp_:
                    fp_.write(load['pub'])
                ret = {'enc': 'clear',
                       'load': {'ret': key_result}}
                eload = {'result': key_result,
                         'act': key_act,
                         'id': load['id'],
                         'pub': load['pub']}
                if self.opts.get('auth_events') is True:
                    self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
                return ret

        elif os.path.isfile(pubfn_pend):
            # This key is in the pending dir and is awaiting acceptance
            if auto_reject:
                # We don't care if the keys match, this minion is being
                # auto-rejected. Move the key file from the pending dir to the
                # rejected dir.
                try:
                    shutil.move(pubfn_pend, pubfn_rejected)
                except (IOError, OSError):
                    pass
                log.info('Pending public key for {id} rejected via '
                         'autoreject_file'.format(**load))
                ret = {'enc': 'clear',
                       'load': {'ret': False}}
                eload = {'result': False,
                         'act': 'reject',
                         'id': load['id'],
                         'pub': load['pub']}
                if self.opts.get('auth_events') is True:
                    self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
                return ret

            elif not auto_sign:
                # This key is in the pending dir and is not being auto-signed.
                # Check if the keys are the same and error out if this is the
                # case. Otherwise log the fact that the minion is still
                # pending.
                with salt.utils.fopen(pubfn_pend, 'r') as pubfn_handle:
                    if pubfn_handle.read() != load['pub']:
                        log.error(
                            'Authentication attempt from {id} failed, the public '
                            'key in pending did not match. This may be an '
                            'attempt to compromise the Salt cluster.'
                            .format(**load)
                        )
                        # put denied minion key into minions_denied
                        with salt.utils.fopen(pubfn_denied, 'w+') as fp_:
                            fp_.write(load['pub'])
                        eload = {'result': False,
                                 'id': load['id'],
                                 'act': 'denied',
                                 'pub': load['pub']}
                        if self.opts.get('auth_events') is True:
                            self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
                        return {'enc': 'clear',
                                'load': {'ret': False}}
                    else:
                        log.info(
                            'Authentication failed from host {id}, the key is in '
                            'pending and needs to be accepted with salt-key '
                            '-a {id}'.format(**load)
                        )
                        eload = {'result': True,
                                 'act': 'pend',
                                 'id': load['id'],
                                 'pub': load['pub']}
                        if self.opts.get('auth_events') is True:
                            self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
                        return {'enc': 'clear',
                                'load': {'ret': True}}
            else:
                # This key is in pending and has been configured to be
                # auto-signed. Check to see if it is the same key, and if
                # so, pass on doing anything here, and let it get automatically
                # accepted below.
                with salt.utils.fopen(pubfn_pend, 'r') as pubfn_handle:
                    if pubfn_handle.read() != load['pub']:
                        log.error(
                            'Authentication attempt from {id} failed, the public '
                            'keys in pending did not match. This may be an '
                            'attempt to compromise the Salt cluster.'
                            .format(**load)
                        )
                        # put denied minion key into minions_denied
                        with salt.utils.fopen(pubfn_denied, 'w+') as fp_:
                            fp_.write(load['pub'])
                        eload = {'result': False,
                                 'id': load['id'],
                                 'pub': load['pub']}
                        if self.opts.get('auth_events') is True:
                            self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
                        return {'enc': 'clear',
                                'load': {'ret': False}}
                    else:
                        os.remove(pubfn_pend)

        else:
            # Something happened that I have not accounted for, FAIL!
            log.warning('Unaccounted for authentication failure')
            eload = {'result': False,
                     'id': load['id'],
                     'pub': load['pub']}
            if self.opts.get('auth_events') is True:
                self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
            return {'enc': 'clear',
                    'load': {'ret': False}}

        log.info('Authentication accepted from {id}'.format(**load))
        # only write to disk if you are adding the file, and in open mode,
        # which implies we accept any key from a minion.
        if not os.path.isfile(pubfn) and not self.opts['open_mode']:
            with salt.utils.fopen(pubfn, 'w+') as fp_:
                fp_.write(load['pub'])
        elif self.opts['open_mode']:
            disk_key = ''
            if os.path.isfile(pubfn):
                with salt.utils.fopen(pubfn, 'r') as fp_:
                    disk_key = fp_.read()
            if load['pub'] and load['pub'] != disk_key:
                log.debug('Host key change detected in open mode.')
                with salt.utils.fopen(pubfn, 'w+') as fp_:
                    fp_.write(load['pub'])
            elif not load['pub']:
                log.error('Public key is empty: {0}'.format(load['id']))
                return {'enc': 'clear',
                        'load': {'ret': False}}

        pub = None

        # the con_cache is enabled, send the minion id to the cache
        if self.cache_cli:
            self.cache_cli.put_cache([load['id']])

        # The key payload may sometimes be corrupt when using auto-accept
        # and an empty request comes in
        try:
            with salt.utils.fopen(pubfn) as f:
                pub = RSA.importKey(f.read())
        except (ValueError, IndexError, TypeError) as err:
            log.error('Corrupt public key "{0}": {1}'.format(pubfn, err))
            return {'enc': 'clear',
                    'load': {'ret': False}}

        cipher = PKCS1_OAEP.new(pub)
        ret = {'enc': 'pub',
               'pub_key': self.master_key.get_pub_str(),
               'publish_port': self.opts['publish_port']}

        # sign the master's pubkey (if enabled) before it is
        # sent to the minion that was just authenticated
        if self.opts['master_sign_pubkey']:
            # append the pre-computed signature to the auth-reply
            if self.master_key.pubkey_signature():
                log.debug('Adding pubkey signature to auth-reply')
                log.debug(self.master_key.pubkey_signature())
                ret.update({'pub_sig': self.master_key.pubkey_signature()})
            else:
                # the master has its own signing-keypair, compute the master.pub's
                # signature and append that to the auth-reply
                log.debug("Signing master public key before sending")
                pub_sign = salt.crypt.sign_message(self.master_key.get_sign_paths()[1],
                                                   ret['pub_key'])
                ret.update({'pub_sig': binascii.b2a_base64(pub_sign)})

        mcipher = PKCS1_OAEP.new(self.master_key.key)
        if self.opts['auth_mode'] >= 2:
            if 'token' in load:
                try:
                    mtoken = mcipher.decrypt(load['token'])
                    aes = '{0}_|-{1}'.format(salt.master.SMaster.secrets['aes']['secret'].value, mtoken)
                except Exception:
                    # Token failed to decrypt, send back the salty bacon to
                    # support older minions
                    pass
            else:
                aes = salt.master.SMaster.secrets['aes']['secret'].value

            ret['aes'] = cipher.encrypt(aes)
        else:
            if 'token' in load:
                try:
                    mtoken = mcipher.decrypt(load['token'])
                    ret['token'] = cipher.encrypt(mtoken)
                except Exception:
                    # Token failed to decrypt, send back the salty bacon to
                    # support older minions
                    pass

            aes = salt.master.SMaster.secrets['aes']['secret'].value
            ret['aes'] = cipher.encrypt(salt.master.SMaster.secrets['aes']['secret'].value)
        # Be aggressive about the signature
        digest = hashlib.sha256(aes).hexdigest()
        ret['sig'] = salt.crypt.private_encrypt(self.master_key.key, digest)
        eload = {'result': True,
                 'act': 'accept',
                 'id': load['id'],
                 'pub': load['pub']}
        if self.opts.get('auth_events') is True:
            self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth'))
        return ret
Ejemplo n.º 52
0
import socks, connections, time, sys, json, re
from Cryptodome.PublicKey import RSA

#define private key
key = RSA.importKey(open('/privkey.der').read())
private_key_readable = str(
    key.exportKey().decode("utf-8"))  #private key must be decoded
exchange_address = "MAIN_EXCHANGE_ADDRESS"

#print ('Number of arguments:', len(sys.argv), 'arguments.')
#print ('Argument List:', str(sys.argv))


def replace_regex_all(string, replace):
    replaced_string = re.sub(r'{}'.format(replace), "", string)
    return replaced_string


try:
    command = sys.argv[1]
except:
    pass

try:
    arg1 = sys.argv[2]
except:
    pass

try:
    arg2 = sys.argv[3]
except:
Ejemplo n.º 53
0
 def test_sign_message_with_passphrase(self):
     key = RSA.importKey(PRIVKEY_DATA)
     with patch('salt.crypt._get_rsa_key', return_value=key):
         self.assertEqual(SIG, crypt.sign_message('/keydir/keyname.pem', MSG, passphrase='password'))
Ejemplo n.º 54
0
def get_public_key():
    if os.path.exists(PUBLIC_KEY_FILE):
        with open(PUBLIC_KEY_FILE, 'rb') as f:
            return RSA.importKey(f.read())
Ejemplo n.º 55
0
def get_private_key():
    if os.path.exists(PRIVATE_KEY_FILE):
        with open(PRIVATE_KEY_FILE, 'rb') as f:
            return RSA.importKey(f.read())
Ejemplo n.º 56
0
def decrypt(cipher):
    privatekey = open("private.pem", "rb")
    private_key = RSA.importKey(privatekey.read())
    decryptor = PKCS1_OAEP.new(private_key)
    print(decryptor.decrypt(cipher).decode())
Ejemplo n.º 57
0
 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)
Ejemplo n.º 58
0
 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)
Ejemplo n.º 59
0
 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)
Ejemplo n.º 60
0
 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)