コード例 #1
0
def main():
	(pubkey, privkey) = rsa.newkeys(512)
	test = "goob"
	signature = rsa.sign(test, privkey, 'SHA-1')
	msg = ("I, Cecil Lam, signed this sentence!")
	publicKey = pubkey
	return msg, signature, publicKey;
コード例 #2
0
ファイル: crypto.py プロジェクト: arkaic/hermes
def _asymmetric_encrypt_sign(plaintext, encrypt_key, sign_key):
    """ This function takes a plaintext message, encryption key (typically the 
        public key of the sender), and the signature key (typically the 
        private key) and produces the ciphertext using an RSA encryption 
        algorithm along with the signature. A key thing to keep in mind is that 
        the plaintext of the outputted ciphertext contains the signature in its 
        first 512 bytes. So the output of this function is something like this:
        ciphertext                   signature
        signature        message     signature
        ([   512 bytes   ][message]) [signature]
        Where the items in parenthesis are encrypted.
    Args:
        plaintext (bytearray): The plaintext message that is meant to be 
                               encrypted.
        encrypt_key (rsa.PublicKey): The key with which the message is to be 
                                     encrypted, the public key of the recipient.
        sign_key (rsa.PrivateKey): The key with which the message is to be 
                                   signed, the private key of the sender.
    Returns:
        bytearray: A bytearray containing the ciphertext of the message 
                   pre-pended with the signature.
        bytearray: A bytearray containing the plaintext signature of the 
                   message.
    """
    signature = sign(plaintext, sign_key, 'SHA-512')
    plaintext = signature + plaintext
    blocks = []
    for i in range(0, len(plaintext), ENCRYPTION_BLOCK_SIZE):
        blocks.append(encrypt(plaintext[i:i + ENCRYPTION_BLOCK_SIZE], 
                              encrypt_key))
    ciphertext = b''.join(blocks)
    return ciphertext, signature
コード例 #3
0
def main():
    (pub_key, priv_key) = key.newkeys(1024)
    raw = b'I, Chengeng Xiao, signed this sentence!'
    crypto = rsa.encrypt(raw, pub_key)
    signature = rsa.sign(raw, priv_key, 'SHA-256')
    msg = rsa.decrypt(crypto, priv_key)
    return msg, signature, pub_key
コード例 #4
0
ファイル: pykey.py プロジェクト: hoosteeno/gecko-dev
 def sign(self, data):
     """Returns a hexified bit string representing a
     signature by this key over the specified data.
     Intended for use with pyasn1.type.univ.BitString"""
     rsaPrivateKey = rsa.PrivateKey(self.RSA_N, self.RSA_E, self.RSA_D, self.RSA_P, self.RSA_Q)
     signature = rsa.sign(data, rsaPrivateKey, "SHA-256")
     return byteStringToHexifiedBitString(signature)
コード例 #5
0
 def rsa_signer(message):
     private_key = cloudfront_private_key
     return rsa.sign(
         message,
         rsa.PrivateKey.load_pkcs1(private_key.encode('utf8')),
         'SHA-1'
     )  # CloudFront requires SHA-1 hash
コード例 #6
0
ファイル: auth.py プロジェクト: cloudera/hue
 def _sign_string(self, string_to_sign):
     try:
         # We expect the private key to be the an PKCS8 pem formatted string.
         pem_bytes = self.credentials.private_key.encode('utf-8')
         if pem.detect(pem_bytes):
             _, _, der_bytes = pem.unarmor(pem_bytes)
             # In PKCS8 the key is wrapped in a container that describes it
             info = keys.PrivateKeyInfo.load(der_bytes, strict=True)
             # The unwrapped key is equivalent to pkcs1 contents
             key = rsa.PrivateKey.load_pkcs1(info.unwrap().dump(), 'DER')
         else:
             raise Exception('Not a PEM file')
     except:
         message = \
             "Failed to import private key from: '%s'. The private key is " \
             "corrupted or it is not in PKCS8 PEM format. The private key " \
             "was extracted either from 'env' (environment variables), " \
             "'shared-credentials-file' (a profile in the shared " \
             "credential file, by default under ~/.altus/credentials), or " \
             "'auth-config-file' (a file containing the credentials whose " \
             "location was supplied on the command line.)" % \
             self.credentials.method
         LOG.debug(message, exc_info=True)
         raise Exception(message)
     # We sign the hash.
     signature = rsa.sign(string_to_sign.encode('utf-8'), key, 'SHA-256')
     return urlsafe_b64encode(signature).strip().decode('utf-8')
def main():
    import rsa
    message = "I, Matthew Kyawmyint, signed this sentence!".encode('utf-8')

    (matt_pub, matt_priv) = rsa.newkeys(1024)
    signature = rsa.sign(message, matt_priv, 'SHA-256')
    return message, signature, matt_priv
コード例 #8
0
ファイル: utils.py プロジェクト: olivergs/django-apibase
def json_signed_post_data(apikey,privkey,data):
	"""
	Prepares a signed request post data

    :param apikey: API key
    :type apikey: :class:`unicode`
    :param pubkey: Private key for data signing
    :type pubkey: :class:`unicode` or :class:`rsa.PrivateKey`
    :param data: Data that will be signed and sent
    :type data: :class:`dict`, :class:`list` -- Any JSON serializable
	:returns: :class:`dict` with POST data

    .. note::
    	Data will be converted to JSON to be signed
	"""
	key=get_rsa_key(privkey)
	# Convert data to JSON
	jsondata=json.dumps(data)
	# Generate signature
	signature=rsa.sign(jsondata,key,'SHA-1')
	# Encode signature in BASE64
	b64signature=base64.b64encode(signature)
	# Prepare data
	return {
		'key': apikey,
		'data': jsondata,
		'signature': b64signature,
	}
コード例 #9
0
ファイル: utils.py プロジェクト: MrCreosote/auth
def sign_with_rsa(key_file, path, method, user_id, body='', query='', password=None):
    """
    Sign a request using the specified rsa key.

    :return: dictionary of headers
    """
    private_key = read_openssh_private_key(key_file, password)
    headers = {
            'X-Globus-UserId': user_id,
            'X-Globus-Sign': 'version=1.0'
            }
    timestamp = canonical_time(datetime.datetime.now())
    headers['X-Globus-Timestamp'] = timestamp
    hashed_body = base64.b64encode(hashlib.sha1(body).digest())
    hashed_path =  base64.b64encode(hashlib.sha1(path).digest())
    hashed_query = base64.b64encode(hashlib.sha1(query).digest())
    to_sign = ("Method:{0}\n"
        "Hashed Path:{1}\n"
        "X-Globus-Content-Hash:{2}\n"
        "X-Globus-Query-Hash:{3}\n"
        "X-Globus-Timestamp:{4}\n"
        "X-Globus-UserId:{5}")
    to_sign = to_sign.format(method,
            hashed_path,
            hashed_body,
            hashed_query,
            headers['X-Globus-Timestamp'],
            headers['X-Globus-UserId'])
    value = rsa.sign(to_sign, private_key, 'SHA-1')
    sig = b64encode(value)
    for i, line in enumerate(sig):
        headers['X-Globus-Authorization-{0}'.format(i)] = line
    return headers
コード例 #10
0
def _get_token():
    """Get the authentication token for windows vm xmlrpc client."""
    challenge = proxy.get_challenge()
    priv_key = rsa.PrivateKey.load_pkcs1(open(settings.WINDOWS_VM_SECRET).read())
    signature = rsa.sign(challenge, priv_key, 'SHA-512')
    sig_b64 = base64.b64encode(signature)
    return sig_b64
コード例 #11
0
ファイル: pycert.py プロジェクト: lgarner/mozilla-central
 def toDER(self):
     tbsCertificate = rfc2459.TBSCertificate()
     tbsCertificate.setComponentByName('version', self.getVersion())
     tbsCertificate.setComponentByName('serialNumber', self.getSerialNumber())
     tbsCertificate.setComponentByName('signature', self.getSignature())
     tbsCertificate.setComponentByName('issuer', self.getIssuer())
     tbsCertificate.setComponentByName('validity', self.getValidity())
     tbsCertificate.setComponentByName('subject', self.getSubject())
     tbsCertificate.setComponentByName('subjectPublicKeyInfo', self.getSubjectPublicKeyInfo())
     if self.extensions:
         extensions = rfc2459.Extensions().subtype(
             explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 3))
         count = 0
         for extension in self.extensions:
             extensions.setComponentByPosition(count, extension)
             count += 1
         tbsCertificate.setComponentByName('extensions', extensions)
     tbsDER = encoder.encode(tbsCertificate)
     rsaPrivateKey = rsa.PrivateKey(self.issuerRSA_N, self.issuerRSA_E, self.issuerRSA_D,
                                    self.issuerRSA_P, self.issuerRSA_Q)
     signature = rsa.sign(tbsDER, rsaPrivateKey, 'SHA-256')
     certificate = rfc2459.Certificate()
     certificate.setComponentByName('tbsCertificate', tbsCertificate)
     certificate.setComponentByName('signatureAlgorithm', self.getSignatureAlgorithm())
     certificate.setComponentByName('signatureValue', byteStringToHexifiedBitString(signature))
     return encoder.encode(certificate)
コード例 #12
0
ファイル: distribution.py プロジェクト: Kroisse/boto
    def _sign_string(message, private_key_file=None, private_key_string=None):
        """
        Signs a string for use with Amazon CloudFront.
        Requires the rsa library be installed.
        """
        try:
            import rsa
        except ImportError:
            raise NotImplementedError("Boto depends on the python rsa "
                                      "library to generate signed URLs for "
                                      "CloudFront")
        # Make sure only one of private_key_file and private_key_string is set
        if private_key_file and private_key_string:
            raise ValueError("Only specify the private_key_file or the private_key_string not both")
        if not private_key_file and not private_key_string:
            raise ValueError("You must specify one of private_key_file or private_key_string")
        # If private_key_file is a file name, open it and read it
        if private_key_string is None:
            if isinstance(private_key_file, basestring):
                with open(private_key_file, 'r') as file_handle:
                    private_key_string = file_handle.read()
            # Otherwise, treat it like a file
            else:
                private_key_string = private_key_file.read()

        # Sign it!
        private_key = rsa.PrivateKey.load_pkcs1(private_key_string)
        signature = rsa.sign(str(message), private_key, 'SHA-1')
        return signature
コード例 #13
0
ファイル: rsa_demo.py プロジェクト: Rockyzsu/base_function
def rsa_demo():
    (pubkey,privkey)=rsa.newkeys(1024)
    print('pubkey >>>> {}'.format(pubkey))
    print('privkey >>>> {}'.format(privkey))
    with open('pub.pem','w') as f:
        f.write(pubkey.save_pkcs1().decode())

    with open('priva.pem','w') as f:
        f.write(privkey.save_pkcs1().decode())

    message = 'Kill bill tonight'
    print("message encode {}".format(message.encode()))
    crypto=rsa.encrypt(message.encode(),pubkey)

    print('密文{}'.format(crypto))

    # 解密
    e_message = rsa.decrypt(crypto,privkey)
    print("解密后{}".format(e_message.decode()))

    private_sign = rsa.sign(message.encode(),privkey,'SHA-1')
    print('签名:{}'.format(private_sign))

    print('验证签名')
    print(rsa.verify(message.encode(),private_sign,pubkey))
コード例 #14
0
ファイル: crypto.py プロジェクト: No9/drogulus
def get_signed_item(key, value, public_key, private_key, expires=None):
    """
    Returns a copy of the passed in key/value pair that has been signed using
    the private_key and annotated with metadata (a timestamp indicating when
    the message was signed, a timestamp indicating when the item should expire,
    the drogulus version that created the item, a sha512 key used by the DHT,
    the public_key and the signature).

    The expiration timestamp is derived by adding the (optional) expires
    number of seconds to the timestamp. If no expiration is specified then the
    "expires" value is set to 0.0 (expiration is expressed as a float).
    """
    signed_item = {
        'name': key,
        'value': value,
        'created_with': get_version(),
        'public_key': public_key,
        'timestamp': time.time(),
        'key': construct_key(public_key, key)
    }
    expires_at = 0.0  # it's a float, dammit
    t = type(expires)
    if expires and (t == int or t == float) and expires > 0.0:
        expires_at = signed_item['timestamp'] + expires
    signed_item['expires'] = expires_at
    root_hash = _get_hash(signed_item).hexdigest()
    key = rsa.PrivateKey.load_pkcs1(private_key.encode('ascii'))
    sig = binascii.hexlify(rsa.sign(root_hash.encode('ascii'), key,
                                    'SHA-512')).decode('ascii')
    signed_item['signature'] = sig
    return signed_item
コード例 #15
0
ファイル: storage_server.py プロジェクト: yawkat/password
 def store(self, obj):
     f = io.BytesIO()
     _writeblock(f, self.public_key.save_pkcs1(format="DER"))
     _writeblock(f, rsa.sign(obj, self.private_key, HASH))
     _writeblock(f, obj)
     request = urllib.request.Request(self.address, data=f.getvalue(), method="PUT")
     urllib.request.urlopen(request)
コード例 #16
0
ファイル: views.py プロジェクト: mabdrabo/Tneatar
def send_message(request):
    '''
        The message is encrypted using the recipient's Public key,
        the message is digitally signed using the sender's Private key,
        the recipient must use his own Private key to decrypt,
        and use the sender's Public key to verify ownership

        Messages are saved in DB in Base64,
        so it needs decoding before decryption
    '''
    user = logged_in_user(request)
    if user:
        if 'direct_message' in request.POST and 'recipient_username' in request.POST:
            try:
                recipient = User.objects.get(username=request.POST['recipient_username'])
                crypto = rsa.encrypt(request.POST['direct_message'].encode('utf-8'), recipient.get_public_key())
                signature = rsa.sign(crypto, user.get_private_key(), 'SHA-1')
                encryp_tneata = 'MMMMM'.join([crypto, signature])
                encryp_tneata = encryp_tneata.encode('Base64')
                print encryp_tneata
                dmsg = DirectMessage.objects.create(sender=user, recipient=recipient,  content=encryp_tneata)
                return dashboard(request, username=recipient.username, dic={'success':'message sent!'})
            except User.DoesNotExist:
                return render_to_response('master.html', {'error': 'user not found'}, RequestContext(request))
        return render_to_response('master.html', {'error': 'error'}, RequestContext(request))
    return user
def main():
    message = "I, Raymund Alksninis, signed this sentence!"
    message_enc = message.encode('utf-8')
    (publicKey, privateKey) = rsa.newkeys(1024)
    signature = rsa.sign(message_enc, privateKey, 'SHA-256')

    return(message, signature, publicKey)
コード例 #18
0
ファイル: views.py プロジェクト: mabdrabo/Tneatar
def tneat(request):
    '''
        The Tneata is digitally signed using the owner's Private key,
        the followers can use the owner's Public key to verify
        the ownership of the tneata to the owner

        Tneatas are saved in DB in Base64,
        so it needs decoding before verification
    '''
    logged_user = logged_in_user(request)
    if isinstance(logged_user, User):
        if 'tneata' in request.POST:
            t = request.POST['tneata'].encode('utf-8')
            if len(t) > 0:
                tags = extract_hashtags(t)
                hashtags = map(lambda tag: HashTag.objects.get_or_create(name=tag)[0], tags)
                signature = rsa.sign(t, logged_user.get_private_key(), 'SHA-1')
                signed_tneata = 'MMMMM'.join([t, signature])
                signed_tneata = signed_tneata.encode('Base64')
                tneat = Tneata.objects.create(user=logged_user, content=signed_tneata)
                [tag.add_tneata(tneat) for tag in hashtags]
                return dashboard(request, dic={'success':'your tneata has just been published'})
            else:
                return dashboard(request, dic={'error':'you can not publish a blank tneata'})
        else:
            return dashboard(request, dic={'error':'error, try again later.'})
    else:
        return logged_user
def main():
    (pcKey, pKey) = rsa.newkeys(1024)
    messg = 'I, Graciela Vargas Roque, signed this message!'
    messg = messg.encode('utf-8')
    sig = rsa.sign(messg, pKey, 'SHA-256')

    return messg, sig, pcKey
コード例 #20
0
def sign(message):
	#message = base92.encode(message)
	privatefile = FileUtil.open(common.CONFIG_PRIKEY,'r')
	keydata = privatefile.read()
	prikey = rsa.PrivateKey.load_pkcs1(keydata)
	signature = rsa.sign(message, prikey, 'SHA-1')
	return base92.encode(signature)
コード例 #21
0
ファイル: my-rsa.py プロジェクト: 54017/distributedComputing
def main():
    (publicKey, privateKey) = rsa.newkeys(1024)

    pub = publicKey.save_pkcs1()
    pubfile = open("public.pem", "w+")
    pubfile.write(pub)
    pubfile.close()

    pri = privateKey.save_pkcs1()
    prifile = open("private.pem", "w+")
    prifile.write(pri)
    prifile.close()

    prifile = open("private.pem", "r")
    p = prifile.read()
    privateKey = rsa.PrivateKey.load_pkcs1(p)
    prifile.close()

    pubfile = open("public.pem", "r")
    p = pubfile.read()
    publicKey = rsa.PublicKey.load_pkcs1(p)
    pubfile.close()

    message = "lalalalal"

    secret = rsa.encrypt(message, publicKey)
    non_secret = rsa.decrypt(secret, privateKey)
    print non_secret

    signature = rsa.sign(message, privateKey, "SHA-1")
    rsa.verify("lalalalal", signature, publicKey)
コード例 #22
0
    def signature(self,content,private_key_file):
        """
            signature the content
        """

            # get private key and signature
        private_key = None
        with open(private_key_file,"r") as fp:
            text = fp.read()
            private_key = rsa.PrivateKey.load_pkcs1(text)

        signatured_content = rsa.sign(content,private_key,self.setting["HASH"])
        # set preamble content 
        
        # self.msg.preamble = MIMEText(content)
        self.msg.preamble = "this is from Qingluan'client .. written by Py"
        # self.msg.add_header("Content-type","text/plain")
        # set payload 
        # print(signatured_content)

        # with open("signed.p1s","wb") as fp:
        #     fp.write(signatured_content)
        
        # signatured_payload = self.add_attachmen("signed.p1s") # self.gen_content_mime(signatured_content,"application/python2.7-rsa-sign")
        signatured_payload = self.gen_content_mime(signatured_content,"application/python2.7-rsa-sign")
        self.msg.attach(signatured_payload)

        # change main mime type
        self.msg.set_type("multipart/signed")
        self.msg.set_param("micalg",self.setting["HASH"])
        return signatured_content
def main():

    (publicKey, privateKey) = key.newkeys(1024)
    sentence = b'I, Ziyue Gao, signed this sentence!'
    sig = rsa.sign(sentence, privateKey, 'SHA-256')
    enc = rsa.encrypt(sentence, publicKey)
    return sentence, sig, publicKey
def main():

    (publicKey, privateKey) = rsa.newkeys(1024)
    msg = ('I, Ran, signed this sentence!').encode('utf-8')
    signature = rsa.sign(msg, privateKey, 'SHA-256')

    return [msg, signature, publicKey]
コード例 #25
0
ファイル: utils.py プロジェクト: lisongwei1593/demo
def makeSign(m, sign_type='md5'):
    """

    :param m: 待签名参数
    :param sign_type: 签名类型
    :return: 签名。如果类型为RSA,返回的是base64编码后经quote编码的签名
    """
    ks = m.keys()
    ks.sort()
    ls = []
    for k in ks:
        if m[k] not in (None, ''):
            if isinstance(m[k], unicode):
                ls.append('{k}={v}'.format(k=k, v=m[k].encode('utf8')))
            else:
                ls.append('{k}={v}'.format(k=k, v=m[k]))

    # ls = ['{k}={v}'.format(k=k, v=m[k]) for k in ks if m[k] not in (None, '')]
    s = '&'.join(ls)
    if not sign_type or sign_type.lower() == 'md5':
        s += AliPayConfig.MD5_KEY
        return hashlib.md5(s).hexdigest().lower(), ''
    elif sign_type.lower() == 'rsa':
        key = rsa.PrivateKey.load_pkcs1(AliPayConfig.MY_RSA_PRIVATE_KEY)
        sign_r = rsa.sign(s, key, 'SHA-1')
        # sign = base64.b64encode(sign_r)
        sign = urllib.quote(base64.b64encode(sign_r))
        return sign, s
コード例 #26
0
ファイル: views.py プロジェクト: mabdrabo/Tneatar
def retneat(request, tneata_id):
    logged_user = logged_in_user(request)
    if isinstance(logged_user, User):
        try:
            tn = Tneata.objects.get(pk=tneata_id)
            original_user = tn.user
            t_content = tn.content.decode('Base64')
            text, signature = t_content.split('MMMMM')
            try:
                if rsa.verify(text, signature, original_user.get_public_key()):
                    t = text
                    if len(t) > 0:
                        tags = extract_hashtags(t)
                        hashtags = map(lambda tag: HashTag.objects.get_or_create(name=tag)[0], tags)
                        signature = rsa.sign(t, logged_user.get_private_key(), 'SHA-1')
                        signed_tneata = 'MMMMM'.join([t, signature])
                        signed_tneata = signed_tneata.encode('Base64')
                        tneat = Tneata.objects.create(user=logged_user, content=signed_tneata, retneat_from = original_user)
                        [tag.add_tneata(tneat) for tag in hashtags]
                        return dashboard(request, dic={'success':'Retweet success'})
            except:
                return dashboard(request, dic={'error':'Integrity violation'})
        except Tneata.DoesNotExist:
            return dashboard(request, dic={'error':'error, try again later.'})
    return logged_user
def main():

    (my_pubkey, my_privkey) = rsa.newkeys(1024)
    message = 'I, Bryan Ngo, signed this message'.encode('utf-8')
    sign = rsa.sign(message, my_privkey, "SHA-256")
    rsa.verify(message, sign, my_pubkey)
    return message, sign, my_pubkey
コード例 #28
0
ファイル: gevent_test.py プロジェクト: ideascf/play
def do_with_rsa():
    global cnt
    _print('BEFORE sign', cnt)
    ret_sign = rsa.sign(TEST_DATA, g_pri_key, 'SHA-1')
    _print('AFTER sign', cnt)

    _print('BEFORE urlopen', cnt)
    try:
        urllib2.urlopen(
            TEST_URL,
            TEST_DATA,
            # timeout=10
        ).read()
    except Exception as e:
        _print('IN exception', e)
        return False
    _print('AFTER urlopen', cnt)

    _print('BEFORE verify', cnt)
    rsa.verify(TEST_DATA, ret_sign, g_pub_key)
    _print('AFTER verify', cnt)

    cnt += 1

    return True
コード例 #29
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

    import rsa
    key = rsa.PrivateKey.load_pkcs1(rsa_private_key)
    sig = rsa.sign(base_string, key, 'SHA-1')
    return binascii.b2a_base64(sig)[:-1]
コード例 #30
0
	def activeAuthenticate(self):
		# Grab key for receiver username and compare it against what the receiver gave us.
		key = self.peer.getUserKeyFor(self.receiver_username)

		# Friend was added but never authenticated:
		if key == None:
			my_congruent_state = "True"
		else:
			my_congruent_state = str(self.receiver_user_key == key)

		# If key is empty or matches, proceed.
		if my_congruent_state == "True":
			self.sock.sendall("True")
			# Receive congruent state message from receiver.
			their_congruent_state = self.sock.recv(self.message_size)

			# If their state is congruent, proceed.
			if their_congruent_state == "True":
				# Compose verifier int V and send it.
				my_verifier = str(random.getrandbits(512))
				self.sock.sendall(my_verifier)

				# Receive initiator's verifier string
				their_verifier = self.sock.recv(self.message_size)

				# Sign and send
				my_signature = rsa.sign(their_verifier, self.peer.getPrivateKey(), 'SHA-1')
				self.sock.sendall(my_signature) 

				# Receive initiator's signature
				their_signature = self.sock.recv(self.message_size)

				# Verify the signature and send the response.
				try:
					my_decision = rsa.verify(my_verifier, their_signature, self.receiver_user_key)
					self.sock.sendall(str(my_decision))
				except rsa.VerificationError:
					self.sock.sendall("False")
					self.peer.endChat(self.receiver_username)
					return False

				# Receive initiator's authorization status.
				their_decision = self.sock.recv(self.message_size)
				if not their_decision == "True":
					self.peer.endChat(self.receiver_username)
					return False
				else:
					return True
			# Their state was incongruent, session should end.
			else:
				if not self.gui == None:
					self.gui.showMessage("Authentication failure: your credentials were rejected.")
				self.peer.endChat(self.receiver_username)
				return False
		# State is incongruent; reject session.
		else: 
			self.sock.sendall("False")
			self.peer.endChat(self.receiver_username)
			return False
コード例 #31
0
ファイル: alipay_rsa.py プロジェクト: hmjrun/djangosite
 def make_sign(slef, data):
     """
     签名
     :param message:
     :return:
     """
     from alipay_py import alipay_config
     private_key = rsa.PrivateKey._load_pkcs1_pem(alipay_config.RSA_PRIVATE)
     sign = rsa.sign(data.encode('utf-8'), private_key, SIGN_TYPE)
     b64sing = base64.b64encode(sign)
     return b64sing
コード例 #32
0
    def get_sign(self, sign_str):
        with open('keys/private.txt', 'r') as f:
            privkey = rsa.PrivateKey.load_pkcs1(f.read())

        sign_1 = rsa.sign(sign_str.encode('utf-8'),
                          privkey,
                          hash_method='SHA-256')

        # print("+"*50)
        sign = base64.b64encode(sign_1).decode('utf-8')
        return sign
コード例 #33
0
 def sign_trust(self, node):
     print(node.get_private_key())
     content = "{}{}{}{}{}{}{}".format(self.transaction_type,
                                       self.issuing_public_key,
                                       self.issuing_signature,
                                       node.public_key),
     self.reliable_node_signature = rsa.sign(content.encode("utf-8"),
                                             node.get_private_key(),
                                             'SHA-1')
     self.timestamp = date.datetime.now()
     self.save()
コード例 #34
0
ファイル: alipay_core.py プロジェクト: kay-yi/flashsale
def make_sign(message):
    """
    签名
    :param message:
    :return:
    """
    message = message.encode("utf-8")
    private_key = rsa.PrivateKey._load_pkcs1_pem(RSA_PRIVATE)
    sign = rsa.sign(message, private_key, SIGN_TYPE)
    b64sing = base64.b64encode(sign)
    return b64sing
コード例 #35
0
    def _make_sign(self, params, **kwargs):

        private_key = rsa.PrivateKey.load_pkcs1(
            kwargs.get('private_key', None) or self.private_key)
        # print(self.private_key)
        # breakpoint()
        sign = base64.b64encode(
            rsa.sign(params.encode(), private_key, "SHA-256")).decode('gbk')

        # print(sign)
        return sign
コード例 #36
0
 def sign_miner_trust(self, node, step):
     self.validation_step = step
     self.validation_public_key = node.public_key.n
     content = "{}{}{}{}{}{}{}".format(self.identify, self.born_step,
                                       self.transaction_type,
                                       self.origin_public_key,
                                       self.origin_signature,
                                       node.public_key,
                                       self.validation_step)
     self.validation_signature = rsa.sign(content.encode("utf-8"),
                                          node.get_private_key(), 'SHA-1')
コード例 #37
0
ファイル: client.py プロジェクト: favoretti/transip-api
    def _sign(self, message):
        """ Uses the decrypted private key to sign the message. """
        signature = None
        with open(self.private_file) as private_key:
            keydata = private_key.read()
            privkey = rsa.PrivateKey.load_pkcs1(keydata)
            signature = rsa.sign(message, privkey, 'SHA-512')
            signature = base64.b64encode(signature)
            signature = urllib.quote_plus(signature)

        return signature
コード例 #38
0
def sign_with_rsa2(private_key, sign_content, charset):
    if PYTHON_VERSION_3:
        sign_content = sign_content.encode(charset)
    private_key = fill_private_key_marker(private_key)
    signature = rsa.sign(sign_content,
                         rsa.PrivateKey.load_pkcs1(private_key, format='PEM'),
                         'SHA-256')
    sign = base64.b64encode(signature)
    if PYTHON_VERSION_3:
        sign = str(sign, encoding=charset)
    return sign
コード例 #39
0
ファイル: message.py プロジェクト: vulogov/thebund
 def seal(self, key=None):
     if not key:
         key = self.keys.keys.key
     data = self.dumps()
     sign = rsa.sign(data, key, 'SHA-512')
     return msgpack.packb({
         'seal': True,
         'msg': data,
         'sign': sign,
         'name': self.keys.name
     })
コード例 #40
0
 def e(self, data, key, method="MD5"):
     # 1.得到文件数据签名,数据为字节码
     data = self.__add_to_16(data)
     sign = rsa.sign(data, self.__RSA[1], method)
     # 2.使用发送者私钥加密数字签名
     # 3.对称随机密码加密数字签名和数据内容
     aes = AES.new(self.__add_to_16(self.__pwd), AES.MODE_ECB)  # 初始化加密器
     data = aes.encrypt(sign + data)
     # 4.使用接收者公钥加密随机对称密码
     pwd_safe = rsa.encrypt(self.__add_to_16(self.__pwd), key)
     return pwd_safe + data
コード例 #41
0
 def __init__(self, sender, to, amount, priv, phash="no one", n=0):
     self.data = {'from': to_str(sender), 'to': to, 'amount': amount}
     self.prev_hash = phash
     self.n = n
     self.nonce = 0
     self.time = time()
     self.miner = sender
     self.hash()
     self.sign = rsa.sign(
         (json.dumps(self.data) + str(self.time)).encode('utf8'), priv,
         'SHA-256')
コード例 #42
0
    def sign_string(self, message, priv_key_string):
        # Make sure message and private key are in bytes format so we can support more inputs
        if not hasattr(message, 'decode'):
            message = message.encode('utf-8')

        if not hasattr(priv_key_string, 'decode'):
            priv_key_string = priv_key_string.encode('utf-8')

        key = rsa.PrivateKey.load_pkcs1(priv_key_string)
        signature = rsa.sign(message, key, 'SHA-1')
        return self.aws_safe_b64encode(signature).decode('utf-8')
コード例 #43
0
def generate_edge(target, source):
    signature = rsa.sign(pubkeys[target].encode(),
                         to_priv_pem_key(privkeys[source]), 'SHA-1')
    edge = {
        "from": nodes[source]["pubkey"],
        "to": nodes[target]["pubkey"],
        "trusted": True,
        "message": pubkeys[target],
        "signature": signature.hex()
    }
    return edge
コード例 #44
0
 def sign(self, message, priv_key=None, hash_method='SHA-1'):
     """
     生成明文的哈希签名以便还原后对照
     :param message: str
     :param priv_key:
     :param hash_method: 哈希的模式
     :return:
     """
     if None == priv_key:
         priv_key = self.privkey
     return rsa.sign(message.encode(), priv_key, hash_method)
コード例 #45
0
ファイル: cli.py プロジェクト: joshis1/Python
    def perform_operation(self, indata: bytes, priv_key: rsa.key.AbstractKey,
                          cli_args: Indexable) -> bytes:
        """Signs files."""
        assert isinstance(priv_key, rsa.key.PrivateKey)

        hash_method = cli_args[1]
        if hash_method not in HASH_METHODS:
            raise SystemExit("Invalid hash method, choose one of %s" %
                             ", ".join(HASH_METHODS))

        return rsa.sign(indata, priv_key, hash_method)
コード例 #46
0
def _make_signed_jwt(payload, pkey):
    """Wraps |payload| dict into signed JSON Web Token."""
    # See http://self-issued.info/docs/draft-jones-json-web-token.html.
    as_json = lambda d: json.dumps(d, sort_keys=True, separators=(',', ':'))
    b64encode = lambda d: base64.urlsafe_b64encode(d).rstrip('=')
    to_sign = '%s.%s' % (b64encode(as_json({
        'typ': 'JWT',
        'alg': 'RS256'
    })), b64encode(as_json(payload)))
    signature = rsa.sign(to_sign, pkey, 'SHA-256')
    return '%s.%s' % (to_sign, b64encode(signature))
コード例 #47
0
 def post_signed_report(self, message, user, private_key_pkcs):
     pkey = rsa.PrivateKey.load_pkcs1(private_key_pkcs)
     signed_message = hexlify(rsa.sign(message, pkey, 'SHA-1'))
     signed_post_url = "http://localhost:9000/api/signedreport/"
     signed_data = {"report": message, "signedreport": signed_message}
     resp_signed = requests.post(signed_post_url,
                                 data=signed_data,
                                 auth=(user, ''))
     if resp_signed.status_code == 200:
         return resp_signed.content
     else:
         return {"Error": resp_signed.content}
コード例 #48
0
 def encrypt(params):
     """
     数据加密
     :param params:
     :return:
     """
     signature = rsa.sign(params.encode(), ENCRYPT_KEY.get('public_key'), 'SHA-1')
     data = {
         'params': params,
         'signature': signature
     }
     return rsa.encrypt(str(data).encode(), ENCRYPT_KEY.get('private_key'))
コード例 #49
0
ファイル: genBase.py プロジェクト: mancanjua/PAI1
def sign_database():
    # Loads the private key
    with open(conf.PRIVATE_KEY, "rb") as private_key_dump:
        private_key = pickle.load(private_key_dump)

    # Sign the database of hash
    with open(conf.DATABASE, 'rb') as msgfile:
        signature = rsa.sign(msgfile, private_key, 'SHA-256')

    # Writes the signature in a file.
    with open(conf.DATABASE_SIG, "wb") as signature_file:
        signature_file.write(signature)
コード例 #50
0
    def test_sign_verify(self):

        message = u"Euro=\u20ac ABCDEFGHIJKLMNOPQRSTUVWXYZ".encode('utf-8')
        print "\tMessage:   %s" % message

        signed = rsa.sign(message, self.priv)
        print "\tSigned:    %s" % signed

        verified = rsa.verify(signed, self.pub)
        print "\tVerified:  %s" % verified

        self.assertEqual(message, verified)
コード例 #51
0
    def encrypt(cls, message):
        public_key_data, private_key_data = cls.get_keys_raw()

        private_rsa_key = rsa.PrivateKey.load_pkcs1(private_key_data)
        signature = rsa.sign(message, private_rsa_key, 'SHA-512')
        iv, aes_key, encrypted_message = aes_cbc_encrypt(signature + message)

        public_key = RSA.importKey(public_key_data.strip())
        public_cipher = PKCS1_OAEP.new(public_key)
        encrypted_key = public_cipher.encrypt(aes_key)

        return base64.b64encode(iv + encrypted_key + encrypted_message)
コード例 #52
0
    def encrypt(self, binary, use_sign=True):
        """Encrypt binary data.

        **中文文档**

        - 发送消息时只需要对方的pubkey
        - 如需使用签名, 则双方都需要持有对方的pubkey 
        """
        token = rsa.encrypt(binary, self.his_pubkey)  # encrypt it
        if use_sign:
            self.sign = rsa.sign(binary, self.my_privkey, "SHA-1")  # sign it
        return token
コード例 #53
0
ファイル: myras.py プロジェクト: chenfengqiannian/djdianjiang
def sign(message):
    print os.path.join(settings.BASE_DIR, 'rsa_public_key.pem')
    op = os.path.join(settings.BASE_DIR, 'rsa_public_key.pem')
    oi = os.path.join(settings.BASE_DIR, 'rsa_private_key.pem')

    with open(oi) as privatefile:
        p = privatefile.read()
        privkey = rsa.PrivateKey.load_pkcs1(p)
    signature = rsa.sign(message, privkey, "SHA-1")
    print base64.b64encode(signature)

    return base64.b64encode(signature)
コード例 #54
0
ファイル: votes.py プロジェクト: 6200m/File-Maker
def sign_file(name):
    final = name + '.bin'
    print("Processing " + final + " ...")
    file = open(name, 'rb')
    copy = file.read()
    file.close()
    print("Calculating CRC32 ...")
    crc32 = format(binascii.crc32(copy) & 0xFFFFFFFF, '08x')
    print("Calculating Size ...")
    size = os.path.getsize(name) + 12
    dest = open(final + '-1', 'wb+')
    dest.write(u32(0))
    dest.write(u32(size))
    dest.write(binascii.unhexlify(crc32))
    dest.write(copy)
    os.remove(name)
    dest.close()
    print("Compressing ...")
    nlzss.encode_file(final + '-1', final + '-1')
    file = open(final + '-1', 'rb')
    new = file.read()
    dest = open(final, "wb+")
    key = open(config["key_path"], 'rb')
    print("RSA Signing ...")
    private_key = rsa.PrivateKey.load_pkcs1(key.read(),
                                            "PEM")  # Loads the RSA key.
    signature = rsa.sign(new, private_key,
                         "SHA-1")  # Makes a SHA1 with ASN1 padding. Beautiful.
    dest.write(
        b"\0" * 64
    )  # Padding. This is where data for an encrypted WC24 file would go (such as the header and IV), but this is not encrypted so it's blank.
    dest.write(signature)
    dest.write(new)
    dest.close()
    file.close()
    key.close()
    if config["production"]:
        if file_type == "q" or file_type == "r":
            if arg == "n":
                folder = str(country_code).zfill(3)
            elif arg == "w":
                folder = "world"
            subprocess.call([
                "mkdir", "-p",
                "%s/%s/%s" % (config["file_path"], folder, get_year())
            ])  # If folder for the year does not exist, make it.
            path = "/".join([config["file_path"], folder, get_year(), final])
        elif file_type == "v":
            path = "/".join(
                [config["file_path"],
                 str(country_code).zfill(3), final])
    subprocess.call(["mv", final, path])
    os.remove(final + '-1')
コード例 #55
0
def sign(msg, path=False):
    if path == False:
        path = get_cur_path() + '/cfg/pk.pem'

    try:
        with open(path) as pkfile:
            pkkey = rsa.PrivateKey.load_pkcs1(pkfile.read())
        signature = rsa.sign(msg, pkkey, 'SHA-1')
    except:
        return False
    else:
        return signature
コード例 #56
0
def respond_handshake(s):
    message = s.recv(256)
    msgDecrypted = rsa.decrypt(message, private_key)
    msgDecoded = msgDecrypted.decode()
    numbers = msgDecoded.split(" + ")
    a = int(numbers[0])
    b = int(numbers[1])
    response = a + b

    response = bytes(str(response), "utf-8")
    signature = rsa.sign(response, private_key, 'SHA-256')
    s.send(signature)
コード例 #57
0
def encrypt_t(privkey, pubkey_t, message, need_sig):
    third = rsa.PublicKey.load_pkcs1(pubkey_t)
    ciphertext = prefix_m + b64encode(
        rsa.encrypt(message.encode('utf-8'), third)) + suffix_m

    if need_sig:
        signature = b64encode(
            rsa.sign(message.encode('utf-8'), privkey, encryption_method))
        ciphertext = ciphertext + prefix_s + signature + suffix_s

    ciphertext = ciphertext.decode()
    return True, ciphertext
コード例 #58
0
ファイル: tuputech.py プロジェクト: michaelWGR/projectmc
    def __sign(self):
        """get the signature"""
        timestamp = datetime.datetime.now()
        nonce = random.randint(1 << 4, 1 << 32)
        sign_string = "%s,%s,%s" % (self.__secret_id, timestamp, nonce)
        signature = base64.b64encode(rsa.sign(sign_string.encode("utf-8"), self.__private_key, 'SHA-256'))

        return {
            "timestamp": timestamp,
            "nonce": nonce,
            "signature": signature
        }
コード例 #59
0
ファイル: cmoney.py プロジェクト: noahfrench/DucksBux
def verify():
	sourceFilename = sys.argv[1]
	statementFilename = sys.argv[2]

	# Get the private key from the sourceFilename wallet
	with open(sourceFilename, mode='rb') as privatefile:
		keydata = privatefile.read()
		privkey = rsa.PrivateKey.load_pkcs1(keydata)

	# Get the message used to create the signature and get the alleged signature and other things
	statementFile = open(statementFilename, "r")
	lines = statementFile.readlines()
	statementFile.close()
	sourceAddress = lines[0].strip().split()[1]
	fundRequest = (sourceAddress == "Bank_of_1,000_Quacks")
	destAddress = lines[1].strip().split()[1]
	amount = lines[2].strip().split()[1]

	if fundRequest:
		allegedSig = "It's a fund request!"
	else:
		allegedSig = lines[4]

	transactionList = lines[:3]
	transactionMessage = ""
	for line in transactionList:
		transactionMessage += line

	#Calculate the theoretical signature and check it against the alleged signature
	theoreticalSig = str(binascii.hexlify(rsa.sign(transactionMessage.encode('ascii'), privkey, "SHA-256")).decode('ascii'))

	validSig = (theoreticalSig == allegedSig)

	# Check to make sure the source has enough funds
	enoughFunds = (balance(sourceAddress) - float(amount)) > 0.0

	# If valid signature and enough funds, make a record in the ledger!
	if validSig and enoughFunds:
		ledgerFile = open("ledger.txt", "a")
		ledgerFile.write(sourceAddress + " transfered " + amount + " to " + destAddress + "\n")
		ledgerFile.close()
		print("The transaction in file '" + statementFilename + "' with wallet '" + sourceFilename + "' is valid, and was written to the ledger")
	elif fundRequest:
		ledgerFile = open("ledger.txt", "a")
		ledgerFile.write(sourceAddress + " transferred " + amount + " to " + destAddress + "\n")
		ledgerFile.close()
		print("Any fund request (i.e., from Bank_of_1,000_Quacks) is considered valid; written to the ledger")
	elif not validSig:
		print("The signature is not valid.")
	elif not enoughFunds:
		print("The sender does not have sufficient funds in their DucksBux wallet.")

	return None
コード例 #60
0
ファイル: run.py プロジェクト: waseem18/drogulus
def make_headers(path, pubkey, privkey):
    """
    Returns a dict object containing the headers needed to authenticate and
    validate an incoming HTTP request for the web based API.
    """
    headers = {}
    pubkey_hash = sha512(pubkey.save_pkcs1()).hexdigest()
    headers['AUTHORIZATION'] = pubkey_hash
    signature = rsa.sign(path.encode('ascii'), privkey, 'SHA-512')
    headers['VALIDATION'] = binascii.hexlify(signature).decode('ascii')
    assert False
    return headers