예제 #1
0
 def action_validate(self, cr, uid, ids, context=None):
     if context is None:
         context = {}
     pairkeys = self.read(cr, uid, ids, ["key", "pub"], context=context)
     confirm_ids = []
     for pk in pairkeys:
         # Check public key
         try:
             PUB = BIO.MemoryBuffer(pk["pub"].encode("ascii"))
             RSA.load_pub_key_bio(PUB)
             pub = True
         except:
             pub = False
         # Check private key
         try:
             RSA.load_key_string(pk["key"].encode("ascii"))
             key = True
         except:
             key = False
         if key or pub:
             confirm_ids.append(pk["id"])
         else:
             raise osv.except_osv(
                 _("Invalid action !"),
                 _("Cannot confirm invalid pairkeys. You need provide private and public keys in PEM format."),
             )
     self.write(cr, uid, confirm_ids, {"state": "confirmed"}, context=context)
     return True
예제 #2
0
 def action_validate(self, cr, uid, ids, context=None):
     if context is None:
         context = {}
     pairkeys = self.read(cr, uid, ids, ['key', 'pub'], context=context)
     confirm_ids = []
     for pk in pairkeys:
         # Check public key
         try:
             PUB = BIO.MemoryBuffer(pk['pub'].encode('ascii'))
             RSA.load_pub_key_bio(PUB)
             pub = True
         except:
             pub = False
         # Check private key
         try:
             RSA.load_key_string(pk['key'].encode('ascii'))
             key = True
         except:
             key = False
         if key or pub:
             confirm_ids.append(pk['id'])
         else:
             raise osv.except_osv(_('Invalid action !'),
                                  _('Cannot confirm invalid pairkeys. You need provide private and public keys in PEM format.'))
     return True
예제 #3
0
 def action_validate(self, cr, uid, ids, context=None):
     if context is None:
         context = {}
     pairkeys = self.read(cr, uid, ids, ['key', 'pub'], context=context)
     confirm_ids = []
     for pk in pairkeys:
         # Check public key
         try:
             PUB = BIO.MemoryBuffer(pk['pub'].encode('ascii'))
             RSA.load_pub_key_bio(PUB)
             pub = True
         except:
             pub = False
         # Check private key
         try:
             RSA.load_key_string(pk['key'].encode('ascii'))
             key = True
         except:
             key = False
         if key or pub:
             confirm_ids.append(pk['id'])
         else:
             raise osv.except_osv(
                 _('Invalid action !'),
                 _('Cannot confirm invalid pairkeys. You need provide private and public keys in PEM format.'
                   ))
     return True
예제 #4
0
def verify_and_decrypt(pmsg,
                       emsg,
                       sig,
                       senderPubPem,
                       receiverPrivPem,
                       hash = 'sha256',
                       cipher = 'aes_256_cbc',
                       padding = 'pkcs1_oaep'):

   padding = PADDING[padding]

   pmsg = binascii.a2b_base64(pmsg)
   emsg = binascii.a2b_base64(emsg)
   sig = binascii.a2b_base64(sig)

   key_len = int(cipher.split("_")[1])
   md = EVP.MessageDigest(hash)
   md.update(pmsg)
   md.update(emsg)
   digest = md.digest()

   skey = RSA.load_pub_key_bio(BIO.MemoryBuffer(senderPubPem))
   if not skey.verify(digest, sig, hash):
      raise Exception("could not verify signature")

   rkey = RSA.load_key_bio(BIO.MemoryBuffer(receiverPrivPem))

   kv = rkey.private_decrypt(emsg, padding)
   key = kv[0:key_len/8]
   iv = kv[key_len/8:]

   c = EVP.Cipher(alg = cipher, key = key, iv = iv, op = m2.decrypt)
   msg = cipher_filter(c, pmsg)

   return msg
예제 #5
0
def encrypt_and_sign(msg,
                     senderPrivPem,
                     receiverPubPem,
                     hash = 'sha256',
                     cipher = 'aes_256_cbc',
                     padding = 'pkcs1_oaep'):

   padding = PADDING[padding]

   key_len = int(cipher.split("_")[1])
   key = os.urandom(key_len/8)
   iv = os.urandom(key_len/8)
   c = EVP.Cipher(alg = cipher, key = key, iv = iv, op = m2.encrypt)
   pmsg = cipher_filter(c, msg)

   rkey = RSA.load_pub_key_bio(BIO.MemoryBuffer(receiverPubPem))
   emsg = rkey.public_encrypt(key + iv, padding)

   md = EVP.MessageDigest(hash)
   md.update(pmsg)
   md.update(emsg)
   digest = md.digest()

   skey = RSA.load_key_bio(BIO.MemoryBuffer(senderPrivPem))
   sig = skey.sign(digest, hash)

   return (binascii.b2a_base64(pmsg).strip(),
           binascii.b2a_base64(emsg).strip(),
           binascii.b2a_base64(sig).strip())
예제 #6
0
파일: jwt.py 프로젝트: nickeddy/atmosphere
def verify(jwt, *keys):
    try:
        signing_input, crypto_segment = str(jwt).rsplit('.', 1)
        header_segment, payload_segment = signing_input.split('.', 1)
    except ValueError:
        raise DecodeError("Not enough segments")
    try:
        header = json.loads(base64url_decode(header_segment))
        payload = json.loads(base64url_decode(payload_segment))
        signature = base64url_decode(crypto_segment)
    except (ValueError, TypeError):
        raise DecodeError("Invalid segment encoding")

    try:
        for key in keys:
            if isinstance(key, unicode):
                key = key.encode('utf-8')
            try:
                bio = BIO.MemoryBuffer(key)
                k = RSA.load_pub_key_bio(bio)
                k.verify(signing_input, signature, header['alg'])
                break  # Successful verification. Do not run 'else' block.
            except Exception as e:
                pass
        else:
            raise DecodeError("Signature verification failed")
    except KeyError:
        raise DecodeError("Algorithm not supported")
예제 #7
0
파일: crypto.py 프로젝트: MiniSEC/GRR_clone
  def Verify(self, pub_key):
    """Verify the data in this blob.

    Args:
      pub_key: The public key to use for verification.

    Returns:
      True when verification succeeds.

    Raises:
      rdfvalue.DecodeError if the data is not suitable verified.
    """
    if self.digest_type != self.HashType.SHA256:
      raise rdfvalue.DecodeError("Unsupported digest.")

    bio = BIO.MemoryBuffer(pub_key)
    rsa = RSA.load_pub_key_bio(bio)
    result = 0
    try:
      result = rsa.verify(self.digest, self.signature,
                          DIGEST_ALGORITHM_STR)
      if result != 1:
        raise rdfvalue.DecodeError("Could not verify blob.")

    except RSA.RSAError, e:
      raise rdfvalue.DecodeError("Could not verify blob. Error: %s" % e)
예제 #8
0
 def init_rsa_M2C(self):
     from M2Crypto import RSA, BIO
     self.rsa = RSA.load_pub_key_bio(BIO.MemoryBuffer(self.rsa_key))
     self.rsa_decode = lambda d: self.rsa.public_decrypt(
         d, RSA.pkcs1_padding)
     self.rsa_encode = lambda d: self.rsa.public_encrypt(
         d, RSA.pkcs1_padding)
예제 #9
0
파일: models.py 프로젝트: bitlair/hackdns
 def encrypt(self, other, message):
     '''
     Encrypt message to other server. The message must be a byte string.
     '''
     bio = BIO.MemoryBuffer(bytes(other.key_public))
     rsa = RSA.load_pub_key_bio(his_bio)
     return his_rsa.public_encrypt(message, RSA.pkcs1_padding)
예제 #10
0
 def _derive_pubkey(self):
     # derive EC public key instance from self._key
     if self._key == None:
         return False
     membuff = BIO.MemoryBuffer()
     self._key.save_pub_key_bio(membuff)  #(filename)
     self._pubkey = RSA.load_pub_key_bio(membuff)   #(filename)
예제 #11
0
    def set_public_key_string(self, public_key_string):

        # convert from unicode, as this can throw off the key parsing
        public_key_string = str(public_key_string)

        # remove the PEM header/footer
        public_key_string = remove_pem_headers(public_key_string)

        if self._using_m2crypto:
            header_string = "PUBLIC KEY"
            # add the PKCS#8 header if it doesn't exist
            if not public_key_string.startswith(PKCS8_HEADER):
                public_key_string = PKCS8_HEADER + public_key_string
            # break up the base64 key string into lines of max length 64, to please m2crypto
            public_key_string = public_key_string.replace("\n", "")
            public_key_string = "\n".join(
                re.findall(".{1,64}", public_key_string))
        else:
            header_string = "RSA PUBLIC KEY"
            # remove PKCS#8 header if it exists
            if public_key_string.startswith(PKCS8_HEADER):
                public_key_string = public_key_string[len(PKCS8_HEADER):]

        # add the appropriate PEM header/footer
        public_key_string = add_pem_headers(public_key_string, header_string)

        if self._using_m2crypto:
            self._public_key = M2RSA.load_pub_key_bio(
                M2BIO.MemoryBuffer(public_key_string))
        else:
            self._public_key = PYRSA.PublicKey.load_pkcs1(public_key_string)
예제 #12
0
파일: models.py 프로젝트: bitlair/hackdns
 def verify(self, signer, data, signature, algorithm='sha1'):
     '''
     Verify an RSA signature.
     '''
     bio = BIO.MemoryBuffer(bytes(signer.key_public))
     rsa = RSA.load_pub_key_bio(bio)
     return rsa.verify(data, signature, algo=algorithm)
예제 #13
0
def validate_rsa_pubkey(value):
    """ Validate X.501 and PKCS#1 RSA public keys """
    value = value.encode('ascii')
    try:
        # ckeck X.501 formatted key
        bio = BIO.MemoryBuffer(value)
        RSA.load_pub_key_bio(bio)
    except:
        try:
            # Check PKCS#1 formatted key (tinc favourite format)
            pk = pkcs_to_x501(value)
            bio = BIO.MemoryBuffer(pk)
            RSA.load_pub_key_bio(bio)
        except:
            msg = 'This is not a valid RSA (X.501 or PKCS#1) public key.'
            raise ValidationError(msg)
예제 #14
0
def process_cookie(original_message):
    unquoted_message = urllib.unquote(original_message)
    payload = unquoted_message[:unquoted_message.rfind('#')]
    base64_signature = unquoted_message[unquoted_message.rfind('#') + 1:]

    signature = base64.decodestring(base64_signature)

    try:
        pem = open(PEM_FILE_PATH or '').read()
    except:
        raise Exception("Could not open PEM file")

    bio = BIO.MemoryBuffer(pem)
    rsa = RSA.load_pub_key_bio(bio)
    pubkey = EVP.PKey()
    pubkey.assign_rsa(rsa)
    pubkey.reset_context(md='sha1')
    pubkey.verify_init()
    pubkey.verify_update(payload)
    return_value = pubkey.verify_final(signature)
    if not return_value:
        raise Exception("UNED cookie not verified")

    user_id = ''
    email = ''

    for elem in payload.split('#'):
        if elem.startswith('ID:'):
            user_id = base64.decodestring(elem.split(':')[1])
        elif elem.startswith('EMAIL:'):
            email = base64.decodestring(elem.split(':')[1])

    return user_id, email
예제 #15
0
파일: crypto.py 프로젝트: 2flcastro/ka-lite
    def set_public_key_string(self, public_key_string):
        
        # convert from unicode, as this can throw off the key parsing
        public_key_string = str(public_key_string)
        
        # remove the PEM header/footer
        public_key_string = remove_pem_headers(public_key_string)
                
        if self._using_m2crypto:
            header_string = "PUBLIC KEY"
            # add the PKCS#8 header if it doesn't exist
            if not public_key_string.startswith(PKCS8_HEADER):
                public_key_string = PKCS8_HEADER + public_key_string
            # break up the base64 key string into lines of max length 64, to please m2crypto
            public_key_string = public_key_string.replace("\n", "")
            public_key_string = "\n".join(re.findall(".{1,64}", public_key_string))
        else:
            header_string = "RSA PUBLIC KEY"
            # remove PKCS#8 header if it exists
            if public_key_string.startswith(PKCS8_HEADER):
                public_key_string = public_key_string[len(PKCS8_HEADER):]

        # add the appropriate PEM header/footer
        public_key_string = add_pem_headers(public_key_string, header_string)
        
        if self._using_m2crypto:
            self._public_key = M2RSA.load_pub_key_bio(M2BIO.MemoryBuffer(public_key_string))
        else:
            self._public_key = PYRSA.PublicKey.load_pkcs1(public_key_string)
예제 #16
0
    def test_delegation_get_pubkey_csr(self):
        empty_db()
        response = self.app.put(url('delegation', delegation_id='test'),
                                params='{ "renewable": false }')
        delegation = Session.query(model.Delegation).first()

        response = self.app.get(url('delegation_pubkey', delegation_id='test'))
        pubkey1 = response.body

        response = self.app.get(url('delegation_pubkey', delegation_id='test'))
        pubkey2 = response.body

        response = self.app.get(url('delegation_pubkey', delegation_id='test'),
                                headers={'Accept': 'application/x-pkcs1'})
        pubkey3 = response.body

        key1 = RSA.load_pub_key_bio(BIO.MemoryBuffer(pubkey1))
        key3 = certlib.rsa_load_pub_key_der(pubkey3)

        assert key1.pub() == delegation.new_key.pub()
        assert pubkey1 == pubkey2
        assert key1.pub() == key3.pub()

        response = self.app.get(url('delegation_request', delegation_id='test'),
                                headers={'Accept': 'application/x-pkcs10+der'})
        req = X509.load_request_der_string(response.body)

        assert key1.pub() == req.get_pubkey().get_rsa().pub()
예제 #17
0
    def test_delegation_renew(self):
        empty_db()
        response = self.app.put(url('delegation', delegation_id='test'),
                                params='{ "renewable": false }')
        delegation = Session.query(model.Delegation).first()

        response = self.app.get(url('delegation_pubkey', delegation_id='test'))
        pub_key = RSA.load_pub_key_bio(BIO.MemoryBuffer(response.body))
        pkey = EVP.PKey()
        pkey.assign_rsa(pub_key)

        key, chain = certlib.load_proxy(test_user_proxy)
        proxy = proxylib.generate_proxycert(pkey, chain[0], key)

        new_chain = X509.X509_Stack()
        new_chain.push(proxy)
        for cert in chain:
            new_chain.push(cert)

        response = self.app.put(url('delegation_renew', delegation_id='test'),
                                params=new_chain.as_der(),
                                headers={'Content-Type': 'application/x-pkix-chain+der'})
        assert response.status_int == 204

        try:
            response = self.app.put(url('delegation_renew', delegation_id='test'),
                                    params=new_chain.as_der(),
                                    headers={'Content-Type': 'application/x-pkix-chain+der'})
            raise "Should raise AppError"
        except webtest.AppError, exc:
            assert 'No pending renew key pair found' in exc.args[0]
예제 #18
0
def validate_rsa_pubkey(value):
    """ Validate X.501 and PKCS#1 RSA public keys """
    value = value.encode('ascii')
    try:
        # ckeck X.501 formatted key
        bio = BIO.MemoryBuffer(value)
        RSA.load_pub_key_bio(bio)
    except:
        try:
            # Check PKCS#1 formatted key (tinc favourite format)
            pk = pkcs_to_x501(value)
            bio = BIO.MemoryBuffer(pk)
            RSA.load_pub_key_bio(bio)
        except:
            msg = 'This is not a valid RSA (X.501 or PKCS#1) public key.'
            raise ValidationError(msg)
예제 #19
0
def verify_certs_signature(service_id, xml_text, notary_pub_key_text):
	doc = parseString(xml_text)
	root = doc.documentElement
	sig_to_verify = base64.standard_b64decode(root.getAttribute("sig"))
	
	to_verify = service_id
	cert_elements = root.getElementsByTagName("certificate")
	
	for cert_elem in cert_elements:
		cert = base64.standard_b64decode(cert_elem.getAttribute("body"))
		to_verify += cert
		
		start_ts = int(cert_elem.getAttribute("start"))
		end_ts = int(cert_elem.getAttribute("end"))
		to_verify += struct.pack("!2I", start_ts, end_ts)
		
	
	bio = BIO.MemoryBuffer(notary_pub_key_text)
	rsa_pub = RSA.load_pub_key_bio(bio)
	pubkey = EVP.PKey()
	pubkey.assign_rsa(rsa_pub)

	pubkey.reset_context(md='sha256')
	pubkey.verify_init()
	pubkey.verify_update(to_verify)
	return pubkey.verify_final(sig_to_verify)
예제 #20
0
    def do_POST(self):
        #get public key
        pub_key_url = ''
        try:
            pub_key_url_base64 = self.headers['x-oss-pub-key-url']
            pub_key_url = pub_key_url_base64.decode('base64')
            url_reader = urllib2.urlopen(pub_key_url)
            pub_key = url_reader.read()
        except:
            print 'pub_key_url : ' + pub_key_url
            print 'Get pub key failed!'
            self.send_response(400)
            self.end_headers()
            return

        #get authorization
        authorization_base64 = self.headers['authorization']
        authorization = authorization_base64.decode('base64')

        #get callback body
        content_length = self.headers['content-length']
        callback_body = self.rfile.read(int(content_length))

        #compose authorization string
        auth_str = ''
        pos = self.path.find('?')
        if -1 == pos:
            auth_str = self.path + '\n' + callback_body
        else:
            auth_str = urllib2.unquote(
                self.path[0:pos]) + self.path[pos:] + '\n' + callback_body
        print auth_str

        #verify authorization
        auth_md5 = md5.new(auth_str).digest()
        bio = BIO.MemoryBuffer(pub_key)
        rsa_pub = RSA.load_pub_key_bio(bio)
        try:
            result = rsa_pub.verify(auth_md5, authorization, 'md5')
        except e:
            result = False

        if not result:
            print 'Authorization verify failed!'
            print 'Public key : %s' % (pub_key)
            print 'Auth string : %s' % (auth_str)
            self.send_response(400)
            self.end_headers()
            return

        #do something accoding to callback_body

        #response to OSS
        resp_body = '{"Status":"OK"}'
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Content-Length', str(len(resp_body)))
        self.end_headers()
        self.wfile.write(resp_body)
예제 #21
0
    def RSA_encryptor(self, plaintext, RSA_public_key):

        bio = BIO.MemoryBuffer(RSA_public_key.encode('ascii')) 
        rsa = RSA.load_pub_key_bio(bio)
         
        # encrypt
        encrypted = rsa.public_encrypt(plaintext, RSA.pkcs1_padding)
        return encrypted.encode('hex')
예제 #22
0
def rsa_encrypt_string(message):
    """Encrypt a string using an RSA public key"""
    pub_key = settings.RSA_PUBLIC_KEY
    from M2Crypto import RSA, BIO
    bio = BIO.MemoryBuffer(pub_key)
    rsa = RSA.load_pub_key_bio(bio)
    encrypted = rsa.public_encrypt(message, RSA.pkcs1_oaep_padding)
    return encrypted.encode('base64')
예제 #23
0
    def do_POST(self):
        #get public key
        pub_key_url = ''
        try:
            pub_key_url_base64 = self.headers['x-oss-pub-key-url']
            pub_key_url = pub_key_url_base64.decode('base64')
            url_reader = urllib2.urlopen(pub_key_url)
            pub_key = url_reader.read()
        except:
            print 'pub_key_url : ' + pub_key_url
            print 'Get pub key failed!'
            self.send_response(400)
            self.end_headers()
            return

        #get authorization
        authorization_base64 = self.headers['authorization']
        authorization = authorization_base64.decode('base64')

        #get callback body
        content_length = self.headers['content-length']
        callback_body = self.rfile.read(int(content_length))

        #compose authorization string
        auth_str = ''
        pos = self.path.find('?')
        if -1 == pos:
            auth_str = self.path + '\n' + callback_body
        else:
            auth_str = urllib2.unquote(self.path[0:pos]) + self.path[pos:] + '\n' + callback_body
        print auth_str

        #verify authorization
        auth_md5 = md5.new(auth_str).digest()
        bio = BIO.MemoryBuffer(pub_key)
        rsa_pub = RSA.load_pub_key_bio(bio)
        try:
            result = rsa_pub.verify(auth_md5, authorization, 'md5')
        except e:
            result = False

        if not result:
            print 'Authorization verify failed!'
            print 'Public key : %s' % (pub_key)
            print 'Auth string : %s' % (auth_str)
            self.send_response(400)
            self.end_headers()
            return

        #do something accoding to callback_body

        #response to OSS
        resp_body = '{"Status":"OK"}'
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Content-Length', str(len(resp_body)))
        self.end_headers()
        self.wfile.write(resp_body)
예제 #24
0
def DencryptForRegCode(regCode,public_key):
    pub_bio = BIO.MemoryBuffer(public_key)
    rsa = RSA.load_pub_key_bio(pub_bio)
    #pub_key = EVP.load_key_string(public)
    try:
        machine_code = rsa.public_decrypt(b64decode(regCode),RSA.pkcs1_padding)
    except:
        machine_code = ""
    return machine_code
예제 #25
0
 def pubkey(self):
     """fetch pulp's public key"""
     if self._pubkey:
         return self._pubkey
     with self.asserting(True):
         response = self.send(StaticRequest("GET", "rsa_pub.key"))
     assert response.content, "got empty content: %s" % format_response(response)
     self._pubkey = RSA.load_pub_key_bio(BIO.MemoryBuffer(response.content))
     return self._pubkey
예제 #26
0
def RSA_pub_key_from_der(der):
    from M2Crypto import RSA, BIO
    s = '-----BEGIN PUBLIC KEY-----\n'
    b = base64.standard_b64encode(der)
    s += textwrap.fill(b, 64)
    s += '\n'
    s += '-----END PUBLIC KEY-----\n'
    bio = BIO.MemoryBuffer(s)
    return RSA.load_pub_key_bio(bio)
예제 #27
0
def encrypt(mess, pub_key):
    """
    Encrypt the message mess by public key pub_key
    """
    mem = BIO.MemoryBuffer(pub_key)
    key = RSA.load_pub_key_bio(mem)
    cipher = key.public_encrypt(mess, RSA.pkcs1_oaep_padding)

    return cipher.encode('base64')
def RSA_pub_key_from_der(der):
    from M2Crypto import RSA, BIO
    s = '-----BEGIN PUBLIC KEY-----\n'
    b = base64.standard_b64encode(der)
    s += textwrap.fill(b, 64)
    s += '\n'
    s += '-----END PUBLIC KEY-----\n'
    bio = BIO.MemoryBuffer(s)
    return RSA.load_pub_key_bio(bio)
예제 #29
0
def encrypt(mess,pub_key):
    """
    Encrypt the message mess by public key pub_key
    """
    mem = BIO.MemoryBuffer(pub_key)
    key = RSA.load_pub_key_bio(mem)
    cipher = key.public_encrypt(mess,RSA.pkcs1_oaep_padding)

    return cipher.encode('base64')
예제 #30
0
파일: crypto.py 프로젝트: 0xdabbad00/grr
  def GetPublicKey(self):
    try:
      bio = BIO.MemoryBuffer(self._value)
      rsa = RSA.load_pub_key_bio(bio)
      if rsa.check_key() != 1:
        raise CipherError("RSA.check_key() did not succeed.")

      return rsa
    except RSA.RSAError as e:
      raise type_info.TypeValueError("Public key invalid: %s" % e)
예제 #31
0
    def GetPublicKey(self):
        try:
            bio = BIO.MemoryBuffer(self._value)
            rsa = RSA.load_pub_key_bio(bio)
            if rsa.check_key() != 1:
                raise RSA.RSAError("RSA.check_key() did not succeed.")

            return rsa
        except RSA.RSAError as e:
            raise type_info.TypeValueError("Public key invalid: %s" % e)
예제 #32
0
 def pubkey(self):
     '''fetch pulp's public key'''
     if self._pubkey:
         return self._pubkey
     with self.asserting(True):
         response = self.send(StaticRequest('GET', 'rsa_pub.key'))
     assert response.content, "got empty content: %s" % format_response(
         response)
     self._pubkey = RSA.load_pub_key_bio(BIO.MemoryBuffer(response.content))
     return self._pubkey
예제 #33
0
파일: crypto.py 프로젝트: ewalbridge/mystic
    def __init__(self, data, password, public_key):
        bio = BIO.MemoryBuffer(str(public_key).encode('utf8')) # read public key into memory
        rsa = RSA.load_pub_key_bio(bio) # load public key
        
        pwd = password
        enc = rsa.public_encrypt(pwd, RSA.pkcs1_oaep_padding) # encrypt password
        self.__encrypted_password = b64encode(enc) #enc.encode('base64') # encode password

        crypto_service = aes_encryption_service()
        cipher = b64encode(crypto_service.aes_encrypt(password, data))
        self.__data = cipher
예제 #34
0
	def _import_keys(self):
		public_bio = BIO.MemoryBuffer(self.public_key) if self.public_key \
			else None
		self.rsa_public = M2C_RSA.load_pub_key_bio(public_bio) \
			if public_bio else M2C_RSA.load_pub_key(self.public_key_filename)

		private_bio = BIO.MemoryBuffer(self.private_key) if self.private_key \
			else None
		self.rsa_private = M2C_RSA.load_key_bio(private_bio) \
			if private_bio else M2C_RSA.load_key(self.private_key_filename,
				callback=self.dpc)
예제 #35
0
파일: crypto.py 프로젝트: dsuch/zato
 def load_keys(self):
     if self.priv_key_location:
         self.priv_key = RSA.load_key(self.priv_key_location)
     elif self.priv_key:
         bio = self._get_bio(self.priv_key)
         self.priv_key = RSA.load_key_bio(bio)
         
     if self.pub_key_location:
         self.pub_key = RSA.load_pub_key(self.pub_key_location)
     elif self.pub_key:
         bio = self._get_bio(self.pub_key)
         self.pub_key = RSA.load_pub_key_bio(bio)
예제 #36
0
파일: referer.py 프로젝트: XinMa1/work
 def __rsa_verify(self, string, sign, public_key_path):
     #print("string is %s, sign is %s, key: %s\n" % (string, sign, public_key_path))
     bio = BIO.MemoryBuffer(open(public_key_path).read())
     rsa = RSA.load_pub_key_bio(bio)
     pubkey = EVP.PKey()
     pubkey.assign_rsa(rsa)
     pubkey.reset_context(md='sha1')
     pubkey.verify_init()
     pubkey.verify_update(str(string))
     ret=pubkey.verify_final(base64.b64decode(str(sign)))
     #return True if pubkey.verify_final(base64.b64decode(sign)) == 1 else False
     return True if ret == 1 else False
예제 #37
0
파일: auth.py 프로젝트: CUXIDUMDUM/pulp
 def get_key(consumer_id):
     """
     Get the consumer's public RSA key.
     :return: The consumer's public RSA key.
     :rtype: RSA.RSA
     """
     rsa_pub = 'rsa_pub'
     manager = managers.consumer_manager()
     consumer = manager.get_consumer(consumer_id, fields=[rsa_pub])
     pem = consumer[rsa_pub]
     bfr = BIO.MemoryBuffer(str(pem))
     return RSA.load_pub_key_bio(bfr)
예제 #38
0
    def load_keys(self):
        if self.priv_key_location:
            self.priv_key = RSA.load_key(self.priv_key_location)
        elif self.priv_key:
            bio = self._get_bio(self.priv_key)
            self.priv_key = RSA.load_key_bio(bio)

        if self.pub_key_location:
            self.pub_key = RSA.load_pub_key(self.pub_key_location)
        elif self.pub_key:
            bio = self._get_bio(self.pub_key)
            self.pub_key = RSA.load_pub_key_bio(bio)
예제 #39
0
파일: auth.py 프로젝트: omps/pulp
 def get_key(consumer_id):
     """
     Get the consumer's public RSA key.
     :return: The consumer's public RSA key.
     :rtype: RSA.RSA
     """
     rsa_pub = 'rsa_pub'
     manager = managers.consumer_manager()
     consumer = manager.get_consumer(consumer_id, fields=[rsa_pub])
     pem = consumer[rsa_pub]
     bfr = BIO.MemoryBuffer(str(pem))
     return RSA.load_pub_key_bio(bfr)
예제 #40
0
def read_key(file_path, type):
    """
    读取RSA密钥
    :param file_path: 文件路径
    :param type: 密钥类型,private:私钥|public:公钥
    :return:
    """
    with open(file_path, "rb") as file_handler:
        rea_key = BIO.MemoryBuffer(file_handler.read())
    if type == "private":
        return RSA.load_key_bio(rea_key)
    else:
        return RSA.load_pub_key_bio(rea_key)
예제 #41
0
def encrypt_RSA(key, message):
    '''
    param: public_key_loc Path to public key
    param: message String to be encrypted
    return base64 encoded encrypted string
    '''
    from M2Crypto import RSA, BIO 
    #key = open(public_key_loc, "r").read() 
    pubkey = str(key).encode('utf8') 
    bio = BIO.MemoryBuffer(pubkey) 
    rsa = RSA.load_pub_key_bio(bio) 
    encrypted = rsa.public_encrypt(message, RSA.pkcs1_oaep_padding)
    return encrypted.encode('base64')
예제 #42
0
파일: test_auth.py 프로젝트: ipanova/pulp
    def test_not_validated(self, mock_get):
        message = 'hello'
        consumer_id = 'test-consumer_id'
        document = Mock()
        document.any = {'consumer_id': consumer_id}
        key = RSA.load_key_bio(BIO.MemoryBuffer(OTHER_KEY))

        mock_get.return_value = RSA.load_pub_key_bio(BIO.MemoryBuffer(RSA_PUB))

        authenticator = Authenticator()
        self.assertRaises(ValidationFailed, authenticator.validate, document,
                          message, key.sign(message))
        mock_get.assert_called_with(consumer_id)
예제 #43
0
def encrypt_RSA(key, message):
    '''
    param: public_key_loc Path to public key
    param: message String to be encrypted
    return base64 encoded encrypted string
    '''
    from M2Crypto import RSA, BIO
    #key = open(public_key_loc, "r").read()
    pubkey = str(key).encode('utf8')
    bio = BIO.MemoryBuffer(pubkey)
    rsa = RSA.load_pub_key_bio(bio)
    encrypted = rsa.public_encrypt(message, RSA.pkcs1_oaep_padding)
    return encrypted.encode('base64')
예제 #44
0
 def action_validate(self):
     confirm_ids = []
     for pk in self:
         # Check public key
         try:
             PUB = BIO.MemoryBuffer(pk.pub.encode('ascii'))
             RSA.load_pub_key_bio(PUB)
             pub = True
         except:
             pub = False
         # Check private key
         try:
             RSA.load_key_string(pk.key.encode('ascii'))
             key = True
         except:
             key = False
         if key or pub:
             confirm_ids.append(pk.id)
         else:
             raise Warning(_(
                 'Invalid action! Cannot confirm invalid pairkeys. You need provide private and public keys in PEM format.'))
     return True
예제 #45
0
파일: test_auth.py 프로젝트: ipanova/pulp
    def test_not_validated(self, mock_get):
        message = 'hello'
        consumer_id = 'test-consumer_id'
        document = Mock()
        document.any = {'consumer_id': consumer_id}
        key = RSA.load_key_bio(BIO.MemoryBuffer(OTHER_KEY))

        mock_get.return_value = RSA.load_pub_key_bio(BIO.MemoryBuffer(RSA_PUB))

        authenticator = Authenticator()
        self.assertRaises(
            ValidationFailed, authenticator.validate, document, message, key.sign(message))
        mock_get.assert_called_with(consumer_id)
예제 #46
0
파일: utils.py 프로젝트: zengman/pathend
def verify(s, signature, pub):
    try:
        bio = BIO.MemoryBuffer(pub)
        rsa = RSA.load_pub_key_bio(bio)
        pubkey = EVP.PKey()
        pubkey.assign_rsa(rsa)

        # if you need a different digest than the default 'sha1':
        pubkey.reset_context(md='sha256')
        pubkey.verify_init()
        pubkey.verify_update(s)
        return (pubkey.verify_final(signature) == 1)
    except:
        return False
예제 #47
0
    def _set_public_key_string(self, public_key_string):

        # add the PKCS#8 header if it doesn't exist
        if not public_key_string.startswith(PKCS8_HEADER):
            public_key_string = PKCS8_HEADER + public_key_string

        # break up the base64 key string into lines of max length 64, to please m2crypto
        public_key_string = public_key_string.replace("\n", "")
        public_key_string = "\n".join(re.findall(".{1,64}", public_key_string))

        # add the appropriate PEM header/footer
        public_key_string = self._add_pem_headers(public_key_string, "PUBLIC KEY")

        self._public_key = M2RSA.load_pub_key_bio(M2BIO.MemoryBuffer(self.ensure_bytes(public_key_string)))
예제 #48
0
def verify_signature(self, pubkey, str_to_verify, signature):
    """
   Verify that signature matches str_to_verify
   """

    k = RSA.load_pub_key_bio(BIO.MemoryBuffer(pubkey))
    ver = EVP.PKey()
    ver.assign_rsa(k)
    ver.verify_init()
    ver.verify_update(str_to_verify)

    if ver.verify_final(signature) == False:
        print 'Error: message is not as expected, may be adversary'
        return False
    else:
        return True
예제 #49
0
    def set_pubkey(self, public_key_fname):
        """
        Set the public key
        """

        if public_key_fname:
            # TODO: try block around file ops
            key_str = open(public_key_fname).read()
            bio = BIO.MemoryBuffer(key_str)
            key = RSA.load_pub_key_bio(bio)
        else:
            key_str = None
            key = None

        self._pub = key
        self._pub_str = key_str
예제 #50
0
파일: config.py 프로젝트: shahabzd/docker
def _init():
    flavor = os.environ.get('SETTINGS_FLAVOR', 'dev')
    config_path = os.environ.get('DOCKER_REGISTRY_CONFIG', 'config.yml')

    if not os.path.isabs(config_path):
        config_path = os.path.join(os.path.dirname(__file__), '../../',
                                   'config', config_path)
    try:
        f = open(config_path)
    except Exception:
        raise exceptions.FileNotFoundError(
            'Heads-up! File is missing: %s' % config_path)

    conf = Config(f.read())
    if flavor:
        if flavor not in conf:
            raise exceptions.ConfigError(
                'The specified flavor (%s) is missing in your config file (%s)'
                % (flavor, config_path))
        conf = conf[flavor]
        conf.flavor = flavor

    if conf.privileged_key:
        try:
            f = open(conf.privileged_key)
        except Exception:
            raise exceptions.FileNotFoundError(
                'Heads-up! File is missing: %s' % conf.privileged_key)

        try:
            pk = f.read().split('\n')
            pk = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A' + ''.join(pk[1:-2])
            pk = [pk[i: i + 64] for i in range(0, len(pk), 64)]
            pk = ('-----BEGIN PUBLIC KEY-----\n' + '\n'.join(pk) +
                  '\n-----END PUBLIC KEY-----')
            bio = BIO.MemoryBuffer(pk)
            conf.privileged_key = RSA.load_pub_key_bio(bio)
        except Exception:
            raise exceptions.ConfigError(
                'Key at %s is not a valid RSA key' % conf.privileged_key)
        f.close()

    if conf.index_endpoint:
        conf.index_endpoint = conf.index_endpoint.strip('/')

    return conf
예제 #51
0
def rsaEncrypt(public_key: "公钥", message: "要加密的信息", showAllInfo=True):
    """RSA 加密"""
    bio = BIO.MemoryBuffer(public_key)
    rsa_pub = RSA.load_pub_key_bio(bio)
    buffer = None
    while message:
        input = message[:245]
        if showAllInfo:
            tlog("正在加密分段 ...")
            tlog(input)
        snidata = rsa_pub.public_encrypt(input, RSA.pkcs1_padding)
        if buffer == None:
            buffer = snidata
        else:
            buffer = buffer + snidata
        message = message[245:]
    ctxt64_pri = base64.b64encode(buffer)
    return ctxt64_pri
예제 #52
0
    def GetRSAPublicKey(self, common_name="Server"):
        """Retrieve the relevant public key for that common name.

    This maintains a cache of public keys or loads them from external
    sources if available.

    Args:
      common_name: The common_name of the key we need.

    Returns:
      A valid public key.
    """
        try:
            pub_key = self.pub_key_cache.Get(common_name)
            bio = BIO.MemoryBuffer(pub_key)
            return RSA.load_pub_key_bio(bio)
        except (KeyError, X509.X509Error):
            raise KeyError("No certificate found")
예제 #53
0
def create_certificate(issuerPrivKey,
                       issuerInfo,
                       subjectPubKey,
                       subjectInfo,
                       validForDays,
                       serial,
                       version = 0,
                       hash = 'sha1'):
   """
   Create a certificate and return certificate (PEM, text, fingerprint).
   """

   ikey = RSA.load_key_bio(BIO.MemoryBuffer(issuerPrivKey))
   if ikey.check_key() != 1:
      raise Exception("invalid issuer RSA key")
   p_ikey = EVP.PKey(md = hash)
   p_ikey.assign_rsa(ikey)

   skey = RSA.load_pub_key_bio(BIO.MemoryBuffer(subjectPubKey))
   if skey.check_key() != 1:
      raise Exception("invalid subject RSA key")
   p_skey = EVP.PKey(md = hash)
   p_skey.assign_rsa(skey)

   cert = X509.X509()
   cert.set_pubkey(p_skey)

   issuer = x509name_from_info(issuerInfo)
   cert.set_issuer(issuer)

   subject = x509name_from_info(subjectInfo)
   cert.set_subject(subject)

   notBefore = m2.x509_get_not_before(cert.x509)
   notAfter = m2.x509_get_not_after(cert.x509)
   m2.x509_gmtime_adj(notBefore, 0)
   m2.x509_gmtime_adj(notAfter, 60 * 60 * 24 * validForDays)

   cert.set_serial_number(serial)
   cert.set_version(version)

   cert.sign(p_ikey, hash)
   return (cert.as_pem(), cert.as_text(), cert_fingerprint(cert))
예제 #54
0
def rsa_verify(xml, signature, key, c14n_exc=True):
    "Verify a XML document signature usign RSA-SHA1, return True if valid"

    # load the public key (from buffer or filename)
    if key.startswith("-----BEGIN PUBLIC KEY-----"):
        bio = BIO.MemoryBuffer(key)
        rsa = RSA.load_pub_key_bio(bio)
    else:
        rsa = RSA.load_pub_key(certificate)
    # create the digital envelope
    pubkey = EVP.PKey()
    pubkey.assign_rsa(rsa)
    # do the cryptographic validation (using the default sha1 hash digest)
    pubkey.reset_context(md='sha1')
    pubkey.verify_init()
    # normalize and feed the signed xml to be verified
    pubkey.verify_update(canonicalize(xml, c14n_exc))
    ret = pubkey.verify_final(base64.b64decode(signature))
    return ret == 1
예제 #55
0
    def renew_delegation(self, delegation_id, key, chain):
        response = self.get("/delegations/%s/pubkey" % delegation_id,
                            headers={"accept": "application/x-pkcs1+pem"})
        if response.status != 200:
            raise PilotError("Failed to fetch delegation renew public key for delegation %s" % delegation_id)
        new_key = RSA.load_pub_key_bio(BIO.MemoryBuffer(response.body))
        new_pkey = EVP.PKey()
        new_pkey.assign_rsa(new_key)
        new_proxy = proxylib.generate_proxycert(new_pkey, chain[0], key, full=True)

        new_stack = X509.X509_Stack()
        new_stack.push(new_proxy)
        for cert in chain:
            new_stack.push(cert)
        response = self.put("/delegations/%s/renew" % delegation_id,
                            data=new_stack.as_der(),
                            headers={"content-type": "application/x-pkix-chain+der"})
        if response.status != 204:
            raise PilotError("Failed to update delegation %s: %s" % (delegation_id, response.body))