Пример #1
0
 def decrypt(self, buff):
     md = SHA256.new(buff[:-0x100])
     verifier = PKCS1_v1_5.new(self._static_pubkey)
     if verifier.verify(md, buff[-0x100:]) == False:
         raise ValueError('Invalid signature in footer.')
     if self._pubkey is not None:
         md = SHA256.new(buff[:-0x200])
         verifier = PKCS1_v1_5.new(self._pubkey)
         if verifier.verify(md, buff[-0x200:-0x100]) == False:
             raise ValueError('Invalid signature in footer.')
     buff = buff[:-0x200]
     nonce = array.array('I', buff[-4:])
     nonce.byteswap()
     length = len(buff) - 4
     buff = array.array('I', buff[:-4] + b'\x00' * (8 - length % 8))
     buff.byteswap()
     counter = Counter.new(32, prefix=nonce.tostring(), initial_value=0, little_endian=True)
     cipher = Blowfish.new(self._key, Blowfish.MODE_CTR, counter=counter)
     buff = array.array('I', cipher.decrypt(buff.tostring()))
     buff.byteswap()
     buff = buff.tostring()[:length]
     md = buff[-20:]
     buff = buff[:-20]
     if md != hashlib.sha1(buff).digest():
         raise ValueError('Invalid SHA1 hash in footer.')
     return buff
Пример #2
0
        def testSignVerify(self):
            rng = Random.new().read
            key = RSA.generate(1024, rng)

            for hashmod in (MD2, MD5, SHA1, SHA224, SHA256, SHA384, SHA512, RIPEMD160):
                hobj = hashmod.new()
                hobj.update(b('blah blah blah'))

                signer = PKCS.new(key)
                signature = signer.sign(hobj)
                signer.verify(hobj, signature)

            # Blake2b has variable digest size
            for digest_bits in (160, 256, 384, 512):
                hobj = BLAKE2b.new(digest_bits=digest_bits)
                hobj.update(b("BLAKE2b supports several digest sizes"))

                signer = PKCS.new(key)
                signature = signer.sign(hobj)
                signer.verify(hobj, signature)

            # Blake2s too
            for digest_bits in (128, 160, 224, 256):
                hobj = BLAKE2s.new(digest_bits=digest_bits)
                hobj.update(b("BLAKE2s supports several digest sizes"))

                signer = PKCS.new(key)
                signature = signer.sign(hobj)
                signer.verify(hobj, signature)
Пример #3
0
    def do(pub_key, priv_key):
        d = SHA.new('hello')

        priv = pkcs.new(priv_key)
        ret_sign = priv.sign(d)

        pub = pkcs.new(pub_key)
        pub.verify(d, ret_sign)
Пример #4
0
def test_rsa_verify(key=KEY, time=TIME, data=DATA):
    """
    RSA Verify (PKCS #1 v1.5)
    """
    time = test_time(time)
    mac = HMAC.new(time, data.encode("ascii"), SHA256)
    mac = SHA256.new(mac.digest())
    key = RSA.importKey(key)
    sig = PKCS1_v1_5.new(key).sign(mac)
    return b"Yes" if PKCS1_v1_5.new(key).verify(mac, sig) else b"No"
Пример #5
0
def main():
    pub_key, priv_key = load_keys()

    d = SHA.new(config.test_data)

    priv = pkcs.new(priv_key)
    ret_sign = priv.sign(d)

    pub = pkcs.new(pub_key)
    pub.verify(d, ret_sign)
Пример #6
0
 def __init__(self, public_key_file, private_key_file):
     with open(public_key_file,'rb') as pkf:
         pubkey_string = pkf.read()
         self.public_key = RSA.importKey(pubkey_string)
     with open(private_key_file,'rb') as pkf:
         privkey_string = pkf.read()
         self.private_key = RSA.importKey(privkey_string)
     self.public = PKCS1_OAEP.new(self.public_key)
     self.private = PKCS1_OAEP.new(self.private_key)
     self.signer = PKCS1_v1_5.new(self.private_key)
     self.verifier = PKCS1_v1_5.new(self.public_key)
Пример #7
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)
Пример #8
0
def main_01():
    def do(pub, priv):
        d = SHA.new('hello')

        ret_sign = priv.sign(d)
        pub.verify(d, ret_sign)

    pub = pkcs.new(pub_key)
    priv = pkcs.new(priv_key)

    for _ in range(config.calc_times):
        do(pub, priv)
Пример #9
0
def sign(xml_etree, certificate, der_key, passphrase=None, trusted=None):
    """
    Return xmldsig XML string from xml_string of XML.

    :param xml_etree: etree of the xml to sign
    :param der_key: Private key in DER format
    :param certificate: publicKey Public key

    :returns: signed XML byte string

    """
    # from M2Crypto import RSA as m2cryptoRSA
    # from M2Crypto import EVP as m2cryptoEVP
    # from Crypto.PublicKey import RSA as cryptoRSA
    # path_to_pem="/home/rovskyhp/.virtualenvs/agreement/var/tmp/tmp_60.pem"
    # evp = m2cryptoEVP.load_key(str(path_to_pem)).as_der() # Convert Private key (M2Crypto Object) to  DER format
    # key = cryptoRSA.importKey(evp, passphrase='12345678a')

    if hasattr(certificate, 'key'):
        key_info_xml = _generate_key_info_xml_rsa(certificate.key.n,
certificate.key.e)
        pubkey, hasher = certificate, Hash.SHA1
    else:
        der_cer = certificate.as_der()
        key_info_xml = _generate_key_info_xml_x509(der_cer)
        #pubkey, hasher, serialNumber, subject = _x509_certificate(der_cer=certificate, trusted=trusted)
        pubkey = RSA.importKey(certificate.get_pubkey().as_der())

    signed_info_xml = _generate_signed_info(xml_etree)
    text = c14n(signed_info_xml)

    key = RSA.importKey(der_key, passphrase)
    signer = PKCS1_v1_5.new(key)
    signature = signer.sign(Hash.SHA1.new(text))

    verifier = PKCS1_v1_5.new(pubkey)

    if not verifier.verify(Hash.SHA1.new(text), signature):
        raise Exception("Signature verification failure!")

    signature_xml = PTN_SIGNATURE_XML % {
        'signed_info_xml': signed_info_xml,
        'signature_value': binascii.b2a_base64(signature)[:-1],
        'key_info_xml': key_info_xml,
    }
    signature_etree = etree.parse(StringIO(signature_xml))
    xml_etree.append(signature_etree.getroot())

    return xml_etree
Пример #10
0
        def test_wrong_signature(self):
            key = RSA.generate(1024)
            msg_hash = SHA1.new(b("Message"))

            signer = PKCS.new(key)
            s = signer.sign(msg_hash)

            verifier = PKCS.new(key.publickey())

            # The signature s should be OK
            verifier.verify(msg_hash, s)

            # Construct an incorrect signature and ensure that the check fails
            wrong_s = s[:-1] + bchr(bord(s[-1]) ^ 0xFF)
            self.assertRaises(ValueError, verifier.verify, msg_hash, wrong_s)
Пример #11
0
def _get_signature_bytes(credentials, string_to_sign):
    """Uses crypto attributes of credentials to sign a string/bytes.

    :type credentials: :class:`client.SignedJwtAssertionCredentials`,
                       :class:`service_account._ServiceAccountCredentials`,
                       :class:`_GAECreds`
    :param credentials: The credentials used for signing text (typically
                        involves the creation of an RSA key).

    :type string_to_sign: string
    :param string_to_sign: The string to be signed by the credentials.

    :rtype: bytes
    :returns: Signed bytes produced by the credentials.
    """
    if isinstance(credentials, _GAECreds):
        _, signed_bytes = app_identity.sign_blob(string_to_sign)
        return signed_bytes
    else:
        pem_key = _get_pem_key(credentials)
        # Sign the string with the RSA key.
        signer = PKCS1_v1_5.new(pem_key)
        if not isinstance(string_to_sign, six.binary_type):
            string_to_sign = string_to_sign.encode('utf-8')
        signature_hash = SHA256.new(string_to_sign)
        return signer.sign(signature_hash)
Пример #12
0
    def get_new_token(self):
        """
        Get a new token using the email address and RSA Key.

        :return:  Dictionary containing token information
        :rtype:   ``dict``
        """
        # The header is always the same
        header = {'alg': 'RS256', 'typ': 'JWT'}
        header_enc = base64.urlsafe_b64encode(b(json.dumps(header)))

        # Construct a claim set
        claim_set = {'iss': self.user_id,
                     'scope': self.scopes,
                     'aud': 'https://accounts.google.com/o/oauth2/token',
                     'exp': int(time.time()) + 3600,
                     'iat': int(time.time())}
        claim_set_enc = base64.urlsafe_b64encode(b(json.dumps(claim_set)))

        # The message contains both the header and claim set
        message = b'.'.join((header_enc, claim_set_enc))
        # Then the message is signed using the key supplied
        key = RSA.importKey(self.key)
        hash_func = SHA256.new(message)
        signer = PKCS1_v1_5.new(key)
        signature = base64.urlsafe_b64encode(signer.sign(hash_func))

        # Finally the message and signature are sent to get a token
        jwt = b'.'.join((message, signature))
        request = {'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
                   'assertion': jwt}

        return self._token_request(request)
Пример #13
0
 def Generate(self):
     if not os.path.exists(self.source_dir_):
         print("The source directory %s is invalid." % self.source_dir_)
         return
     try:
         zip_file = '%s.tmp' % self.output_file_
         self.__Compress(self.source_dir_, zip_file)
         signer = PKCS1_v1_5.new(self.RSAkey)
         zfile = open(zip_file, 'rb')
         sha = SHA.new(zfile.read())
         signature = signer.sign(sha)
         xpk = open(self.output_file_, 'wb')
         zfile.seek(0)
         print('Generating XPK package: %s' % self.output_file_)
         xpk.write('\x43\x72\x57\x6B')
         xpk.write(struct.pack('<I', len(self.pubkey)))
         xpk.write(struct.pack('<I', len(signature)))
         xpk.write(self.pubkey)
         xpk.write(signature)
         xpk.write(zfile.read())
         zfile.close()
         xpk.close()
         print('Generated new XPK package %s successfully.'
               % self.output_file_)
     except IOError:
         if os.path.exists(self.output_file_):
             os.remove(self.output_file_)
         traceback.print_exc()
     finally:
         if os.path.exists(zip_file):
             os.remove(zip_file)
Пример #14
0
def sign(message, sender_private_key):

    h = SHA.new(message)
    signer = PKCS1_v1_5.new(sender_private_key)
    signature = signer.sign(h)
    
    return signature
Пример #15
0
def webhooks_verify(path_pubkey, private_sign, req_data):
    """ path_pubkey : 公钥文件路径,内容为ping++提供的公钥(账户和设置 - Ping++ 公钥)
        private_sign: ping++对应的私钥签名后的字符串
        req_data    : 请求的json格式字符串,不要get_json(),因为会改变字段的顺序,直接获取原始字符串即可
        备注:遇到一个坑,直接从官网上copy公钥时,vim保存文件时会多一个字符,导致验算不通过,推荐notepad++保存
              最后一行不要有换行符
    """
    import base64
    
    from Crypto.PublicKey import RSA
    from Crypto.Signature import PKCS1_v1_5
    from Crypto.Hash import SHA256

    def decode_base64(data):
        missing_padding = 4 - len(data) % 4
        if missing_padding:
            data += b'='*missing_padding
        return base64.decodestring(data)

    sig = decode_base64(private_sign)
    req_data = req_data.encode('utf-8')
    digest = SHA256.new(req_data)
    pubkey = RSA.importKey(open(path_pubkey).read())
    pkcs = PKCS1_v1_5.new(pubkey)

    return pkcs.verify(digest, sig)
Пример #16
0
 def verify(self, msg, sig, key):
     h = self.digest.new(msg)
     verifier = PKCS1_v1_5.new(key)
     if verifier.verify(h, sig):
         return True
     else:
         raise BadSignature()
Пример #17
0
def sign_rsa_sha1(base_string, rsa_private_key):
    """**RSA-SHA1**

    Per `section 3.4.3`_ of the spec.

    The "RSA-SHA1" signature method uses the RSASSA-PKCS1-v1_5 signature
    algorithm as defined in `RFC3447, Section 8.2`_ (also known as
    PKCS#1), using SHA-1 as the hash function for EMSA-PKCS1-v1_5.  To
    use this method, the client MUST have established client credentials
    with the server that included its RSA public key (in a manner that is
    beyond the scope of this specification).

    NOTE: this method requires the python-rsa library.

    .. _`section 3.4.3`: http://tools.ietf.org/html/rfc5849#section-3.4.3
    .. _`RFC3447, Section 8.2`: http://tools.ietf.org/html/rfc3447#section-8.2

    """
    # TODO: finish RSA documentation
    from Crypto.PublicKey import RSA
    from Crypto.Signature import PKCS1_v1_5
    from Crypto.Hash import SHA

    key = RSA.importKey(rsa_private_key)
    if isinstance(base_string, unicode_type):
        base_string = base_string.encode("utf-8")
    h = SHA.new(base_string)
    p = PKCS1_v1_5.new(key)
    return binascii.b2a_base64(p.sign(h))[:-1].decode("utf-8")
Пример #18
0
def rsa_sign(para_str):
    """对请求参数做rsa签名"""
    para_str = para_str.encode('utf-8')
    key = RSA.importKey(settings.ALIPAY_PRIVATE_KEY)
    h = SHA.new(para_str)
    signer = PKCS1_v1_5.new(key)
    return base64.b64encode(signer.sign(h))
Пример #19
0
def verify_hash(pub_algorithm_type, public_key, hash_, values):
    if pub_algorithm_type in (1, 3):
        # RSA
        s = long_to_bytes(values[0])
        return PKCS1_v1_5.new(public_key).verify(hash_, s)
    elif pub_algorithm_type == 20:
        # ELG
        # TODO: Remove dependence on undocumented method
        sig_string = PKCS1_v1_5.EMSA_PKCS1_V1_5_ENCODE(
                            hash_, public_key.size())
        return public_key.verify(sig_string, values)
    elif pub_algorithm_type == 17:
        # DSA
        q = public_key.q
        qbits = int(math.floor(float(math.log(q, 2)))) + 1
        qbytes = int(math.ceil(qbits / 8.0))

        digest = hash_.digest()
        # Discard empty leading bytes
        start = 0
        while digest[start] == b'\x00':
            start += 1
        digest = digest[start:start + qbytes]
        return public_key.verify(bytes_to_long(digest), values)
    else:
        # TODO: complete this
        raise ValueError
Пример #20
0
def sign_hash(pub_algorithm_type, secret_key, hash_, k=None):
    if pub_algorithm_type in (1, 3):
        # RSA
        sig_string = PKCS1_v1_5.new(secret_key).sign(hash_)
        return (bytes_to_long(sig_string),)
    elif pub_algorithm_type == 20:
        # ELG
        # TODO: Should only be allowed for test purposes
        if k is None:
            while 1:
                # This can be pretty darn slow
                k = random.StrongRandom().randint(1, secret_key.p - 1)
                if GCD(k, secret_key.p - 1) == 1:
                    break
            print(k)
        # TODO: Remove dependence on undocumented method
        sig_string = PKCS1_v1_5.EMSA_PKCS1_V1_5_ENCODE(
                            hash_, secret_key.size())
        return secret_key.sign(sig_string, k)
    elif pub_algorithm_type == 17:
        q = secret_key.q
        qbits = int(math.floor(float(math.log(q, 2)))) + 1
        qbytes = int(math.ceil(qbits / 8.0))
        if k is None:
            k = random.StrongRandom().randint(1, q - 1)

        digest = hash_.digest()[:qbytes]
        return secret_key.sign(bytes_to_long(digest), k)
    else:
        # TODO: complete
        raise ValueError
Пример #21
0
 def _verify_sign(self, public_key, sign_str, sign):
     rsa_key = RSA.importKey(public_key)
     signer = PKCS1_v1_5.new(rsa_key)
     digest = SHA.new(sign_str)
     if signer.verify(digest, base64.decodestring(sign)):
         return True
     return False
Пример #22
0
    def post_results(self, url, content, sign_with=None):
        '''Post the combined results back to the server.'''
        endpoint = '%s/v1/results/' % url
        headers = {'Content-type': 'application/json'}
        data = json.dumps(content)
        self.logger.debug('API request content: %s ' % content)
        if sign_with:
            data_hash = SHA256.new()
            data_hash.update(data.encode('utf-8'))
            with open(sign_with) as key_pair_file:
                try:
                    key = RSA.importKey(key_pair_file.read())
                except (IOError, ValueError) as e:
                    self.logger.info('Error during upload key pair %s'
                                     '' % key_pair_file)
                    self.logger.exception(e)
                    return
            signer = PKCS1_v1_5.new(key)
            sign = signer.sign(data_hash)
            headers['X-Signature'] = binascii.b2a_hex(sign)
            headers['X-Public-Key'] = key.publickey().exportKey('OpenSSH')
        try:
            response = requests.post(endpoint,
                                     data=data,
                                     headers=headers,
                                     verify=not self.args.insecure)
            self.logger.info(endpoint + " Response: " + str(response.text))
        except Exception as e:
            self.logger.info('Failed to post %s - %s ' % (endpoint, e))
            self.logger.exception(e)
            return

        if response.status_code == 201:
            resp = response.json()
            print 'Test results uploaded!\nURL: %s' % resp.get('url', '')
Пример #23
0
def check_signature(baseurl, signature, data, publickey=None):
    if publickey == None:
        if baseurl in publickeys:
            publickey = base64.decodestring(publickeys[baseurl])
        else:
            print >>sys.stderr, "Public key for", baseurl, \
                "not found, specify key file with --publickey"
            # sys.exit(1)
            raise Exception
    (hash_alg, signature_alg, unpacked_signature) = decode_signature(signature)
    assert hash_alg == 4, \
        "hash_alg is %d, expected 4" % (hash_alg,) # sha256
    assert (signature_alg == 3 or signature_alg == 1), \
        "signature_alg is %d, expected 1 or 3" % (signature_alg,) # ecdsa

    if signature_alg == 3:
        vk = ecdsa.VerifyingKey.from_der(publickey)
        vk.verify(unpacked_signature, data, hashfunc=hashlib.sha256,
              sigdecode=ecdsa.util.sigdecode_der)
    else:
        h = SHA256.new(data)

        rsa_key = RSA.importKey(publickey)
        verifier = PKCS1_v1_5.new(rsa_key)
        assert verifier.verify(h, unpacked_signature), \
            "could not verify RSA signature"
Пример #24
0
    def __init__(self, conf, state):
        """
        conf  -- dictionary with configuration variables
        state -- class object with update() function
        """
        self.logger = conf['log']
        self.maxBal = -1
        self.maxVBal = -1       # highest ballot voted in
        self.maxVVal = None     # value voted for maxVBal
        self.avs = []           # msg dict keyed by value
        self.seen = {}          # 1b messages -> use to check if v is safe at b
        self.bmsgs = []         # log of values in 2b messages sent by this instance       
        self.Q = None
        
        with open(conf['keyfile'], 'r') as fh:
            key = RSA.importKey(fh.read())
        self.signer = PKCS1_v1_5.new(key)

        # initialize localgroup
        self.peers = GroupManager(conf)
        self.peers.init_local_group()
        self.state = state
        #self.state.groups['G1'] = self.peers

        self.ctx = get_ssl_context(conf['peer_certs'])
        self.pending = None
Пример #25
0
    def _sign_request(self, info, return_urls):
        """Create and sign payment request data."""
        # Basic fields
        fields = [('VK_SERVICE', u'1002'),
                  ('VK_VERSION', u'008'),
                  ('VK_SND_ID',  self.user),
                  ('VK_STAMP',   '%d' % int(time())),
                  ('VK_AMOUNT',  info.amount),
                  ('VK_CURR',    u'EUR'),
                  ('VK_REF',     info.refnum),
                  ('VK_MSG',     info.message)]

        # Check whether provider supplies extra fields
        if hasattr(self, 'extra_fields'):
            fields.extend(self.extra_fields)

        ## MAC calculation for request 1002
        m = self._build_mac(('SERVICE', 'VERSION', 'SND_ID', 'STAMP', \
                             'AMOUNT', 'CURR', 'REF', 'MSG'), dict(fields))
        # Append mac fields
        fields.append(('VK_MAC', b64encode( \
                    PKCS1_v1_5.new(self.keychain.private_key)
                              .sign(SHA.new(m)))))
        # Append return url field(s)
        fields.append(('VK_RETURN', return_urls['return']))
        return fields
Пример #26
0
    def parse_response(self, form, success=True):
        """Parse and return payment response."""
        fields = {
            # Successful payment
            '1101': ('SERVICE', 'VERSION', 'SND_ID', 'REC_ID', 'STAMP', #  1..5
                     'T_NO', 'AMOUNT', 'CURR', 'REC_ACC', 'REC_NAME',   #  6..10
                     'SND_ACC', 'SND_NAME', 'REF', 'MSG', 'T_DATE'),    # 11..15
            # Unsuccessful payment
            '1901': ('SERVICE', 'VERSION', 'SND_ID', 'REC_ID', 'STAMP', #  1..5
                     'REF', 'MSG')                                      #  6..7
        }
        # See which response we got
        resp = form.get('VK_SERVICE', None)
        if not resp and resp not in fields:
            raise InvalidResponseError
        success = resp == '1101'

        Random.atfork()

        # Parse and validate MAC
        m = self._build_mac(fields[resp], form)
        f = lambda x: form.get('VK_%s' % x)
        if not PKCS1_v1_5.new(self.keychain.public_key) \
                         .verify(SHA.new(m), b64decode(f('MAC'))):
            raise InvalidResponseError
        # Save payment data
        data = {}
        if success:
            for item in ('T_NO', 'AMOUNT', 'CURR', 'REC_ACC', 'REC_NAME',
                         'SND_ACC', 'SND_NAME', 'REF', 'MSG', 'T_DATE'):
                data[item] = f(item)
        return PaymentResponse(self, data, success)
Пример #27
0
def sign_data(data, key_path):
    with open(key_path, 'r') as f:
        key = RSA.importKey(f.read())
    signer = PKCS1_v1_5.new(key)
    hash = SHA.new(data)
    signature = signer.sign(hash)
    return base64.b64encode(signature)
Пример #28
0
def verify_rsa_sha1(request, rsa_public_key):
    """Verify a RSASSA-PKCS #1 v1.5 base64 encoded signature.

    Per `section 3.4.3`_ of the spec.

    Note this method requires the PyCrypto library.

    .. _`section 3.4.3`: http://tools.ietf.org/html/rfc5849#section-3.4.3

    To satisfy `RFC2616 section 5.2`_ item 1, the request argument's uri
    attribute MUST be an absolute URI whose netloc part identifies the
    origin server or gateway on which the resource resides. Any Host
    item of the request argument's headers dict attribute will be
    ignored.

    .. _`RFC2616 section 5.2`: http://tools.ietf.org/html/rfc2616#section-5.2
    """
    from Crypto.PublicKey import RSA
    from Crypto.Signature import PKCS1_v1_5
    from Crypto.Hash import SHA
    key = RSA.importKey(rsa_public_key)
    norm_params = normalize_parameters(request.params)
    uri = normalize_base_string_uri(request.uri)
    message = construct_base_string(request.http_method, uri, norm_params)
    h = SHA.new(message.encode('utf-8'))
    p = PKCS1_v1_5.new(key)
    sig = binascii.a2b_base64(request.signature.encode('utf-8'))
    return p.verify(h, sig)
Пример #29
0
    def sign(cls, string):
        """Returns the signature of a string.

        This signature is generated using the singleton private key, then
        base64-encoded. It's of the form expected by Google Cloud Storage query
        string authentication. See
        https://developers.google.com/storage/docs/accesscontrol#Signed-URLs.
        """

        # All Google API keys have "notasecret" as their passphrase
        value = cls.get_oauth()
        if value is None: raise "Private key has not been set."
        if handlers.is_production():
            # TODO(nweiz): This currently doesn't work on the development server
            # without adding 'AESCipher', 'blockalgo', and '_AES' to the
            # __CRYPTO_CIPHER_ALLOWED_MODULES constant in
            # google/appengine/tools/dev_appserver_import_hook.py. However, it
            # does work in production, so to make it work locally, we just do a
            # dumb hash of the private key and the string.
            #
            # See http://code.google.com/p/googleappengine/issues/detail?id=8188
            key = RSA.importKey(value, passphrase='notasecret')
            return base64.b64encode(PKCS1_v1_5.new(key).sign(SHA256.new(string)))
        else:
            m = hashlib.md5()
            m.update(value)
            m.update(string)
            return base64.b64encode(m.digest())
def sign_file(f):
    # TODO: For Part 2, you'll use public key crypto here
    # The existing scheme just ensures the updates start with the line 'Caesar'
    # This is naive -- replace it with something better!
    
    # Generate key pairs
    key = RSA.generate(2048)
    
    # Export public key to file
    export_pukey = key.publickey().exportKey('PEM')
    publickey_file = open(os.path.join("pastebot.net", "publickey"), "wb")
    publickey_file.write(export_pukey)
    publickey_file.close()
    
    # Create RSA object from public key
    publickey_file = open(os.path.join("pastebot.net", "publickey"), "rb").read()
    public_key = RSA.importKey(publickey_file)
    
    # Hash message
    hashed_m = SHA256.new(f)
    
    # Encrypt message using public key
    cipher = PKCS1_cipher.new(public_key)
    ciphertext = cipher.encrypt(f+hashed_m.digest())
    
    # Export private key to be prefixed to ciphertext
    export_prkey = key.exportKey('PEM')
    
    # Sign message using private key
    prkey = RSA.importKey(export_prkey)
    signer = PKCS1_v1_5.new(prkey)
    signature = signer.sign(hashed_m)
    
    # Return private key and ciphertext, as well as signature separately
    return export_prkey + b"\n" + ciphertext, signature
Пример #31
0
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
import base64
import sys
MovimientoId = sys.argv[1]
key = RSA.importKey(open("archivorsa" + MovimientoId + ".pem").read())
archivo = open("timbre" + MovimientoId + ".txt", "r")
message = archivo.read()

h = SHA.new(message)
p = PKCS1_v1_5.new(key)
signature = p.sign(h)

archivofirmado = open('timbrefirmado' + MovimientoId + '.txt', 'w')
archivofirmado.write(base64.b64encode(signature))
archivofirmado.close()
print "TIMBRE ELECTRONICO GENERADO"
Пример #32
0
def cmd_asydns(url, generate, revoke):

    dotdir = Path.home() / '.asydns'

    dotdir.mkdir(exist_ok=True)

    pub_file = dotdir / 'rsa.pub'
    key_file = dotdir / 'rsa.key'


    if generate or not key_file.is_file():

        print('Generating RSA key ...')
        random_generator = Random.new().read
        key = RSA.generate(2048, random_generator)
        pub = key.publickey()

        with key_file.open('w') as k:
            k.write(key.exportKey('PEM').decode())

        with pub_file.open('w') as p:
            p.write(pub.exportKey('PEM').decode())


    print('Loading RSA key ...')
    with key_file.open() as k:
        key = RSA.importKey(k.read())

    with pub_file.open() as p:
        pub = RSA.importKey(p.read())


    r = requests.get(url + '/api')

    if r.status_code != 200:
        print('Error')
        print(r.content.decode())
        return False

    j = r.json()

    challenge = base64.b64decode(j['challenge'])
    signer = PKCS1_v1_5.new(key)
    response = signer.sign(SHA224.new(challenge))
    response = base64.b64encode(response).decode()

    if revoke:
        r = requests.delete(url + '/api', json={'pub': pub.exportKey('PEM').decode(), 'challenge' : j['challenge'], 'response': response})
    else:
        r = requests.post(url + '/api', json={'pub': pub.exportKey('PEM').decode(), 'challenge' : j['challenge'], 'response': response})

    print(r.request.headers)
    print(r.request.body)

    if r.status_code != 200:
        print('Error')
        print(r.content.decode())
        return False

    print(json.dumps(r.json(), indent=4))

    return True
Пример #33
0
 def signature(self, cleartext):
     h = SHA256.new(cleartext)
     signer = sig_pkcs.new(self.key)
     signature = signer.sign(h)
     return base64.b64encode(signature)
Пример #34
0
def query(action=None,
          command=None,
          args=None,
          method='GET',
          location=None,
          data=None):
    '''
    Make a web call to Joyent
    '''
    user = config.get_cloud_config_value(
        'user', get_configured_provider(), __opts__, search_global=False
    )

    if not user:
        log.error('username is required for Joyent API requests. Please set one in your provider configuration')

    password = config.get_cloud_config_value(
        'password', get_configured_provider(), __opts__,
        search_global=False
    )

    verify_ssl = config.get_cloud_config_value(
        'verify_ssl', get_configured_provider(), __opts__,
        search_global=False, default=True
    )

    ssh_keyfile = config.get_cloud_config_value(
        'private_key', get_configured_provider(), __opts__,
        search_global=False, default=True
    )

    if not ssh_keyfile:
        log.error('ssh_keyfile is required for Joyent API requests.  Please set one in your provider configuration')

    ssh_keyname = config.get_cloud_config_value(
        'keyname', get_configured_provider(), __opts__,
        search_global=False, default=True
    )

    if not ssh_keyname:
        log.error('ssh_keyname is required for Joyent API requests.  Please set one in your provider configuration')

    if not location:
        location = get_location()

    api_host_suffix = config.get_cloud_config_value(
        'api_host_suffix', get_configured_provider(), __opts__,
        search_global=False, default=JOYENT_API_HOST_SUFFIX
    )

    path = get_location_path(location=location, api_host_suffix=api_host_suffix)

    if action:
        path += action

    if command:
        path += '/{0}'.format(command)

    log.debug('User: \'%s\' on PATH: %s', user, path)

    if (not user) or (not ssh_keyfile) or (not ssh_keyname) or (not location):
        return None

    timenow = datetime.datetime.utcnow()
    timestamp = timenow.strftime('%a, %d %b %Y %H:%M:%S %Z').strip()
    rsa_key = salt.crypt.get_rsa_key(ssh_keyfile, None)
    if HAS_M2:
        md = EVP.MessageDigest('sha256')
        md.update(timestamp.encode(__salt_system_encoding__))
        digest = md.final()
        signed = rsa_key.sign(digest, algo='sha256')
    else:
        rsa_ = PKCS1_v1_5.new(rsa_key)
        hash_ = SHA256.new()
        hash_.update(timestamp.encode(__salt_system_encoding__))
        signed = rsa_.sign(hash_)
    signed = base64.b64encode(signed)
    keyid = '/{0}/keys/{1}'.format(user.split('/')[0], ssh_keyname)

    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'X-Api-Version': JOYENT_API_VERSION,
        'Date': timestamp,
        'Authorization': 'Signature keyId="{0}",algorithm="rsa-sha256" {1}'.format(
            keyid,
            signed.decode(__salt_system_encoding__)
        ),
    }

    if not isinstance(args, dict):
        args = {}

    # post form data
    if not data:
        data = salt.utils.json.dumps({})

    return_content = None
    result = salt.utils.http.query(
        path,
        method,
        params=args,
        header_dict=headers,
        data=data,
        decode=False,
        text=True,
        status=True,
        headers=True,
        verify_ssl=verify_ssl,
        opts=__opts__,
    )
    log.debug('Joyent Response Status Code: %s', result['status'])
    if 'headers' not in result:
        return [result['status'], result['error']]

    if 'Content-Length' in result['headers']:
        content = result['text']
        return_content = salt.utils.yaml.safe_load(content)

    return [result['status'], return_content]
Пример #35
0
    def process_incoming_message(self, msg_raw, msg_id, owner_str):
        '''
        Process incoming messages
        :param msg_raw: the raw message
        :param msg_id: ID of the message
        :param owner_str: user name of the user who posted the message
        :param user_name: name of the current user
        :param print_all: is the message part of the conversation history?
        :return: None
        '''
        global state
        user = self.manager.user_name

        if user == self.owner and state == STARTED:
            print "user STARTED"

            #reply with nonce from other participants
            cipher_STARTED = PKCS1_OAEP.new(self.private_key)
            print msg_raw
            print b64decode(msg_raw)
            buf_STARTED = cipher_STARTED.decrypt(b64decode(msg_raw))
            print "buf_STARTED: " + buf_STARTED
            index = buf_STARTED.index('|')
            buf_NAMES = buf_STARTED[:index]
            nonce_STARTED = buf_STARTED[index + 1:]
            if (owner_str + user) == buf_NAMES:
                #correct response
                #generate keys
                session_key = SHA256.new(
                    self.user_public_key.publickey().exportKey())
                session_key = session_key.hexdigest()
                print session_key
                mac_key = Random.get_random_bytes(32)
                iv_GENERATED = Random.new().read(AES.block_size)
                self.key_pair = [session_key, mac_key]
                state = GENERATED
                print "GENERATED"

            else:
                #print bad message (need to account for multiple participants TODO: use array!) state and nonce
                print "Y U DO DIS"
                return

            #send keys
            nonce_GENERATED = Random.new().read(16)
            data = user.encode('utf-8') + "|" + b64encode(
                nonce_GENERATED) + "|" + b64encode(
                    self.key_pair[0] + "|" +
                    self.key_pair[1]) + "|" + b64encode(iv_GENERATED)

            #for loop through users state array if they are state == GENERATED then send them this message
            user_index = self.list_of_users.index(owner_str)
            cipher_GENERATED = PKCS1_OAEP.new(self.users_init[user_index])
            encrypted_msg = cipher_GENERATED.encrypt(data.encode('utf-8'))

            data2 = nonce_STARTED + encrypted_msg

            #create sign
            h = SHA256.new(data2)

            signer = PKCS1_v1_5.new(self.private_key)
            signed_data2 = b64encode(signer.sign(data2))

            final_msg_GENERATED = nonce_STARTED + "|" + iv_GENERATED + "|" + encrypted_msg + "|" + signed_data2
            print final_msg_GENERATED
            self.manager.post_message_to_conversation(final_msg_GENERATED)

            print "timer generated start"
            #TODO
            #start timer
            timer_GENERATED = time.time()

            #change state? in GENERATED right now

        elif state == LISTENING:  #not owner listening for initial msg
            cipher1 = PKCS1_OAEP.new(self.private_key)
            buf = b64decode(msg_raw)
            decrypted_message = cipher1.decrypt(buf)

            msg_check = self.owner + user
            if decrypted_message != msg_check:
                print "Invalid message"
                return
                #throw an exception?
            else:
                print "Valid message"

            #generate Nonce
            nonce_user = Random.new().read(16)
            #reply_message = user.encode('utf-8') + self.owner.encode('utf-8') + "|".encode('utf-8') + nonce_user.encode('utf-8')
            re0 = user.encode('utf-8')
            print re0
            re = self.owner.encode('utf-8')
            print re
            re2 = "|".encode('utf-8')
            print re2
            print b64encode(nonce_user)
            re3 = b64encode(nonce_user)  #.encode('utf-8')
            reply_message = re0 + re + re2 + re3
            print reply_message
            pubkeystr = self.users_init[len(self.list_of_users) - 1]
            print pubkeystr

            #pubkey = RSA.importKey(pubkeystr)
            cipher2 = PKCS1_OAEP.new(pubkeystr)

            self.manager.post_message_to_conversation(
                b64encode(cipher2.encrypt(reply_message)))
            #self.process_outgoing_message(cipher2.encrypt(reply_message), True)
            #TODO
            self.timer_LISTENING = time.time()
            #start a timer for key freshness

            #change state
            state = FIRST_NONCE

        elif state == FIRST_NONCE:

            #TODO
            #receiving key message from the creator
            # data = user.encode('utf-8') + "|" + b64encode(nonce_GENERATED)
            #+ "|" + b64encode(self.key_pair[0] + "|" + self.key_pair[1]) + "|" + b64encode(iv_GENERATED)

            timer_FIRST_NONCE = time.time()
            if (timer_FIRST_NONCE - self.timer_LISTENING <= 60):
                #check incoming nonce against nonce_user and make sure timer hasn't expired
                print "FIRST_NONCE: " + msg_raw
                msg_raw = b64decode(msg_raw)
                nonce_index = msg_raw.index("|")
                if (nonce_user == msg_raw[:nonce_index]):
                    #for i in range(nonce_index+1, len(msg_raw)):
                    msg = msg_raw[nonce_index + 1:]
                    index = msg.index("|")

                    #save the iv
                    iv_FIRST_NONCE = msg[:index]

                    msg = msg[index + 1:]
                    index = msg.index("|")
                    encrypted_msg = msg[:index]

                    signed_msg = msg[index + 1:]

                    #decrypt the third part of the message A |Na|K|IV with self.private_key
                    cipher_FIRST_NONCE = PKCS1_OAEP.new(self.private_key)
                    decrypted_FIRST_NONCE = cipher_FIRST_NONCE.decrypt(
                        encrypted_msg)

                    #check iv values
                    index = decrypted_FIRST_NONCE.index("|")
                    decrypted_user = decrypted_FIRST_NONCE[:index]

                    msg = decrypted_FIRST_NONCE[index + 1:]
                    index = msg.index("|")

                    decrypted_nonce = msg[:index]
                    msg = decrypted_FIRST_NONCE[index + 1:]

                    index = msg.index("|")
                    decrypted_key_pair = msg[:index]

                    decrypted_iv = msg[index + 1:]

                    #Check signature of last part of the message against hashed part of third part
                    #e.g. msg = A |Na|K|IV, h = SHA256.new(msg) == unsigned(signature) / maybe we use verify?
                    h = SHA256.new(nonce_user + encrypted_msg)

                    msg_owner = self.list_of_users.index(owner_str)
                    sign_check = PCKS1_v1_5.new(self.users_init[msg_owner])

                    if (sign_check.verify(h, b64decode(signed_msg))):
                        # now we have the new session key, iv and a nonce from the creator
                        if (iv_FIRST_NONCE == decrypted_iv):
                            self.iv = decrypted_iv
                            self.key_pair = decrypted_key_pair

                # respond with E(B|NA|K)PuA , E(E(B|NA|K)PuA)PrB
                # second part is signed of the first part
                #change state to FINAL_CHECK
        elif state == GENERATED:
            print state
            #TODO
            # creator waiting for final response from participants
            # parse msg = B |Na|K|
            # check if Na == nonce_GENERATED for user B
            #make sure nonce is received in enough time to be considered valid
            # check if K = self.key_pair
            #verify signature of second part of message
            #state == VERIFIED

        if state == KEY_READY:  #we can probably make these the same

            #TODO fix this  not real message sending use key pair not RSA keys
            kfile = open("user_" + user + "_privatekey.txt")
            keystr = kfile.read()
            kfile.close()

            private_key = RSA.importKey(keystr)
            cipher = PKCS1_OAEP.new(private_key)

            plain_text = cipher.decrypt(msg_raw)

            # print message and add it to the list of printed messages
            self.print_message(msg_raw=decoded_msg, owner_str=owner_str)
Пример #36
0
from Util import PKCS1_pad as pad


def verify(s, m, n, e):
    if pow(s, e, n) == pad(m):
        return True
    else:
        return False


key = RSA.generate(1024)

message = "super important information for admin only"

h = SHA.new(message)
signer = RSAsign.new(key)

signature = signer.sign(h)
s = int(signature.encode("hex"), 16)

print "Welcome to admin's music portal.\nTo verify that you are the owner of this service\nsend the public key which will verify the following signature :\n"

print "Message   ->", message
print
print "Signature ->", signature.encode("hex")
print

sys.stdout.flush()

n = long(raw_input("Enter n:"))
e = long(raw_input("Enter e:"))
Пример #37
0
from Crypto.Hash import MD5
from Crypto import Random

# 伪随机数生成器
random_generator = Random.new().read

# 生成2048比特秘钥对(pk, sk)
rsa = RSA.generate(2048, random_generator)
private_pem = rsa.exportKey()
with open('master-privatekey.pem', 'w') as f:
    f.write(private_pem)
public_pem = rsa.publickey().exportKey()
with open('master-publickey.pem', 'w') as f:
    f.write(public_pem)

message = '{"date":"Fri Jun  1 04:04:23 EDT 2018", "md5":"2d7aa5d9dbb7bad9774fd8df5e544838", "last":"v1", "sign":""}'

# 对消息进行签名
h = MD5.new(message)
private_key = RSA.importKey(open('master-privatekey.pem').read())
signer = PKCS1_v1_5.new(private_key)
signature = signer.sign(h)

# 对消息进行签名验证
h = MD5.new(message)
public_key = RSA.importKey(open('master-publickey.pem', 'r').read())
verifier = PKCS1_v1_5.new(public_key)
if verifier.verify(h, signature):
    print "OK"
else:
    print "Invalid Signature"
Пример #38
0
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from urlparse import parse_qs

from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256 
from base64 import b64encode, b64decode

# Get port number from 1st argument ...
port = int(sys.argv[1])
# ... and private key filename from 2nd
key_location = sys.argv[2]

# Create signer
rsakey = RSA.importKey(open(key_location, "r").read())
signer = PKCS1_v1_5.new(rsakey)

# Sign token
def get_signature(token):
    digest = SHA256.new(token)
    sign = signer.sign(digest)
    return b64encode(sign)

# HTTP-request handler
class Handler(BaseHTTPRequestHandler):
    # GET-request
    def do_GET(self):
        # Veriffy path
        if self.path.find('/js/token-signer.js?token=') != 0:
            print 'wrong path'
            self.send_response(400)
Пример #39
0
def verify_with_RSA(username, msg, signature):
    key = get_pub_key(username)
    signer = PKCS1_v1_5.new(key)
    return signer.verify(mac_sha256(msg), signature)
Пример #40
0
def sign_transaction(owner, transaction):
    pr = RSA.importKey(
        binascii.unhexlify(base58_to_base16(read_keys(owner)['private_key'])))
    h = SHA256.new(owner.encode())
    signature = PKCS1_v1_5.new(pr).sign(h)
    return base16_to_base58(binascii.hexlify(signature).decode('ascii'))
Пример #41
0
import re

from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
from flask import g, request
import jwt

from .config import Config
from .errors import PermissionsError

from logs import get_logger
logger = get_logger(__name__)

jwt.verify_methods['SHA256WITHRSA'] = (
    lambda msg, key, sig: PKCS1_v1_5.new(key).verify(SHA256.new(msg), sig))
jwt.prepare_key_methods['SHA256WITHRSA'] = jwt.prepare_RS_key


def get_pub_key():
    pub_key = Config.get('web', 'apim_public_key')
    return RSA.importKey(base64.b64decode(pub_key))


TOKEN_RE = re.compile('Bearer (.+)')


def get_pub_key():
    pub_key = Config.get('web', 'apim_public_key')
    return RSA.importKey(base64.b64decode(pub_key))
Пример #42
0
def send(amount_input, recipient_input, keep_input, openfield_input):
    try:
        key
    except:
        top5 = Toplevel()
        top5.title("Locked")

        Label(top5, text="Wallet is locked", width=20).grid(row=0, pady=0)

        done = Button(top5, text="Cancel", command=top5.destroy)
        done.grid(row=1, column=0, sticky=W + E, padx=15, pady=(5, 5))

    app_log.warning("Received tx command")

    try:
        float(amount_input)
    except:
        top7 = Toplevel()
        top7.title("Invalid amount")
        Label(top7, text="Amount must be a number", width=20).grid(row=0, pady=0)
        done = Button(top7, text="Cancel", command=top7.destroy)
        done.grid(row=1, column=0, sticky=W + E, padx=15, pady=(5, 5))

    if encode_var.get() == 1:
        openfield_input = str(base64.b64encode(openfield_input))

    # alias check
    if alias_cb_var.get() == 1:
        conn = sqlite3.connect('static/ledger.db')
        conn.text_factory = str
        c = conn.cursor()
        c.execute("SELECT address FROM transactions WHERE openfield = ? ORDER BY block_height ASC, timestamp ASC LIMIT 1;",("alias="+recipient_input,)) #asc for first entry
        recipient_input = c.fetchone()[0]
        conn.close()
        app_log.warning("Fetched the following alias recipient: {}".format(recipient_input))

    # alias check

    if len(recipient_input) != 56:
        top6 = Toplevel()
        top6.title("Invalid address")
        Label(top6, text="Wrong address length", width=20).grid(row=0, pady=0)
        done = Button(top6, text="Cancel", command=top6.destroy)
        done.grid(row=1, column=0, sticky=W + E, padx=15, pady=(5, 5))
    else:

        app_log.warning("Amount: {}".format(amount_input))
        app_log.warning("Recipient: {}".format(recipient_input))
        app_log.warning("Keep Forever: {}".format(keep_input))
        app_log.warning("OpenField Data: {}".format(openfield_input))

        timestamp = '%.2f' % time.time()
        transaction = (timestamp,address,recipient_input, '%.8f' % float(amount_input),keep_input,openfield_input) #this is signed
        #print transaction

        h = SHA.new(str(transaction))
        signer = PKCS1_v1_5.new(key)
        signature = signer.sign(h)
        signature_enc = base64.b64encode(signature)
        app_log.warning("Client: Encoded Signature: {}".format(signature_enc))

        verifier = PKCS1_v1_5.new(key)
        if verifier.verify(h, signature) == True:
            if float(amount_input) < 0:
                app_log.warning("Client: Signature OK, but cannot use negative amounts")

            elif (float(amount_input) > float(balance)):
                app_log.warning("Mempool: Sending more than owned")

            else:
                app_log.warning("Client: The signature is valid, proceeding to save transaction, signature, new txhash and the public key to mempool")

                mempool = sqlite3.connect('mempool.db')
                mempool.text_factory = str
                m = mempool.cursor()

                m.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?)",(timestamp, address, recipient_input, '%.8f' % float(amount_input),signature_enc, public_key_hashed, keep_input, openfield_input))
                mempool.commit()  # Save (commit) the changes
                mempool.close()
                app_log.warning("Client: Mempool updated with a received transaction")
                #refresh() experimentally disabled
        else:
            app_log.warning("Client: Invalid signature")
        #enter transaction end
        refresh()
Пример #43
0
 def verify_transaction(transaction):
     public_key = RSA.importKey(binascii.unhexlify(transaction.sender))
     verifier = signer_alg.new(public_key)
     h = SHA256.new((str(transaction.sender) + str(transaction.recipient) + str(transaction.amount)).encode('utf8'))
     return verifier.verify(h, binascii.unhexlify(transaction.signature))
Пример #44
0
def assina(privada, receita):
    h = SHA256.new(receita)
    rsa = RSA.importKey(privada)
    signer = PKCS1_v1_5.new(rsa)
    signature = signer.sign(h)
    return signature
Пример #45
0
    is_float = 1
except ValueError:
    is_float = 0
    exit(1)

if len(str(recipient_input)) != 56:
    print("Wrong address length")
else:
    timestamp = '%.2f' % time.time()
    transaction = (str(timestamp), str(address), str(recipient_input),
                   '%.8f' % float(amount_input), str(operation_input),
                   str(openfield_input))  # this is signed
    # print transaction

    h = SHA.new(str(transaction).encode("utf-8"))
    signer = PKCS1_v1_5.new(key)
    signature = signer.sign(h)
    signature_enc = base64.b64encode(signature)
    txid = signature_enc[:56]

    print("Encoded Signature: %s" % signature_enc.decode("utf-8"))
    print("Transaction ID: %s" % txid.decode("utf-8"))

    verifier = PKCS1_v1_5.new(key)

    if verifier.verify(h, signature):
        if float(amount_input) < 0:
            print("Signature OK, but cannot use negative amounts")

        elif float(amount_input) + float(fee) > float(balance):
            print("Mempool: Sending more than owned")
Пример #46
0
    def begin_auth(self):
        # Deal with the beginning authentication
        try:

            self.read += self.recv(2048)
            #print("CALL AUTH")
            if b'\r\n' in self.read:
                authdata = self.read.split(b'\r\n')
                #print (authdata)
                # print(self.ctl.main_pw)
                signature = authdata[0]
                # TODO: fix an error in int(signature,16)
                try:
                    signer = PKCS1_v1_5.new(self.ctl.serverpub)
                    h = SHA256.new(self.ctl.main_pw)
                    verify = signer.verify(h, signature)
                except ValueError:
                    logging.debug("ValueError captured at server.py line 165")
                    verify = False
                if not verify:
                    logging.warning(
                        "Authentication failed, socket closing, case 1")
                    self.close()
                else:
                    try:
                        auth_cipher = PKCS_Cipher.new(self.ctl.clientpri)
                        sentinel = Random.new().read(32)
                        message = auth_cipher.decrypt(authdata[1], sentinel)
                        if len(message) != 16:
                            raise ValueError
                        self.cipher = AESCipher(
                            message, self.ctl.main_pw)
                        oldCipher = AESCipher_old(
                            message, self.ctl.main_pw)
                        self.full = False
                        idchar = authdata[2].decode('utf-8')
                        self.i = int(idchar)
                        self.ctl.newconn(self)
                        logging.debug(
                            "Authentication succeed, connection established")
                        self.send(
                            oldCipher.encrypt(b"2AUTHENTICATED" + authdata[2]))
                        self.read = None
                    except IOError:
                        # TODO: figure out why
                        logging.warning(
                            "Authentication failed, socket closing, , case 2")
                        self.handle_close()
            else:
                if len(self.read) == 0:
                    self.no_data_count += 1
        except BlockingIOError:
            pass

        except socket.error:
            logging.info("empty recv error")

        except Exception as err:
            raise err
            logging.error(
                "Authentication failed, due to error, socket closing")
            self.close()
Пример #47
0
text = response.text
ext = "access_token"
end = " }"
TokName = "Bearer " + text[text.find(ext) + 16:text.find(end) - 13]
#print(TokName) print the bearer token
#Generating Signature
message = sig.encode(
    'utf-8')  # See separate instruction on how to create this concatenation
digest = SHA256.new()
digest.update(message)

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

signer = PKCS1_v1_5.new(private_key)
sigBytes = signer.sign(digest)
signBase64 = b64encode(sigBytes)
#print(signBase64) Print the signature

#Sending money
url = "https://uat.jengahq.io/transaction/v2/remittance"

headers = {
    'Authorization': TokName,
    'content-type': "application/json",
    'signature': signBase64
}

payload = {
    "source": {
Пример #48
0
 def sign_transaction(self, sender, recipient, amount):
     # sign every transaction of current wallet owner
     signer = signer_alg.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')
Пример #49
0
def get_verifier(pubkey):
    src = crypto.dump_privatekey(crypto.FILETYPE_ASN1, pubkey)
    pub_der = DerSequence()
    pub_der.decode(src)
    key = RSA.construct((long(pub_der._seq[1]), long(pub_der._seq[2])))
    return PKCS1_v1_5.new(key)
Пример #50
0
 def sign_transaction(self):
     private_key = RSA.importKey(binascii.unhexlify(
         self.sender_private_key))
     signer = PKCS1_v1_5.new(private_key)
     h = SHA.new(str(self.to_dict()).encode('utf8'))
     return binascii.hexlify(signer.sign(h)).decode('ascii')
Пример #51
0
def rsa_verify(s, key, sig, mod=SHA256):
    key = RSA.importKey(key)
    hash = mod.new(s)
    return PKCS1_v1_5_SIG.new(key).verify(hash, sig)
Пример #52
0
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
from Crypto.Signature import PKCS1_v1_5

# Get the data to be signed
with open('message.txt', 'rb') as reader:
    message = reader.read()
    hashed = SHA256.new(message)

# Reading the private key to sign
private_key = RSA.import_key(open('rsa_private.pem').read())

# Signing and saving
signature = PKCS1_v1_5.new(private_key).sign(hashed)
with open('message.sig', 'wb') as sigfile:
    sigfile.write(signature)

# print(signature)
Пример #53
0
def query(action=None,
          command=None,
          args=None,
          method='GET',
          location=None,
          data=None):
    '''
    Make a web call to Joyent
    '''
    user = config.get_cloud_config_value(
        'user', get_configured_provider(), __opts__, search_global=False
    )

    password = config.get_cloud_config_value(
        'password', get_configured_provider(), __opts__,
        search_global=False
    )

    verify_ssl = config.get_cloud_config_value(
        'verify_ssl', get_configured_provider(), __opts__,
        search_global=False, default=True
    )

    ssh_keyfile = config.get_cloud_config_value(
        'private_key', get_configured_provider(), __opts__,
        search_global=False, default=True
    )

    ssh_keyname = config.get_cloud_config_value(
        'keyname', get_configured_provider(), __opts__,
        search_global=False, default=True
    )

    if not location:
        location = get_location()

    api_host_suffix = config.get_cloud_config_value(
        'api_host_suffix', get_configured_provider(), __opts__,
        search_global=False, default=JOYENT_API_HOST_SUFFIX
    )

    path = get_location_path(location=location, api_host_suffix=api_host_suffix)

    if action:
        path += action

    if command:
        path += '/{0}'.format(command)

    log.debug('User: {0!r} on PATH: {1}'.format(user, path))

    timenow = datetime.datetime.utcnow()
    timestamp = timenow.strftime('%a, %d %b %Y %H:%M:%S %Z').strip()
    with salt.utils.fopen(ssh_keyfile, 'r') as kh_:
        rsa_key = RSA.importKey(kh_)
    rsa_ = PKCS1_v1_5.new(rsa_key)
    hash_ = SHA256.new()
    hash_.update(timestamp)
    signed = base64.b64encode(rsa_.sign(hash_))
    keyid = '/{0}/keys/{1}'.format(user, ssh_keyname)

    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'X-Api-Version': JOYENT_API_VERSION,
        'Date': timestamp,
        'Authorization': 'Signature keyId="{0}",algorithm="rsa-sha256" {1}'.format(
            keyid,
            signed
        ),
    }

    if not isinstance(args, dict):
        args = {}

    # post form data
    if not data:
        data = json.dumps({})

    return_content = None
    result = salt.utils.http.query(
        path,
        method,
        params=args,
        header_dict=headers,
        data=data,
        decode=False,
        text=True,
        status=True,
        headers=True,
        verify=verify_ssl,
        opts=__opts__,
    )
    log.debug(
        'Joyent Response Status Code: {0}'.format(
            result['status']
        )
    )
    if 'Content-Length' in result['headers']:
        content = result['text']
        return_content = yaml.safe_load(content)

    return [result['status'], return_content]
Пример #54
0
def rsa_sign(s, key, mod=SHA256):
    key = RSA.importKey(key)
    hash = mod.new(s)
    return PKCS1_v1_5_SIG.new(key).sign(hash)
Пример #55
0
 def GetSigner(self):
     """Returns a PKCS1-V1_5 object for signing."""
     return PKCS1_v1_5.new(self.GetPrivateKey())
Пример #56
0
 def verificar_tx(transacao):
     chave_publica = RSA.importKey(binascii.unhexlify(transacao.pagador))
     verificar = PKCS1_v1_5.new(chave_publica)
     h = SHA256.new((str(transacao.pagador) + str(transacao.recebedor) +
                     str(transacao.valor)).encode('utf8'))
     return verificar.verify(h, binascii.unhexlify(transacao.assinatura))
Пример #57
0
 def sign(self):
     private_key = RSA.importKey(binascii.unhexlify(self._sender_private_key))
     signer = PKCS1_v1_5.new(private_key)
     hash_from_sign = SHA.new(str(self.to_dict()).encode('utf-8'))
     return binascii.hexlify(signer.sign(hash_from_sign)).decode('ascii')
def get_signature(key, data):
    return PKCS1_v1_5.new(key).sign(SHA.new(data))
Пример #59
0
def verify_transaction(owner, signature):
    pk = RSA.importKey(
        binascii.unhexlify(base58_to_base16(read_keys(owner)['public_key'])))
    h = SHA256.new(owner.encode())
    verifier = PKCS1_v1_5.new(pk)
    return verifier.verify(h, binascii.unhexlify(base58_to_base16(signature)))
Пример #60
0
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256

import paintings

from user_agents import USER_AGENTS

OK, CORRUPT, MUMBLE, DOWN, CHECKER_ERROR = 101, 102, 103, 104, 110

PORT = 80
TIMEOUT = 3

SCRIPT_PATH = pathlib.Path(__file__).parent

signer = PKCS1_v1_5.new(RSA.importKey(open("private.pem").read()))


def get_team_num(host):
    m = re.search(r"\d+\.\d+\.(\d+)\.\d+", host)
    if not m:
        return None

    return m.group(1)


def parse_jpg_bytes(body):
    try:
        painting = PIL.Image.open(BytesIO(body))
    except Exception as e:
        return None