Esempio n. 1
0
def main():
    master_key = open('{{jenkins_home}}/secrets/master.key').read()
    hudson_secret_key = open(
        '{{jenkins_home}}/secrets/hudson.util.Secret').read()

    hashed_master_key = hashlib.sha256(master_key).digest()[:16]
    cipher = Cipher('aes_128_ecb', hashed_master_key, '', 0)
    v = cipher.update(hudson_secret_key)
    x = v + cipher.final()
    assert MAGIC in x

    k = x[:-16]
    k = k[:16]

    token = os.urandom(16).encode('hex')

    plaintext = token + MAGIC
    cipher = Cipher('aes_128_ecb', k, '', 1)
    v = cipher.update(plaintext)
    password = base64.b64encode(v + cipher.final())
    print password

    with open('/etc/jenkins_jobs/jenkins_jobs.ini', 'wb+') as f:
        f.write('\n'.join([
            '[jenkins]', 'user=jenkins',
            'password=%s' % hashlib.md5(token).hexdigest(),
            'url=http://localhost:8080'
        ]))
Esempio n. 2
0
def encrypt_3des(key, text, usebase64=False):
    cipher = Cipher(alg='des_ede3_ecb', key=key, op=1, iv='\0'*16)
    s = cipher.update(text)
    if usebase64:
        return base64.b64encode( s + cipher.final() )
    else:
        return s + cipher.final()
    def decrypt(self, encryptedObject):
        """Given an encrypted object, decrypt it and return the plaintext value.
		
		If necessary, will retrieve the private key and bulk encryption key
		from the storage context associated with self."""

        # Coerce JSON if necessary
        if type(encryptedObject) == str or type(encryptedObject) == unicode:
            encryptedObject = json.loads(encryptedObject)

        # An encrypted object has two relevant fields
        encryptionLabel = encryptedObject['encryption']
        ciphertext = base64.decodestring(encryptedObject['ciphertext'])

        # Go get the keying infromation if need it
        if self.privateKey == None:
            self.fetchPrivateKey()
        if not encryptionLabel in self.bulkKeys:
            self.fetchBulkKey(encryptionLabel)

        # In case you were wondering, this is the same as this operation at the openssl command line:
        # openssl enc -d -in data -aes-256-cbc -K `cat unwrapped_symkey.16` -iv `cat iv.16`

        # Do the decrypt
        logging.debug("Decrypting data record using bulk key %s" %
                      encryptionLabel)
        cipher = Cipher(alg='aes_256_cbc',
                        key=self.bulkKeys[encryptionLabel],
                        iv=self.bulkKeyIVs[encryptionLabel],
                        op=0)  # 0 is DEC
        v = cipher.update(ciphertext)
        v = v + cipher.final()
        del cipher
        logging.debug("Successfully decrypted data record")
        return v
Esempio n. 4
0
 def _new_cipher(key):
     skey = key[0:
                crypto_algo["key_size"]]  # Use first n bytes as crypto key
     iv = key[-crypto_algo["iv_size"]:]  # Use last m bytes as IV
     return Cipher(algorithms.TripleDES(skey),
                   modes.CBC(iv),
                   backend=default_backend())
Esempio n. 5
0
def get_cipher(key, method, op, iv):
    if method == 'rc4-md5':
        return create_rc4_md5(method, key, iv, op)
    elif method in ('salsa20', 'chacha20'):
        return Salsa20Crypto(method, key, iv, op)
    else:
        return Cipher(method.replace('-', '_'), key, iv, op)
Esempio n. 6
0
def decrypt_text(encrypted_text, key):
    # Porting from pyDes-based encryption (see http://git.io/htpk)
    # to use M2Crypto instead (see https://gist.github.com/mrluanma/917014)
    cipher = Cipher(alg="des_ede3_ecb", key=b"{}".format(key), op=0, iv="\0" * 16)
    decrypted_text = cipher.update(base64.b64decode(b"{}".format(encrypted_text)))
    decrypted_text += cipher.final()
    return decrypted_text
Esempio n. 7
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. 8
0
def Encrypt(data):
    print "Enc len=", len(data)
    cipher = Cipher(alg='aes_128_ecb', key=PRIVATE_KEY, iv=iv, op=ENCRYPT_OP)
    buf = cipher.update(data)
    buf = buf + cipher.final()
    del cipher
    return buf
    """
Esempio n. 9
0
def Decrypt(data):

    data = util.h2b(data)
    cipher = Cipher(alg='aes_128_ecb', key=PRIVATE_KEY, iv=iv, op=DECRYPT_OP)
    buf = cipher.update(data)
    buf = buf + cipher.final()
    del cipher
    return buf
Esempio n. 10
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. 11
0
def build_cipher(key, op):
    return Cipher(alg='aes_128_cbc',
                  key=key,
                  iv='\0' * 16,
                  op=op,
                  key_as_bytes=1,
                  d='sha1',
                  salt='saltsalt',
                  i=5)
Esempio n. 12
0
	def AESDecrypt(cls, data):  
	  '使用aes_128_ecb算法对数据解密'  
	  # 将密文从16进制转为字节流  
	  data = util.h2b(data)  
	  cipher = Cipher(alg = 'aes_128_ecb', key = cls.privateKey, iv = cls.iv, op = DEC)  
	  txt = cipher.update(data)  
	  txt = txt + cipher.final()  
	  del cipher  
	  return txt
Esempio n. 13
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. 14
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. 15
0
def Encrypt(data):
  cipher = Cipher(alg = 'aes_128_ecb', key = PRIVATE_KEY, iv = iv, op = ENCRYPT_OP)
  buf = cipher.update(data)
  buf = buf + cipher.final()
  del cipher
  # 将明文从字节流转为16进制
  output = ''
  for i in buf:
    output += '%02X' % (ord(i))
  return output
Esempio n. 16
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. 17
0
	def AESEncrypt(cls, data):  
	  '使用aes_128_ecb算法对数据加密'  
	  cipher = Cipher(alg = 'aes_128_ecb', key = cls.privateKey, iv = cls.iv, op = ENC)  
	  txt = cipher.update(data)  
	  txt = txt + cipher.final()  
	  del cipher  
	  # 将明文从字节流转为16进制  
	  output = ''  
	  for i in txt:  
	    output += '%02X' % (ord(i))  
	  return output  
Esempio n. 18
0
def Decrypt(data):

    #data = util.h2b(data)
    data1 = binascii.a2b_hex(data)
    #for i in len(data)/2:
    #    data1 += binascii.a2b_hex()
    cipher = Cipher(alg='aes_128_ecb', key=PRIVATE_KEY, iv=iv, op=DECRYPT_OP)
    buf = cipher.update(data1)
    buf = buf + cipher.final()
    del cipher
    return buf
Esempio n. 19
0
def Decrypt(data):
  # 将密文从16进制转为字节流
  data = util.h2b(data)
  cipher = Cipher(alg = 'aes_128_ecb', key = PRIVATE_KEY, iv = iv, op = DECRYPT_OP)
  buf = cipher.update(data)
  buf = buf + cipher.final()
  del cipher
  return buf


# print Decrypt('6C0D072989D9F7271EF1BD5AA1C830F2')
Esempio n. 20
0
    def _decrypt(self, payload, key):
        ''' Decrypt payload fetched from server. '''

        ciphertext = payload['ciphertext'].decode('base64')
        iv = payload['IV'].decode('base64')

        # Perform the actual decryption.
        cipher = Cipher(alg='aes_256_cbc', key=key, iv=iv, op=0)
        v = cipher.update(ciphertext)
        v = v + cipher.final()
        del cipher

        return json.loads(v)
Esempio n. 21
0
def aes_api_data_encrypt(data):
    """
    加密api数据
    :param data: 字符串数据等
    :return: base64数据
    """
    key = '!@#$%^&*()_+|%^&'
    iv = '!@#$%^&*()_+|%^&'
    pad_data = pkcs7_pad(data, 16)
    encryptor = Cipher(alg="aes_128_cbc", key=key, iv=iv, op=OP_ENCRYPT, padding=0)
    str = encryptor.update(pad_data)
    str = str + encryptor.final()
    base64str = base64.b64encode(str)
    return base64str
Esempio n. 22
0
def decrypt_aes(key, text, iv='\0'*16, usebase64=False):
    """ aes比3des: 加解密速度快, 资源消耗低, 安全级别高
    param:
        key: 密钥, 16个字符
        note: 当key或iv不足16个字符的时候, 后面补字符'0'; 当超过16个字符的时候, 截断为前面16个字符
        note: 标准Base64编码会出现字符+和/,在URL中不能作为参数,而urlsafe的base64编码,其实是把字符+和/分别变成-和_
    """
    key = _autofill(key) # 当使用 aes_256时候, key需要32个字符; 而使用aes_128时, key需要16个字符
    iv = _autofill(iv)
    if usebase64:
        text = base64.urlsafe_b64decode( text )
    cipher = Cipher(alg='aes_128_cbc', key=key, op=0, iv=iv) # aes_256_cbc, aes_256_ecb
    s = cipher.update(text)
    return s + cipher.final()
Esempio n. 23
0
def aes_html_data_decrypt(data):
    """
    解密Html传过来的数据
    :param data: 数据Base64编码
    :return: 解密后的字符串,如果为无效的字符串解密,则返回空串
    """
    key = '!@#$%^&*()_+|%^&'
    iv = '!@#$%^&*()_+|%^&'
    decryptor = Cipher(alg="aes_128_cbc", key=key, iv=iv, op=OP_DECRYPT, padding=0)
    encrypted_data = base64.b64decode(data)
    decrypted_data = decryptor.update(encrypted_data)
    decrypted_data += decryptor.final()

    return unpad(decrypted_data)
Esempio n. 24
0
def aes_decrypt(mess, aes_key, size=256):
    if size == 128:
        algo = 'aes_128_cbc'
    elif size == 256:
        algo = 'aes_256_cbc'
    else:
        algo = 'aes_128_cbc'
    mess = b64decode(mess)
    cipher = Cipher(alg=algo, key=aes_key, iv=IV, op=0)
    o = cipher.update(mess)
    o = o + cipher.final()
    del cipher

    return o
Esempio n. 25
0
    def get_cipher(self, password, method, op, iv=None):
        password = password.encode('utf-8')
        method = method.lower()
        m = self.get_cipher_len(method)
        if m:
            key, iv_ = EVP_BytesToKey(password, m[0], m[1])
            if iv is None:
                iv = iv_[:m[1]]
            if op == 1:
                self.cipher_iv = iv[:m[
                    1]]  # this iv is for cipher, not decipher
            return Cipher(method.replace('-', '_'), key, iv, op)

        logging.error('method %s not supported' % method)
        sys.exit(1)
Esempio n. 26
0
def str_decrypt(crypted, key, iv=IV, algorithm=ALGORITHM):
    """ Decrypt a string with a key.  For a higher-level decryption
    interface, see :func:`ssl_decrypt`.

    :param crypted: The raw binary encrypted data
    :type crypted: string
    :param key: The encryption key to decrypt with
    :type key: string
    :param iv: The initialization vector
    :type iv: string
    :param algorithm: The cipher algorithm to use
    :type algorithm: string
    :returns: string - The decrypted data
    """
    cipher = Cipher(alg=algorithm, key=key, iv=iv, op=DECRYPT)
    return _cipher_filter(cipher, crypted)
Esempio n. 27
0
 def get_cipher(self, password, method, op, iv):
     password = password.encode('utf-8')
     method = method.lower()
     m = self.get_cipher_len(method)
     if m:
         key, _ = EVP_BytesToKey(password, m[0], 0)
         iv = iv[:m[1]]
         if op == 1:
             self.cipher_iv = iv  # this iv is for cipher, not decipher
         if method == 'rc4-md5':
             return create_rc4_md5(method, key, iv, op)
         elif method in ('salsa20', 'chacha20'):
             return Salsa20Crypto(method, key, iv, op)
         else:
             return Cipher(method.replace('-', '_'), key, iv, op)
     raise ValueError('method %s not supported' % method)
Esempio n. 28
0
    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)
Esempio n. 29
0
def str_encrypt(plaintext, key, iv=IV, algorithm=ALGORITHM, salt=None):
    """ Encrypt a string with a key.  For a higher-level encryption
    interface, see :func:`ssl_encrypt`.

    :param plaintext: The plaintext data to encrypt
    :type plaintext: string
    :param key: The key to encrypt the data with
    :type key: string
    :param iv: The initialization vector
    :type iv: string
    :param algorithm: The cipher algorithm to use
    :type algorithm: string
    :param salt: The salt to use
    :type salt: string
    :returns: string - The decrypted data
    """
    cipher = Cipher(alg=algorithm, key=key, iv=iv, op=ENCRYPT, salt=salt)
    return _cipher_filter(cipher, plaintext)
Esempio n. 30
0
def encrypt_mode_cbc(data, key, iv):
    """
    aes加密得到十进制串
    :param data:
    :param key:
    :param iv:
    :return:
    """

    cipher = Cipher(alg='aes_128_cbc', key=key, iv=iv, op=1)
    buf = cipher.update(data)
    buf += cipher.final()
    del cipher

    # 将明文从字节流转为十进制
    des_list = [int('%02X' % (ord(i)), 16) for i in buf]

    # 原码转补码
    in_list = [~h ^ 255 if h > 128 else h for h in des_list]

    return in_list