AES keys must be either 16, 24, or 32 bytes long. If a key is provided that is not
    one of these lengths, pad it with zeroes (this is what pgcrypto does).
491164
def aes_pad_key(key):
    
    if len(key) in (16, 24, 32):
        return key
    if len(key) < 16:
        return pad(key, 16, zero=True)
    elif len(key) < 24:
        return pad(key, 24, zero=True)
    else:
        return pad(key[:32], 32, zero=True)
1054317
private static byte[] generateKey(int size) throws SymmetricKeyException {
        if (size <= 0)
            throw new IllegalArgumentException("Size cannot be zero or less than zero.");

        try {
            SecureRandom secureRandom = new SecureRandom();
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(size * 8, secureRandom);
            return keyGenerator.generateKey().getEncoded();
        } catch (NoSuchAlgorithmException e) {
            throw new SymmetricKeyException(e);
        }
    }
1202455
private int[][] generateWorkingKey(byte[] key, boolean forEncryption) {
        int keyLen = key.length;
        if (keyLen < 16 || keyLen > 32 || (keyLen & 7) != 0) {
            throw new IllegalArgumentException("Key length not 128/192/256 bits.");
        }

        int KC = keyLen >>> 2;
        ROUNDS = KC + 6;  // This is not always true for the generalized Rijndael that allows larger block sizes
        int[][] W = new int[ROUNDS + 1][4];   // 4 words in a block

        switch (KC) {
            case 4: {
                int t0 = Pack.littleEndianToInt(key, 0);
                W[0][0] = t0;
                int t1 = Pack.littleEndianToInt(key, 4);
                W[0][1] = t1;
                int t2 = Pack.littleEndianToInt(key, 8);
                W[0][2] = t2;
                int t3 = Pack.littleEndianToInt(key, 12);
                W[0][3] = t3;

                for (int i = 1; i <= 10; ++i) {
                    int u = subWord(shift(t3, 8)) ^ rcon[i - 1];
                    t0 ^= u;
                    W[i][0] = t0;
                    t1 ^= t0;
                    W[i][1] = t1;
                    t2 ^= t1;
                    W[i][2] = t2;
                    t3 ^= t2;
                    W[i][3] = t3;
                }

                break;
            }
            case 6: {
                int t0 = Pack.littleEndianToInt(key, 0);
                W[0][0] = t0;
                int t1 = Pack.littleEndianToInt(key, 4);
                W[0][1] = t1;
                int t2 = Pack.littleEndianToInt(key, 8);
                W[0][2] = t2;
                int t3 = Pack.littleEndianToInt(key, 12);
                W[0][3] = t3;
                int t4 = Pack.littleEndianToInt(key, 16);
                W[1][0] = t4;
                int t5 = Pack.littleEndianToInt(key, 20);
                W[1][1] = t5;

                int rcon = 1;
                int u = subWord(shift(t5, 8)) ^ rcon;
                rcon <<= 1;
                t0 ^= u;
                W[1][2] = t0;
                t1 ^= t0;
                W[1][3] = t1;
                t2 ^= t1;
                W[2][0] = t2;
                t3 ^= t2;
                W[2][1] = t3;
                t4 ^= t3;
                W[2][2] = t4;
                t5 ^= t4;
                W[2][3] = t5;

                for (int i = 3; i < 12; i += 3) {
                    u = subWord(shift(t5, 8)) ^ rcon;
                    rcon <<= 1;
                    t0 ^= u;
                    W[i][0] = t0;
                    t1 ^= t0;
                    W[i][1] = t1;
                    t2 ^= t1;
                    W[i][2] = t2;
                    t3 ^= t2;
                    W[i][3] = t3;
                    t4 ^= t3;
                    W[i + 1][0] = t4;
                    t5 ^= t4;
                    W[i + 1][1] = t5;
                    u = subWord(shift(t5, 8)) ^ rcon;
                    rcon <<= 1;
                    t0 ^= u;
                    W[i + 1][2] = t0;
                    t1 ^= t0;
                    W[i + 1][3] = t1;
                    t2 ^= t1;
                    W[i + 2][0] = t2;
                    t3 ^= t2;
                    W[i + 2][1] = t3;
                    t4 ^= t3;
                    W[i + 2][2] = t4;
                    t5 ^= t4;
                    W[i + 2][3] = t5;
                }

                u = subWord(shift(t5, 8)) ^ rcon;
                t0 ^= u;
                W[12][0] = t0;
                t1 ^= t0;
                W[12][1] = t1;
                t2 ^= t1;
                W[12][2] = t2;
                t3 ^= t2;
                W[12][3] = t3;

                break;
            }
            case 8: {
                int t0 = Pack.littleEndianToInt(key, 0);
                W[0][0] = t0;
                int t1 = Pack.littleEndianToInt(key, 4);
                W[0][1] = t1;
                int t2 = Pack.littleEndianToInt(key, 8);
                W[0][2] = t2;
                int t3 = Pack.littleEndianToInt(key, 12);
                W[0][3] = t3;
                int t4 = Pack.littleEndianToInt(key, 16);
                W[1][0] = t4;
                int t5 = Pack.littleEndianToInt(key, 20);
                W[1][1] = t5;
                int t6 = Pack.littleEndianToInt(key, 24);
                W[1][2] = t6;
                int t7 = Pack.littleEndianToInt(key, 28);
                W[1][3] = t7;

                int u, rcon = 1;

                for (int i = 2; i < 14; i += 2) {
                    u = subWord(shift(t7, 8)) ^ rcon;
                    rcon <<= 1;
                    t0 ^= u;
                    W[i][0] = t0;
                    t1 ^= t0;
                    W[i][1] = t1;
                    t2 ^= t1;
                    W[i][2] = t2;
                    t3 ^= t2;
                    W[i][3] = t3;
                    u = subWord(t3);
                    t4 ^= u;
                    W[i + 1][0] = t4;
                    t5 ^= t4;
                    W[i + 1][1] = t5;
                    t6 ^= t5;
                    W[i + 1][2] = t6;
                    t7 ^= t6;
                    W[i + 1][3] = t7;
                }

                u = subWord(shift(t7, 8)) ^ rcon;
                t0 ^= u;
                W[14][0] = t0;
                t1 ^= t0;
                W[14][1] = t1;
                t2 ^= t1;
                W[14][2] = t2;
                t3 ^= t2;
                W[14][3] = t3;

                break;
            }
            default: {
                throw new IllegalStateException("Should never get here");
            }
        }

        if (!forEncryption) {
            for (int j = 1; j < ROUNDS; j++) {
                for (int i = 0; i < 4; i++) {
                    W[j][i] = inv_mcol(W[j][i]);
                }
            }
        }

        return W;
    }
298878
def xor(self, txt, key):
        
        assert isinstance(txt, six.binary_type), "txt: %s is not binary type!" % repr(txt)
        assert isinstance(key, six.binary_type), "key: %s is not binary type!" % repr(key)

        if len(txt) != len(key):
            raise SecureJSLoginError("XOR cipher error: '%s' and '%s' must have the same length!" % (txt, key))

        if six.PY2:
            crypted = "".join([chr(ord(t) ^ ord(k)) for t, k in zip(txt, key)])
        else:
            crypted = [(t ^ k) for t, k in zip(txt, key)]
            crypted = bytes(crypted)
        # log.debug("xor(txt='%s', key='%s'): '%s'", txt, key, crypted)
        return crypted
712196
def decryption(self, ciphertext, key):
        
        if len(ciphertext) != self._key_len:
            raise pyrtl.PyrtlError("Ciphertext length is invalid")
        if len(key) != self._key_len:
            raise pyrtl.PyrtlError("key length is invalid")
        key_list = self._key_gen(key)
        t = self._add_round_key(ciphertext, key_list[10])

        for round in range(1, 11):
            t = self._inv_shift_rows(t)
            t = self._sub_bytes(t, True)
            t = self._add_round_key(t, key_list[10 - round])
            if round != 10:
                t = self._mix_columns(t, True)

        return t
1080783
@Override
    protected final long ciphertextLength(long plaintextLength) {
        long cipherBlockSize = contentCryptoScheme.getBlockSizeInBytes();
        long offset = cipherBlockSize - (plaintextLength % cipherBlockSize);
        return plaintextLength + offset;
    }
1118201
function _setupKey()
    {
        $key = $this->key;
        $keyLength = strlen($key);
        $keyStream = range(0, 255);
        $j = 0;
        for ($i = 0; $i < 256; $i++) {
            $j = ($j + $keyStream[$i] + ord($key[$i % $keyLength])) & 255;
            $temp = $keyStream[$i];
            $keyStream[$i] = $keyStream[$j];
            $keyStream[$j] = $temp;
        }

        $this->stream = array();
        $this->stream[CRYPT_RC4_DECRYPT] = $this->stream[CRYPT_RC4_ENCRYPT] = array(
            0, // index $i
            0, // index $j
            $keyStream
        );
    }
663735
function checkLengths(k, n) {
  if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size');
  if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size');
}
1021520
def rfc6979_ecdsa_nonce(hash, privkey)
      raise ArgumentError, "Hash must be 32 bytes long" if hash.bytesize != 32
      raise ArgumentError, "Private key must be 32 bytes long" if privkey.bytesize != 32

      autorelease do |pool|
        order = self.group_order

        # Step 3.2.a. hash = H(message). Already performed by the caller.

        # Step 3.2.b. V = 0x01 0x01 0x01 ... 0x01 (32 bytes equal 0x01)
        v = "\x01".b*32

        # Step 3.2.c. K = 0x00 0x00 0x00 ... 0x00 (32 bytes equal 0x00)
        k = "\x00".b*32

        # Step 3.2.d. K = HMAC-SHA256(key: K, data: V || 0x00 || int2octets(privkey) || bits2octets(hash))
        h1 = pool.new_bn(hash)
        BN_div(nil, h1, h1, order, pool.bn_ctx) # h1 = h1 % order
        h1data = data_from_bn(h1, min_length: 32)
        k = BTC.hmac_sha256(key: k, data: v + "\x00".b + privkey + h1data)

        # Step 3.2.e. V = HMAC-SHA256(key: K, data: V)
        v = BTC.hmac_sha256(key: k, data: v)

        # Step 3.2.f. K = HMAC-SHA256(key: K, data: V || 0x01 || int2octets(privkey) || bits2octets(hash))
        k = BTC.hmac_sha256(key: k, data: v + "\x01".b + privkey + h1data)

        # Step 3.2.g. V = HMAC-SHA256(key: K, data: V)
        v = BTC.hmac_sha256(key: k, data: v)

        # Step 3.2.h.
        zero32 = "\x00".b*32
        10000.times do
          t = BTC.hmac_sha256(key: k, data: v)
          tn = pool.new_bn(t)
          if BN_cmp(tn, order) < 0
            nonce = data_from_bn(tn, min_length: 32)
            if nonce != zero32
              return nonce
            end
          end
          # Note: the probability of not succeeding at the first try is about 2^-127.
          k = BTC.hmac_sha256(key: k, data: v + zero32)
          v = BTC.hmac_sha256(key: k, data: v)
        end
        # we generated 10000 numbers, none of them is good -> fail.
        raise "Cannot find any good ECDSA nonce after 10000 iterations of RFC6979."
      end
    end
95606
function _setupKey()
    {
        $key = $this->key;
        $keyLength = strlen($key);
        $keyStream = range(0, 255);
        $j = 0;
        for ($i = 0; $i < 256; $i++) {
            $j = ($j + $keyStream[$i] + ord($key[$i % $keyLength])) & 255;
            $temp = $keyStream[$i];
            $keyStream[$i] = $keyStream[$j];
            $keyStream[$j] = $temp;
        }

        $this->stream = array();
        $this->stream[self::DECRYPT] = $this->stream[self::ENCRYPT] = array(
            0, // index $i
            0, // index $j
            $keyStream
        );
    }
1212197
def encryption(self, plaintext, key):
        
        if len(plaintext) != self._key_len:
            raise pyrtl.PyrtlError("Ciphertext length is invalid")
        if len(key) != self._key_len:
            raise pyrtl.PyrtlError("key length is invalid")

        key_list = self._key_gen(key)
        t = self._add_round_key(plaintext, key_list[0])

        for round in range(1, 11):
            t = self._sub_bytes(t)
            t = self._shift_rows(t)
            if round != 10:
                t = self._mix_columns(t)
            t = self._add_round_key(t, key_list[round])
        return t
967436
def bit_size(self):
        

        if self._bit_size is None:
            if self.algorithm == 'rsa':
                prime = self['private_key'].parsed['modulus'].native
            elif self.algorithm == 'dsa':
                prime = self['private_key_algorithm']['parameters']['p'].native
            elif self.algorithm == 'ec':
                prime = self['private_key'].parsed['private_key'].native
            self._bit_size = int(math.ceil(math.log(prime, 2)))
            modulus = self._bit_size % 8
            if modulus != 0:
                self._bit_size += 8 - modulus
        return self._bit_size
426384
function aesKeyWrap(cek, key, bits) {
  let bytes = bits >> 3;
  if (typeof key === 'string') {
    key = Buffer.from(key, 'base64');
  } else if (!(key instanceof Buffer)) {
    throw new TypeError('Key must be a buffer or a base64-encoded string');
  }
  if (key.length < bytes) {
    throw new TypeError(`Key length must be at least ${bytes} bytes`);
  }
  key = key.slice(0, bytes);
  let r = [];
  for (let i = 0; i < cek.length; i += 8) {
    r.push(cek.slice(i, i + 8));
  }
  let iv = Buffer.alloc(16);
  let a = Buffer.from('A6A6A6A6A6A6A6A6', 'hex');
  let count = 1;
  for (let j = 0; j < 6; j++) {
    for (let i = 0; i < r.length; i++) {
      let cipher = crypto.createCipheriv(`AES${bits}`, key, iv);
      let c = `000000000000000${count.toString(16)}`.slice(-16);
      let b = cipher.update(Buffer.concat([a, r[i]]));
      a = Buffer.from(c, 'hex');
      for (let n = 0; n < 8; n++) {
        a[n] ^= b[n];
      }
      r[i] = b.slice(8, 16);
      count++;
    }
  }
  return buf2b64url(Buffer.concat([a].concat(r)));
}
49715
public static int decrypt(int value, byte[] key) {
		int[] buf = new int[4];

		buf[0] = ((value >> 24) & 0xff);
		buf[1] = ((value >> 16) & 0xff);
		buf[2] = ((value >> 8) & 0xff);
		buf[3] = ((value >> 0) & 0xff);

		skip32(key, buf, false);

		int out = ((buf[0]) << 24) | ((buf[1]) << 16) | ((buf[2]) << 8)
				| (buf[3]);

		return out;
	}
69231
function pkcs1pad2(s, n) {
        if (n < s.length + 11) { // TODO: fix for utf-8
            console.error("Message too long for RSA");
            return null;
        }
        var ba = new Array();
        var i = s.length - 1;
        while (i >= 0 && n > 0) {
            var c = s.charCodeAt(i--);
            if (c < 128) { // encode using utf-8
                ba[--n] = c;
            }
            else if ((c > 127) && (c < 2048)) {
                ba[--n] = (c & 63) | 128;
                ba[--n] = (c >> 6) | 192;
            }
            else {
                ba[--n] = (c & 63) | 128;
                ba[--n] = ((c >> 6) & 63) | 128;
                ba[--n] = (c >> 12) | 224;
            }
        }
        ba[--n] = 0;
        var rng = new SecureRandom();
        var x = new Array();
        while (n > 2) { // random non-zero pad
            x[0] = 0;
            while (x[0] == 0) rng.nextBytes(x);
            ba[--n] = x[0];
        }
        ba[--n] = 2;
        ba[--n] = 0;
        return new BigInteger(ba);
    }
635921
function (sessionKey) {

        //The first 16 bytes (MSB first) will be the key, the next 16 bytes (MSB first) will be the initialization vector (IV), and the final 8 bytes (MSB first) will be the salt.
        var key = new Buffer(16); //just the key... +8); //key plus salt
        var iv = new Buffer(16); //initialization vector

        sessionKey.copy(key, 0, 0, 16); //copy the key
        //sessionKey.copy(key, 16, 32, 40); //append the 8-byte salt
        sessionKey.copy(iv, 0, 16, 32); //copy the iv

        //are we not be doing something with the salt here?

        return crypto.createCipheriv('aes-128-cbc', key, iv);
    }
328834
function decrypt(key, iv, data) {
    if(!Buffer.isBuffer(key)) {
        assert(typeof key === 'string');
        key = Buffer.from(key, 'binary')
    }

    if(!Buffer.isBuffer(iv)) {
        assert(typeof iv === 'string');
        iv = Buffer.from(iv, 'binary')
    }

    if(!Buffer.isBuffer(data)) {
        assert(typeof data === 'string');
        data = Buffer.from(data, 'binary')
    }

    let ret = Buffer.alloc(data.length/2);
    for(let i = 0; i < ret.length; i++){
        ret[i] = ((data[i*2]-97)<<4) | (data[i*2+1]-97);
    }

    var decoded = aes.decipher(ret, key, iv);
    return decoded.toString('binary');
}