NOTE convert ECB encryption to AES gem or both to openssl
432278
def decipher_ecb(key,input,strip_padding: true)
      plain = decipher_ecb_blockwise(CryptBuffer(key),CryptBuffer(input).chunks_of(@block_size_bytes)).to_crypt_buffer
      strip_padding ? plain.strip_padding : plain
    end
437877
def convert_to_json_with_mac(self, md5digest, hmacdigest):
        # type: (EncryptionMetadata, str, str) -> dict
        
        # encrypt keys
        enc_content_key = blobxfer.operations.crypto.\
            rsa_encrypt_key_base64_encoded(
                None, self._rsa_public_key, self.symmetric_key)
        enc_sign_key = blobxfer.operations.crypto.\
            rsa_encrypt_key_base64_encoded(
                None, self._rsa_public_key, self.signing_key)
        # generate json
        encjson = {
            EncryptionMetadata._JSON_KEY_ENCRYPTION_MODE:
            EncryptionMetadata._ENCRYPTION_MODE,
            EncryptionMetadata._JSON_KEY_CONTENT_IV:
            blobxfer.util.base64_encode_as_string(self.content_encryption_iv),
            EncryptionMetadata._JSON_KEY_WRAPPEDCONTENTKEY: {
                EncryptionMetadata._JSON_KEY_KEYID: 'private:pem',
                EncryptionMetadata._JSON_KEY_ENCRYPTED_KEY: enc_content_key,
                EncryptionMetadata._JSON_KEY_ENCRYPTED_AUTHKEY: enc_sign_key,
                EncryptionMetadata._JSON_KEY_ALGORITHM:
                EncryptionMetadata._ENCRYPTED_KEY_SCHEME,
            },
            EncryptionMetadata._JSON_KEY_ENCRYPTION_AGENT: {
                EncryptionMetadata._JSON_KEY_PROTOCOL:
                EncryptionMetadata._ENCRYPTION_PROTOCOL_VERSION,
                EncryptionMetadata._JSON_KEY_ENCRYPTION_ALGORITHM:
                EncryptionMetadata._ENCRYPTION_ALGORITHM,
            },
            EncryptionMetadata._JSON_KEY_INTEGRITY_AUTH: {
                EncryptionMetadata._JSON_KEY_ALGORITHM:
                EncryptionMetadata._AUTH_ALGORITHM,
            },
            EncryptionMetadata._JSON_KEY_KEY_WRAPPING_METADATA: {},
        }
        if md5digest is not None:
            encjson[EncryptionMetadata._JSON_KEY_BLOBXFER_EXTENSIONS] = {
                EncryptionMetadata._JSON_KEY_PREENCRYPTED_MD5: md5digest
            }
        if hmacdigest is not None:
            encjson[EncryptionMetadata._JSON_KEY_INTEGRITY_AUTH][
                EncryptionMetadata._JSON_KEY_MAC] = hmacdigest
        bencjson = json.dumps(
            encjson, sort_keys=True, ensure_ascii=False).encode(
                EncryptionMetadata._AUTH_ENCODING_TYPE)
        encjson = {
            EncryptionMetadata._METADATA_KEY_NAME:
            json.dumps(encjson, sort_keys=True)
        }
        # compute MAC over encjson
        hmacsha256 = hmac.new(self._signkey, digestmod=hashlib.sha256)
        hmacsha256.update(bencjson)
        authjson = {
            EncryptionMetadata._JSON_KEY_AUTH_METAAUTH: {
                EncryptionMetadata._JSON_KEY_ALGORITHM:
                EncryptionMetadata._AUTH_ALGORITHM,
                EncryptionMetadata._JSON_KEY_AUTH_ENCODING:
                EncryptionMetadata._AUTH_ENCODING_TYPE,
                EncryptionMetadata._JSON_KEY_MAC:
                blobxfer.util.base64_encode_as_string(hmacsha256.digest()),
            }
        }
        encjson[EncryptionMetadata._METADATA_KEY_AUTH_NAME] = json.dumps(
            authjson, sort_keys=True)
        return encjson
32650
function decryptRaw (buffer, passphrase, progressCallback, scryptParams) {
  // 39 bytes: 2 bytes prefix, 37 bytes payload
  if (buffer.length !== 39) throw new Error('Invalid BIP38 data length')
  if (buffer.readUInt8(0) !== 0x01) throw new Error('Invalid BIP38 prefix')
  scryptParams = scryptParams || SCRYPT_PARAMS

  // check if BIP38 EC multiply
  var type = buffer.readUInt8(1)
  if (type === 0x43) return decryptECMult(buffer, passphrase, progressCallback, scryptParams)
  if (type !== 0x42) throw new Error('Invalid BIP38 type')

  passphrase = Buffer.from(passphrase, 'utf8')

  var flagByte = buffer.readUInt8(2)
  var compressed = flagByte === 0xe0
  if (!compressed && flagByte !== 0xc0) throw new Error('Invalid BIP38 compression flag')

  var N = scryptParams.N
  var r = scryptParams.r
  var p = scryptParams.p

  var salt = buffer.slice(3, 7)
  var scryptBuf = scrypt(passphrase, salt, N, r, p, 64, progressCallback)
  var derivedHalf1 = scryptBuf.slice(0, 32)
  var derivedHalf2 = scryptBuf.slice(32, 64)

  var privKeyBuf = buffer.slice(7, 7 + 32)
  var decipher = aes.createDecipheriv('aes-256-ecb', derivedHalf2, NULL)
  decipher.setAutoPadding(false)
  decipher.end(privKeyBuf)

  var plainText = decipher.read()
  var privateKey = xor(derivedHalf1, plainText)

  // verify salt matches address
  var d = BigInteger.fromBuffer(privateKey)
  var address = getAddress(d, compressed)
  var checksum = hash256(address).slice(0, 4)
  assert.deepEqual(salt, checksum)

  return {
    privateKey: privateKey,
    compressed: compressed
  }
}
546672
def _refine_enc(enc):
    '''
    
    '''

    rsa = ['r', 'rsa', 'ssh-rsa']
    dss = ['d', 'dsa', 'dss', 'ssh-dss']
    ecdsa = ['e', 'ecdsa', 'ecdsa-sha2-nistp521', 'ecdsa-sha2-nistp384',
             'ecdsa-sha2-nistp256']
    ed25519 = ['ed25519', 'ssh-ed25519']

    if enc in rsa:
        return 'ssh-rsa'
    elif enc in dss:
        return 'ssh-dss'
    elif enc in ecdsa:
        # ecdsa defaults to ecdsa-sha2-nistp256
        # otherwise enc string is actual encoding string
        if enc in ['e', 'ecdsa']:
            return 'ecdsa-sha2-nistp256'
        return enc
    elif enc in ed25519:
        return 'ssh-ed25519'
    else:
        raise CommandExecutionError(
            'Incorrect encryption key type \'{0}\'.'.format(enc)
        )
551575
function IEncrypt(options){
	options = options || {};
	var key = options.key ? new Buffer(options.key) : crypto.randomBytes(32);
	var debug = options.debug || false;
	
	/**
	 * Encryption method.
	 * @param data - What to encrypt it can be an object, string or number.
	 * @return {String} the encrypted text or null on fail
	 */
	this.encrypt = function(data){
		try{
			//serialize
			var original = serialize(data);
			
			//if serialization failed throw an error
			if(!original) throw new Error('Invalid type of object given for encryption');
			
			//initialization vector
			var vector = new Buffer(crypto.randomBytes(16));
			
			//new cipher
			var cipher = crypto.createCipheriv('aes256', key, vector);
			
			//the encrypted text
			var encrypted = cipher.update(original,'utf8','base64') + cipher.final('base64');
			
			//the signature for the combination of encrypted text and initialization vector
			var hash = this.sign(encrypted+vector.toString('base64'));
			
			//return token ecrypted.vector.hash
			return encrypted + "." + vector.toString('base64') + "." + hash;
		}
		catch(e){
			if(debug) console.error('An error occured while encrypting : %s',e.stack);
			return null;
		}
	};
	
	/**
	 * Decryption method.
	 * @param text {String} to encrypt
	 * @returns {Object} || {String} || {Number} || null on fail
	 */
	this.decrypt = function(text){
		var decipher,
			original,
			t,
			encrypted,
			vector,
			hash,
			new_hash;
		try{
			// split text and save each value (encrypted text,vector,hash)
			t=text.split(".");
			encrypted = t[0];
			vector = new Buffer(t[1], 'base64');
			hash = t[2];
			
			//check data integrity by validating signature 
			if(!this.validate(encrypted+t[1], hash)){
				throw new Error('Could not verify signature');
			}
			
			//new decipher
			decipher = crypto.createDecipheriv('aes256', key, vector);
		    
			//return the resulted object
			original = decipher.update(encrypted, 'base64', 'utf8') + decipher.final('utf8');
			try{
				return JSON.parse(original);
			}
			catch(e){
				return (!isNaN(parseFloat(original)) && isFinite(original) ? parseFloat(original) : original);
			}
		}
		catch(e){
			if(debug) console.error('An error occured while decrypting : %s',e.stack);
			return null;
		}
	};
	
	/**
	 * Produce a signature for the given object
	 * @param data {Object} || {String} || {Number}
	 * @param format {string} The format of the signature - Default is 'base64'
	 * @returns {String} the signature or null on fail
	 */
	this.sign = function(data, format){
		try{
			// Serialize data
			var serialized = serialize(data);
			
			// If not serialized properly throw an Error
			if(!serialized) throw new Error('Cannot serialize given type of object');
			
			// Set formating
			format = format || 'base64';
			
			// Generate and return HMAC
			return crypto.createHmac('sha256', key).update(serialized).digest(format);
		}
		catch(e){
			if(debug) console.error('An error occured while signing : %s',e.stack);
			return null;
		}
	}
	
	/**
	 * Validate data signature
	 * @param data  {Object} || {String} || {Number}
	 * @param signature {String} the produced signature for the data
	 * @param format {String} format of the signature. Default is 'base64'
	 * @return {Boolean}
	 */
	this.validate = function(data, signature, format){
		var new_sign = this.sign(data,format);
		return new_sign?compare(signature,new_sign):false;
	}
	
	/**
	 * Private serialization method
	 * @private
	 * @param data {Object} || {String} || {Number}
	 * @returns {String} or null on fail
	 */
	var serialize = function(data){
		return typeof data === 'object' 
			? JSON.stringify(data) 
			: (typeof data === 'string' || typeof data === 'number' ? String(data) : null);
	}
}
683517
def encode(self, envelope, session, aes_cipher=None, **kwargs):
		
		return WMessengerBytesEnvelope(aes_cipher.encrypt(envelope.message()), meta=envelope)
255333
def crypto_revision_from_options(params)
            case params[:cipher].upcase
            when 'RC4'
                crypto_revision_from_rc4_key(params[:key_size])
            when 'AES'
                crypto_revision_from_aes_key(params[:key_size], params[:hardened])
            else
                raise EncryptionNotSupportedError, "Cipher not supported : #{params[:cipher]}"
            end
        end
561529
def crypto_box(message, nonce, pk, sk):
    
    if len(nonce) != crypto_box_NONCEBYTES:
        raise exc.ValueError("Invalid nonce size")

    if len(pk) != crypto_box_PUBLICKEYBYTES:
        raise exc.ValueError("Invalid public key")

    if len(sk) != crypto_box_SECRETKEYBYTES:
        raise exc.ValueError("Invalid secret key")

    padded = (b"\x00" * crypto_box_ZEROBYTES) + message
    ciphertext = ffi.new("unsigned char[]", len(padded))

    rc = lib.crypto_box(ciphertext, padded, len(padded), nonce, pk, sk)
    ensure(rc == 0,
           'Unexpected library error',
           raising=exc.RuntimeError)

    return ffi.buffer(ciphertext, len(padded))[crypto_box_BOXZEROBYTES:]
228852
def encrypt(data, key, iv, cipher_type)
      aes = OpenSSL::Cipher.new(cipher_type)
      aes.encrypt
      aes.key = key
      aes.iv  = iv unless iv.nil?
      aes.update(data) + aes.final
    end
1022451
def encrypt(self, keys=None, cek="", iv="", **kwargs):
        

        _alg = self["alg"]

        # Find Usable Keys
        if keys:
            keys = self.pick_keys(keys, use="enc")
        else:
            keys = self.pick_keys(self._get_keys(), use="enc")

        if not keys:
            logger.error(KEY_ERR.format(_alg))
            raise NoSuitableEncryptionKey(_alg)

        # Determine Encryption Class by Algorithm
        if _alg in ["RSA-OAEP", "RSA-OAEP-256", "RSA1_5"]:
            encrypter = JWE_RSA(self.msg, **self._dict)
        elif _alg.startswith("A") and _alg.endswith("KW"):
            encrypter = JWE_SYM(self.msg, **self._dict)
        else:  # _alg.startswith("ECDH-ES"):
            encrypter = JWE_EC(**self._dict)
            cek, encrypted_key, iv, params, eprivk = encrypter.enc_setup(
                self.msg, key=keys[0], **self._dict)
            kwargs["encrypted_key"] = encrypted_key
            kwargs["params"] = params

        if cek:
            kwargs["cek"] = cek

        if iv:
            kwargs["iv"] = iv

        for key in keys:
            if isinstance(key, SYMKey):
                _key = key.key
            elif isinstance(key, ECKey):
                _key = key.public_key()
            else:  # isinstance(key, RSAKey):
                _key = key.public_key()

            if key.kid:
                encrypter["kid"] = key.kid

            try:
                token = encrypter.encrypt(key=_key, **kwargs)
                self["cek"] = encrypter.cek if 'cek' in encrypter else None
            except TypeError as err:
                raise err
            else:
                logger.debug(
                    "Encrypted message using key with kid={}".format(key.kid))
                return token
384626
function (input, dir) {
    if (input.length !== 4) {
      throw new sjcl.exception.invalid("invalid aes block size");
    }

    var key = this._key[dir],
        // state variables a,b,c,d are loaded with pre-whitened data
        a = input[0]           ^ key[0],
        b = input[dir ? 3 : 1] ^ key[1],
        c = input[2]           ^ key[2],
        d = input[dir ? 1 : 3] ^ key[3],
        a2, b2, c2,

        nInnerRounds = key.length/4 - 2,
        i,
        kIndex = 4,
        out = [0,0,0,0],
        table = this._tables[dir],

        // load up the tables
        t0    = table[0],
        t1    = table[1],
        t2    = table[2],
        t3    = table[3],
        sbox  = table[4];

    // Inner rounds.  Cribbed from OpenSSL.
    for (i = 0; i < nInnerRounds; i++) {
      a2 = t0[a>>>24] ^ t1[b>>16 & 255] ^ t2[c>>8 & 255] ^ t3[d & 255] ^ key[kIndex];
      b2 = t0[b>>>24] ^ t1[c>>16 & 255] ^ t2[d>>8 & 255] ^ t3[a & 255] ^ key[kIndex + 1];
      c2 = t0[c>>>24] ^ t1[d>>16 & 255] ^ t2[a>>8 & 255] ^ t3[b & 255] ^ key[kIndex + 2];
      d  = t0[d>>>24] ^ t1[a>>16 & 255] ^ t2[b>>8 & 255] ^ t3[c & 255] ^ key[kIndex + 3];
      kIndex += 4;
      a=a2; b=b2; c=c2;
    }

    // Last round.
    for (i = 0; i < 4; i++) {
      out[dir ? 3&-i : i] =
        sbox[a>>>24      ]<<24 ^
        sbox[b>>16  & 255]<<16 ^
        sbox[c>>8   & 255]<<8  ^
        sbox[d      & 255]     ^
        key[kIndex++];
      a2=a; a=b; b=c; c=d; d=a2;
    }

    return out;
  }
1100218
def to_aes_key(password):
    
    password_hash = hashlib.sha256(password.encode('utf-8')).digest()
    return hashlib.sha256(password_hash).digest()
1324220
def p12parse(self):
        '''  '''
        # open it, using password. Supply/read your own from stdin.
        p12 = crypto.load_pkcs12(open(self.p12, 'rb').read(), self.pwd)
        # grab the certs / keys
        p12cert = p12.get_certificate()     # (signed) certificate object
        p12private = p12.get_privatekey()      # private key.
        # dump private key and cert
        symphony_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, p12private)
        symphony_crt = crypto.dump_certificate(crypto.FILETYPE_PEM, p12cert)
        # write tmpfiles
        crtpath = self.write_tmpfile(symphony_crt)
        keypath = self.write_tmpfile(symphony_key)
        # return cert and privkey
        return crtpath, keypath
414570
def encrypt(data, raw_pubkey)
      raise ArgumentError, "invalid pubkey of length #{raw_pubkey.size}" unless raw_pubkey.size == 64
      Crypto::ECIES.encrypt data, raw_pubkey
    end
762825
def decode_auth_plain(ciphertext)
      message = begin
                  @ecc.ecies_decrypt ciphertext[0,307]
                rescue
                  raise AuthenticationError, $!
                end
      raise RLPxSessionError, 'invalid message length' unless message.size == 194

      sig = message[0,65]
      pubkey = message[65+32,64]
      raise InvalidKeyError, 'invalid initiator pubkey' unless Crypto::ECCx.valid_key?(pubkey)

      nonce = message[65+32+64,32]
      flag = message[(65+32+64+32)..-1].ord
      raise RLPxSessionError, 'invalid flag' unless flag == 0

      [307, sig, pubkey, nonce, 4]
    end
213880
def generate_ec_key
      OpenSSL::PKey::EC.new.tap do |ec|
        ec.group = OpenSSL::PKey::EC::Group.new(CURVE_NAME)
        ec.generate_key
        # https://bugs.ruby-lang.org/issues/8177
        ec.define_singleton_method(:private?) { private_key? }
        ec.define_singleton_method(:public?) { public_key? }
      end
    end
1272140
def aes_encrypt(mode, aes_key, aes_iv, *data):
    """"""
    encryptor = Cipher(
        algorithms.AES(aes_key),
        mode(aes_iv),
        backend=default_backend()).encryptor()

    result = None
    for value in data:
        result = encryptor.update(value)
    encryptor.finalize()

    return result, None if not hasattr(encryptor, 'tag') else encryptor.tag