Esempio n. 1
0
def encrypt_sn(sn):
    m=Cipher(alg = "aes_128_cbc", key = config['passout'], iv = '\x00' * 16, op = 1)
    m.set_padding(padding=7)
    v = m.update(sn)
    v = v + m.final()
    del m
    return v
Esempio n. 2
0
def decrypt(chunk, key):
    cipher = Cipher(alg=ALG, key=key, iv=IV, op=0, key_as_bytes=0, padding=PADDING) # 0 is decrypt
    cipher.set_padding(padding=m2.no_padding)
    v = cipher.update(chunk)
    v = v + cipher.final()
    del cipher #需要删除
    return v 
Esempio n. 3
0
def encrypt_sn(sn):
    m = Cipher(alg="aes_128_cbc", key=config['passout'], iv='\x00' * 16, op=1)
    m.set_padding(padding=7)
    v = m.update(sn)
    v = v + m.final()
    del m
    return v
Esempio n. 4
0
def decryptPasswd(buf, passKey, iv = '\x00' * 16):
    cipher = Cipher(alg='aes_128_cbc', key=passKey, iv=iv, op=0) # 0 is decrypt  
    cipher.set_padding(padding=7)
    v = cipher.update(buf)
    v = v + cipher.final()
    del cipher
    return v
Esempio n. 5
0
def decryptPasswd(buf, passKey, iv='\x00' * 16):
    cipher = Cipher(alg='aes_128_cbc', key=passKey, iv=iv,
                    op=0)  # 0 is decrypt
    cipher.set_padding(padding=7)
    v = cipher.update(buf)
    v = v + cipher.final()
    del cipher
    return v
Esempio n. 6
0
def simple_decrypto(s):
    ''' des_cbc对称解密 '''
    buf = base64.decodestring(s.decode('utf8'))
    cipher = Cipher(alg='des_cbc', key=CRYPTO_KEY, iv=CRYPTO_IV, op=0)
    cipher.set_padding(padding=m2.no_padding)
    out = cipher.update(buf)
    out += cipher.final()
    del cipher
    return out
Esempio n. 7
0
def simple_encrypto(s):
    ''' 加密字符串 '''
    s = s.encode('utf8')
    cipher = Cipher(alg='des_cbc', key=CRYPTO_KEY, iv=CRYPTO_IV, op=1)
    cipher.set_padding(padding=m2.no_padding)
    out = cipher.update(s)
    out += cipher.final()
    del cipher
    return base64.encodestring(out)
Esempio n. 8
0
def encrypt(chunk, key):
    cipher = Cipher(alg=ALG, key=key, iv=IV, op=1, key_as_bytes=0,padding=PADDING) # 1 is encrypt
    # padding 有时设置为1
    cipher.set_padding(padding=m2.no_padding)
    v = cipher.update(chunk)
    v = v + cipher.final()
    del cipher #需要删除
    
    return v                  
Esempio n. 9
0
def encrypto(s):
    ''' 压缩加密字符串 '''
    if isinstance(s, unicode):
        s = s.encode('utf8')
    s = zlib.compress(s)
    cipher = Cipher(alg='des_cbc', key=CRYPTO_KEY, iv=CRYPTO_IV, op=1)
    cipher.set_padding(padding=m2.no_padding)
    out = cipher.update(s)
    out += cipher.final()
    del cipher
    return base64.encodestring(out)
Esempio n. 10
0
class M2CryptoEngine:
    K_CIPHER = None

    @classmethod
    def init_key_cipher(cls, prikey):
        cls.K_CIPHER = RSA.load_key_string(prikey)

    def __init__(self, encrypted_header=None):
        if encrypted_header:
            self.__enc_data = encrypted_header

            header = self.K_CIPHER.private_decrypt(encrypted_header,
                                                   RSA.pkcs1_padding)
            secret = header[:32]
            iv = header[32:]
            op = DEC
        else:
            secret = self._get_random(32)
            iv = self._get_random(16)
            self.__enc_data = self.K_CIPHER.public_encrypt(
                secret + iv, RSA.pkcs1_padding)
            op = ENC

        self.__cipher = Cipher(alg='aes_128_cbc', key=secret, iv=iv, op=op)
        self.__cipher.set_padding(1)

    def _get_random(self, cnt):
        while True:
            data = Rand.rand_bytes(cnt)
            if data[0] != '\x00':
                return data

    def encrypt(self, data, finalize=False):
        end_data = self.__cipher.update(data)
        if finalize:
            end_data += self.__cipher.final()
        return end_data

    def decrypt(self, data, finalize=False):
        end_data = self.__cipher.update(data)
        if finalize:
            end_data += self.__cipher.final()
        return end_data

    def get_encrypted_header(self):
        return self.__enc_data
Esempio n. 11
0
class M2CryptoEngine:
    K_CIPHER = None

    @classmethod
    def init_key_cipher(cls, prikey):
        cls.K_CIPHER = RSA.load_key_string(prikey)

    def __init__(self, encrypted_header=None):
        if encrypted_header:
            self.__enc_data = encrypted_header

            header = self.K_CIPHER.private_decrypt(encrypted_header, RSA.pkcs1_padding)
            secret = header[:32]
            iv = header[32:]
            op = DEC
        else:
            secret = self._get_random(32)
            iv = self._get_random(16)
            self.__enc_data = self.K_CIPHER.public_encrypt(secret+iv, RSA.pkcs1_padding)
            op = ENC

        self.__cipher = Cipher(alg='aes_128_cbc', key=secret, iv=iv, op=op)
        self.__cipher.set_padding(1)

    def _get_random(self, cnt):
        while True:
            data = Rand.rand_bytes(cnt)
            if data[0] != '\x00':
                return data

    def encrypt(self, data, finalize=False):
        end_data = self.__cipher.update(data)
        if finalize:
            end_data += self.__cipher.final()
        return end_data

    def decrypt(self, data, finalize=False):
        end_data = self.__cipher.update(data)
        if finalize:
            end_data += self.__cipher.final()
        return end_data

    def get_encrypted_header(self):
       return self.__enc_data 
Esempio n. 12
0
	def fetchPrivateKey(self):
		"""Fetch the private key for the user and storage context
		provided to this object, and decrypt the private key
		by using my passphrase.  Store the private key in internal
		storage for later use."""
	
		# Retrieve encrypted private key from the server
		logging.debug("Fetching encrypted private key from server")
		privKeyObj = self.ctx.get_item("keys", "privkey")
		payload = json.loads(privKeyObj['payload'])
		self.privKeySalt = base64.decodestring(payload['salt'])
		self.privKeyIV = base64.decodestring(payload['iv'])
		self.pubKeyURI = payload['publicKeyUri']

		data64 = payload['keyData']
		encryptedKey = base64.decodestring(data64)
		
		# Now decrypt it by generating a key with the passphrase
		# and performing an AES-256-CBC decrypt.
		logging.debug("Decrypting encrypted private key")
		
		passKey = PBKDF2(self.passphrase, self.privKeySalt, iterations=4096).read(32)
		cipher = Cipher(alg='aes_256_cbc', key=passKey, iv=self.privKeyIV, op=0) # 0 is DEC
		cipher.set_padding(padding=1)
		v = cipher.update(encryptedKey)
		v = v + cipher.final()
		del cipher
		decryptedKey = v

		# Result is an NSS-wrapped key.
		# We have to do some manual ASN.1 parsing here, which is unfortunate.
		
		# 1. Make sure offset 22 is an OCTET tag; if this is not right, the decrypt
		# has gone off the rails.
		if ord(decryptedKey[22]) != 4:
			logging.debug("Binary layout of decrypted private key is incorrect; probably the passphrase was incorrect.")
			raise ValueError("Unable to decrypt key: wrong passphrase?")

		# 2. Get the length of the raw key, by interpreting the length bytes
		offset = 23
		rawKeyLength = ord(decryptedKey[offset])
		det = rawKeyLength & 0x80
		if det == 0: # 1-byte length
			offset += 1
			rawKeyLength = rawKeyLength & 0x7f
		else: # multi-byte length
			bytes = rawKeyLength & 0x7f
			offset += 1
			
			rawKeyLength = 0
			while bytes > 0:
				rawKeyLength *= 256
				rawKeyLength += ord(decryptedKey[offset])
				offset += 1
				bytes -= 1

		# 3. Sanity check
		if offset + rawKeyLength > len(decryptedKey):
			rawKeyLength = len(decryptedKey) - offset
		
		# 4. Extract actual key
		privateKey = decryptedKey[offset:offset+rawKeyLength]
		
		# And we're done.
		self.privateKey = privateKey
		logging.debug("Successfully decrypted private key")
    def fetchPrivateKey(self):
        """Fetch the private key for the user and storage context
		provided to this object, and decrypt the private key
		by using my passphrase.  Store the private key in internal
		storage for later use."""

        # Retrieve encrypted private key from the server
        logging.debug("Fetching encrypted private key from server")
        privKeyObj = self.ctx.get_item("keys", "privkey")
        payload = json.loads(privKeyObj['payload'])
        self.privKeySalt = base64.decodestring(payload['salt'])
        self.privKeyIV = base64.decodestring(payload['iv'])
        self.pubKeyURI = payload['publicKeyUri']

        data64 = payload['keyData']
        encryptedKey = base64.decodestring(data64)

        # Now decrypt it by generating a key with the passphrase
        # and performing an AES-256-CBC decrypt.
        logging.debug("Decrypting encrypted private key")

        passKey = PBKDF2(self.passphrase, self.privKeySalt,
                         iterations=4096).read(32)
        cipher = Cipher(alg='aes_256_cbc',
                        key=passKey,
                        iv=self.privKeyIV,
                        op=0)  # 0 is DEC
        cipher.set_padding(padding=1)
        v = cipher.update(encryptedKey)
        v = v + cipher.final()
        del cipher
        decryptedKey = v

        # Result is an NSS-wrapped key.
        # We have to do some manual ASN.1 parsing here, which is unfortunate.

        # 1. Make sure offset 22 is an OCTET tag; if this is not right, the decrypt
        # has gone off the rails.
        if ord(decryptedKey[22]) != 4:
            logging.debug(
                "Binary layout of decrypted private key is incorrect; probably the passphrase was incorrect."
            )
            raise ValueError("Unable to decrypt key: wrong passphrase?")

        # 2. Get the length of the raw key, by interpreting the length bytes
        offset = 23
        rawKeyLength = ord(decryptedKey[offset])
        det = rawKeyLength & 0x80
        if det == 0:  # 1-byte length
            offset += 1
            rawKeyLength = rawKeyLength & 0x7f
        else:  # multi-byte length
            bytes = rawKeyLength & 0x7f
            offset += 1

            rawKeyLength = 0
            while bytes > 0:
                rawKeyLength *= 256
                rawKeyLength += ord(decryptedKey[offset])
                offset += 1
                bytes -= 1

        # 3. Sanity check
        if offset + rawKeyLength > len(decryptedKey):
            rawKeyLength = len(decryptedKey) - offset

        # 4. Extract actual key
        privateKey = decryptedKey[offset:offset + rawKeyLength]

        # And we're done.
        self.privateKey = privateKey
        logging.debug("Successfully decrypted private key")