AES encryption cipher.
15626
def cipher(rkey, pt, Nk=4):
    """"""
    assert Nk in {4, 6, 8}
    Nr = Nk + 6

    rkey = rkey.reshape(4*(Nr+1), 32)
    pt = pt.reshape(128)

    # first round
    state = add_round_key(pt, rkey[0:4])

    for i in range(1, Nr):
        state = sub_bytes(state)
        state = shift_rows(state)
        state = mix_columns(state)
        state = add_round_key(state, rkey[4*i:4*(i+1)])

    # final round
    state = sub_bytes(state)
    state = shift_rows(state)
    state = add_round_key(state, rkey[4*Nr:4*(Nr+1)])

    return state
359734
def encrypt(self, data):
        '''
        
        '''
        aes_key, hmac_key = self.keys
        pad = self.AES_BLOCK_SIZE - len(data) % self.AES_BLOCK_SIZE
        if six.PY2:
            data = data + pad * chr(pad)
        else:
            data = data + salt.utils.stringutils.to_bytes(pad * chr(pad))
        iv_bytes = os.urandom(self.AES_BLOCK_SIZE)
        if HAS_M2:
            cypher = EVP.Cipher(alg='aes_192_cbc', key=aes_key, iv=iv_bytes, op=1, padding=False)
            encr = cypher.update(data)
            encr += cypher.final()
        else:
            cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes)
            encr = cypher.encrypt(data)
        data = iv_bytes + encr
        sig = hmac.new(hmac_key, data, hashlib.sha256).digest()
        return data + sig
457648
def encrypt_ige(plain_text, key, iv):
        
        padding = len(plain_text) % 16
        if padding:
            plain_text += os.urandom(16 - padding)

        if cryptg:
            return cryptg.encrypt_ige(plain_text, key, iv)
        if libssl.encrypt_ige:
            return libssl.encrypt_ige(plain_text, key, iv)

        iv1 = iv[:len(iv) // 2]
        iv2 = iv[len(iv) // 2:]

        aes = pyaes.AES(key)

        cipher_text = []
        blocks_count = len(plain_text) // 16

        for block_index in range(blocks_count):
            plain_text_block = list(
                plain_text[block_index * 16:block_index * 16 + 16]
            )
            for i in range(16):
                plain_text_block[i] ^= iv1[i]

            cipher_text_block = aes.encrypt(plain_text_block)

            for i in range(16):
                cipher_text_block[i] ^= iv2[i]

            iv1 = cipher_text_block
            iv2 = plain_text[block_index * 16:block_index * 16 + 16]

            cipher_text.extend(cipher_text_block)

        return bytes(cipher_text)
38344
function AES($z)
    {
        $this->Nb = 4;
        $this->Nk = strlen($z) / 4;
        $this->Nr = $this->Nk + $this->Nb + 2;

        if ($this->Nk != 4 && $this->Nk != 6 && $this->Nk != 8) die("Key is " . ($this->Nk * 32) . " bits long. *not* 128, 192, or 256.");

        $this->Nr = $this->Nk + $this->Nb + 2;
        $this->w  = []; // Nb*(Nr+1) 32-bit words
        $this->s  = [[]];  // 2-D array of Nb colums and 4 rows

        $this->KeyExpansion($z); // places expanded key in w
    }
1145878
function aesDecrypt(msg, key, iv) {
    var logger = getLogger('security.cipher.aesDecrypt');
    var encryptedMsg = buffer2WordArray(msg);
    var keyWordArray = buffer2WordArray(key);
    var ivWordArray = buffer2WordArray(iv);
    if (logger.isDebugEnabled()) {
        logger.debug('encryptedMsg = %s\nkeyWordArray = %s\nivWordArray = %s',
            JSON.stringify(encryptedMsg), JSON.stringify(keyWordArray), JSON.stringify(ivWordArray));
    }
    var decryptedWordArray = CryptoJS.AES.decrypt({ciphertext: encryptedMsg}, keyWordArray, {
        iv: ivWordArray,
        padding: CryptoJS.pad.NoPadding,
        mode: CryptoJS.mode.IGE
    });
    if (logger.isDebugEnabled()) {
        logger.debug('decryptedWordArray = %s', JSON.stringify(decryptedWordArray));
    }
    return wordArray2Buffer(decryptedWordArray);
}
276689
def _encrypt(data):
    """"""
    BS = AES.block_size

    def pad(s):
        n = BS - len(s) % BS
        char = chr(n).encode('utf8')
        return s + n * char

    password = settings.GECKOBOARD_PASSWORD
    salt = Random.new().read(BS - len('Salted__'))
    key, iv = _derive_key_and_iv(password, salt, 32, BS)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    encrypted = b'Salted__' + salt + cipher.encrypt(pad(data))
    return base64.b64encode(encrypted)
804894
def decrypt(self, data):
        '''
        
        '''
        aes_key, hmac_key = self.keys
        sig = data[-self.SIG_SIZE:]
        data = data[:-self.SIG_SIZE]
        if six.PY3 and not isinstance(data, bytes):
            data = salt.utils.stringutils.to_bytes(data)
        mac_bytes = hmac.new(hmac_key, data, hashlib.sha256).digest()
        if len(mac_bytes) != len(sig):
            log.debug('Failed to authenticate message')
            raise AuthenticationError('message authentication failed')
        result = 0

        if six.PY2:
            for zipped_x, zipped_y in zip(mac_bytes, sig):
                result |= ord(zipped_x) ^ ord(zipped_y)
        else:
            for zipped_x, zipped_y in zip(mac_bytes, sig):
                result |= zipped_x ^ zipped_y
        if result != 0:
            log.debug('Failed to authenticate message')
            raise AuthenticationError('message authentication failed')
        iv_bytes = data[:self.AES_BLOCK_SIZE]
        data = data[self.AES_BLOCK_SIZE:]
        if HAS_M2:
            cypher = EVP.Cipher(alg='aes_192_cbc', key=aes_key, iv=iv_bytes, op=0, padding=False)
            encr = cypher.update(data)
            data = encr + cypher.final()
        else:
            cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes)
            data = cypher.decrypt(data)
        if six.PY2:
            return data[:-ord(data[-1])]
        else:
            return data[:-data[-1]]
793252
def cipher_block (self, state):
        """"""
        # PKCS7 Padding
        state=state+[16-len(state)]*(16-len(state))# Fails test if it changes the input with +=

        self._add_round_key(state, 0)

        for i in range(1, self._Nr):
            self._sub_bytes(state)
            self._shift_rows(state)
            self._mix_columns(state, False)
            self._add_round_key(state, i)

        self._sub_bytes(state)
        self._shift_rows(state)
        self._add_round_key(state, self._Nr)
        return state
32425
def decrypt(self, encrypted):
        
        fernet = Fernet(self.decryption_cipher_key)
        return fernet.decrypt(encrypted)
389608
function encrypt(data, key) {
    return Promise.resolve().then(function() {
        var bytesLeft = data.byteLength;
        var currentOffset = 0, blockIndex = 0, totalLength = 0;
        var buffers = [];

        var next = function() {
            var blockLength = Math.min(BlockSize, bytesLeft);
            bytesLeft -= blockLength;

            var blockData = data.slice(currentOffset, currentOffset + blockLength);
            return getBlockHmac(key, blockIndex, blockLength, blockData).then(function(blockHash) {
                var blockBuffer = new ArrayBuffer(32 + 4);
                var stm = new BinaryStream(blockBuffer);
                stm.writeBytes(blockHash);
                stm.setUint32(blockLength, true);

                buffers.push(blockBuffer);
                totalLength += blockBuffer.byteLength;

                if (blockData.byteLength > 0) {
                    buffers.push(blockData);
                    totalLength += blockData.byteLength;
                    blockIndex++;
                    currentOffset += blockLength;
                    return next();
                } else {
                    var ret = new Uint8Array(totalLength);
                    var offset = 0;
                    for (var i = 0; i < buffers.length; i++) {
                        ret.set(new Uint8Array(buffers[i]), offset);
                        offset += buffers[i].byteLength;
                    }
                    return ret.buffer;
                }
            });
        };
        return next();
    });
}
790091
def _cryptodome_cipher(key, iv):
    
    return AES.new(key, AES.MODE_CFB, iv, segment_size=128)
1004941
public static byte[] aesEncrypt(byte[] input, byte[] key, byte[] iv) {
		return aes(input, key, iv, Cipher.ENCRYPT_MODE);
	}
39286
function encrypt (str) {
    var cipher = crypto.createCipher(algorithm, key)
      , crypted = cipher.update(str, from, to) + cipher.final(to)
    return crypted;
  }
1185580
def encrypt(data, digest=True):
    """"""
    alg = get_best_algorithm()
    enc = implementations["encryption"][alg](
        data, implementations["get_key"]()
    )
    return "%s$%s" % (alg, (_to_hex_digest(enc) if digest else enc))
292866
private byte[] decodeBytes(String cipherString) {
        String[] cipherStringBytes = cipherString.split(":");
        byte[] cipherBytes = new byte[cipherStringBytes.length];
        for (int i = 0; i < cipherStringBytes.length; i++) {
            cipherBytes[i] = Byte.parseByte(cipherStringBytes[i]);
        }
        return cipherBytes;
    }
595732
def decrypt_ige(cipher_text, key, iv):
        
        if cryptg:
            return cryptg.decrypt_ige(cipher_text, key, iv)
        if libssl.decrypt_ige:
            return libssl.decrypt_ige(cipher_text, key, iv)

        iv1 = iv[:len(iv) // 2]
        iv2 = iv[len(iv) // 2:]

        aes = pyaes.AES(key)

        plain_text = []
        blocks_count = len(cipher_text) // 16

        cipher_text_block = [0] * 16
        for block_index in range(blocks_count):
            for i in range(16):
                cipher_text_block[i] = \
                    cipher_text[block_index * 16 + i] ^ iv2[i]

            plain_text_block = aes.decrypt(cipher_text_block)

            for i in range(16):
                plain_text_block[i] ^= iv1[i]

            iv1 = cipher_text[block_index * 16:block_index * 16 + 16]
            iv2 = plain_text_block

            plain_text.extend(plain_text_block)

        return bytes(plain_text)
339112
public byte[] decryptAES(byte[] cipher) {

        if (privKey == null) {
            throw new MissingPrivateKeyException();
        }
        if (!(privKey instanceof BCECPrivateKey)) {
            throw new UnsupportedOperationException("Cannot use the private key as an AES key");
        }

        AESFastEngine engine = new AESFastEngine();
        SICBlockCipher ctrEngine = new SICBlockCipher(engine);

        KeyParameter key = new KeyParameter(BigIntegers.asUnsignedByteArray(((BCECPrivateKey) privKey).getD()));
        ParametersWithIV params = new ParametersWithIV(key, new byte[16]);

        ctrEngine.init(false, params);

        int i = 0;
        byte[] out = new byte[cipher.length];
        while (i < cipher.length) {
            ctrEngine.processBlock(cipher, i, out, i);
            i += engine.getBlockSize();
            if (cipher.length - i < engine.getBlockSize())
                break;
        }

        // process left bytes
        if (cipher.length - i > 0) {
            byte[] tmpBlock = new byte[16];
            System.arraycopy(cipher, i, tmpBlock, 0, cipher.length - i);
            ctrEngine.processBlock(tmpBlock, 0, tmpBlock, 0);
            System.arraycopy(tmpBlock, 0, out, i, cipher.length - i);
        }

        return out;
    }