Private: Asymmetrically encrypt a symmetrical encryption key

 triple_des_key - A Triple DES (3DES) encryption key

 Returns a base64-encoded and url-encoded representation of the $triple_des_key
324923
def encrypt_cipher(triple_des_key)
      triple_des_key_urlencoded = ''

      key = OpenSSL::PKey::RSA.new(PUBLIC_KEY)
      encrypted_triple_des = key.public_encrypt(triple_des_key)
      encrypted_base64 = Base64.strict_encode64(encrypted_triple_des)
      triple_des_key_urlencoded = "#{CGI::escape(encrypted_base64)}decode"

      return triple_des_key_urlencoded
    end
839485
function encrypt(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')
    }

    var crypted = aes.encipher(data, key, iv);

    crypted = Buffer.from(crypted, 'binary');
    
    let ret = Buffer.alloc(crypted.length*2);
    for(let i = 0; i < crypted.length; i++){
        ret[2*i] = (crypted[i] >> 4) + 97;
        ret[2*i+1] = (crypted[i] & 0x0F) + 97;
    }
    return ret.toString('binary');
}
645902
def key_CV(key, kcv_length=6):
    
    cipher = DES3.new(B2raw(key), DES3.MODE_ECB)
    encrypted = raw2B(cipher.encrypt(B2raw(b'00000000000000000000000000000000')))

    return encrypted[:kcv_length]
234440
public static byte[] decryptBase64_3DES(byte[] data, byte[] key) {
        try {
            return decrypt3DES(Base64.getDecoder().decode(data), key);
        } catch (Exception e) {
            return null;
        }
    }
367724
private function encryptSymmetricKeyWithSystemKey($clearKey, $entity)
    {
        $publicMasterKey = $this->keyStore->getPublicMasterKey();
        $symmetricKey = new SymmetricKey();
        $encryptedKey = base64_encode($this->cryptographyProvider->encryptWithPublicKey($clearKey, $publicMasterKey));
        $symmetricKey->addSystemKey($encryptedKey);

        return $symmetricKey;
    }
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();
    });
}
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);
        }
    }
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
  }
}
576256
def _hilink_decrypt(self, encrypted_firmware):
        '''
        
        '''
        cipher = DES.new(self.DES_KEY, DES.MODE_ECB)

        p1 = encrypted_firmware[0:3]
        p2 = encrypted_firmware[3:]
        p2 += b"\x00" * (8 - (len(p2) % 8))

        d1 = p1 + cipher.decrypt(p2)
        d1 += b"\x00" * (8 - (len(d1) % 8))

        return cipher.decrypt(d1)
590721
function encodePBES2(decoded){
  const epki = { encryptionAlgorithm: {} };

  // algorithm
  epki.encryptionAlgorithm.algorithm = params.passwordBasedEncryptionSchemes[decoded.encryptionAlgorithm.algorithm].oid;

  // kdf
  const kdf = decoded.encryptionAlgorithm.parameters.keyDerivationFunc;
  if(kdf.algorithm === 'pbkdf2') {
    kdf.parameters.prf.algorithm = params.pbkdf2Prfs[kdf.parameters.prf.algorithm].oid;
    kdf.parameters = PBKDF2Params.encode(kdf.parameters, 'der');
  } else throw new Error('UnsupportedKDF');
  kdf.algorithm = params.keyDerivationFunctions[kdf.algorithm].oid;

  // encryptionScheme
  const eS = decoded.encryptionAlgorithm.parameters.encryptionScheme;
  if(Object.keys(PBES2ESParams).indexOf(eS.algorithm) >= 0){
    eS.parameters = PBES2ESParams[eS.algorithm].encode(eS.parameters, 'der');
  } else throw new Error('UnsupportedCipher');
  eS.algorithm = params.encryptionSchemes[eS.algorithm].oid;

  // params
  epki.encryptionAlgorithm.parameters = PBES2Params.encode({ keyDerivationFunc: kdf, encryptionScheme: eS }, 'der');

  // encoded data
  epki.encryptedData = decoded.encryptedData;
  return EncryptedPrivateKeyInfo.encode(epki, 'der');
}
1247331
def encrypt(text, key=None):
    
    if key is None:
        key = ENCRYPT_KEY

    bits = len(key)
    text = pad(text, bits)
    iv = Random.new().read(16)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    return base64.b64encode(iv + cipher.encrypt(text))
953935
def decrypt(s, passphrase, curve='secp160r1', mac_bytes=10):
    
    curve = Curve.by_name(curve)
    privkey = curve.passphrase_to_privkey(passphrase)
    return privkey.decrypt(s, mac_bytes)
454005
def _tls_auth_encrypt(self, s):
        
        wcs = self.tls_session.wcs
        write_seq_num = struct.pack("!Q", wcs.seq_num)
        wcs.seq_num += 1
        return wcs.cipher.auth_encrypt(s, b"", write_seq_num)
398932
def crypto_shorthash_siphashx24(data, key):
    
    if len(key) != XKEYBYTES:
        raise exc.ValueError(
            "Key length must be exactly {0} bytes".format(XKEYBYTES))
    digest = ffi.new("unsigned char[]", XBYTES)
    rc = lib.crypto_shorthash_siphashx24(digest, data, len(data), key)

    ensure(rc == 0, raising=exc.RuntimeError)
    return ffi.buffer(digest, XBYTES)[:]
836260
def encrypt(self, mesg):
        '''
        
        '''
        seqn = next(self._tx_sn)
        rv = self._tx_tinh.enc(s_msgpack.en((seqn, mesg)))
        return rv
164107
def encryption_block_size(self):
        

        encryption_algo = self['algorithm'].native

        if encryption_algo[0:7] in set(['aes128_', 'aes192_', 'aes256_']):
            return 16

        cipher_map = {
            'des': 8,
            'tripledes_3key': 8,
            'rc2': 8,
        }
        if encryption_algo in cipher_map:
            return cipher_map[encryption_algo]

        if encryption_algo == 'rc5':
            return self['parameters'].parsed['block_size_in_bits'].native / 8

        if encryption_algo == 'pbes2':
            return self['parameters']['encryption_scheme'].encryption_block_size

        if encryption_algo.find('.') == -1:
            return {
                'pbes1_md2_des': 8,
                'pbes1_md5_des': 8,
                'pbes1_md2_rc2': 8,
                'pbes1_md5_rc2': 8,
                'pbes1_sha1_des': 8,
                'pbes1_sha1_rc2': 8,
                'pkcs12_sha1_rc4_128': 0,
                'pkcs12_sha1_rc4_40': 0,
                'pkcs12_sha1_tripledes_3key': 8,
                'pkcs12_sha1_tripledes_2key': 8,
                'pkcs12_sha1_rc2_128': 8,
                'pkcs12_sha1_rc2_40': 8,
            }[encryption_algo]

        raise ValueError(unwrap(
            '''
            Unrecognized encryption algorithm "%s"
            ''',
            encryption_algo
        ))
314030
public void encryptBlock(byte[] data, int offset, byte[] dest, int destOffset) {
        // w128_t x;
        // x.q[0] = ((uint64_t *) blk)[0];
        // x.q[1] = ((uint64_t *) blk)[1];
        Kuz128 x = new Kuz128();
        x.setQ(0, ByteStrings.bytesToLong(data, offset));
        x.setQ(1, ByteStrings.bytesToLong(data, offset + 8));

        for (int i = 0; i < 9; i++) {
            // x.q[0] ^= key->k[i].q[0];
            // x.q[1] ^= key->k[i].q[1];
            x.setQ(0, x.getQ(0) ^ key.getK()[i].getQ(0));
            x.setQ(1, x.getQ(1) ^ key.getK()[i].getQ(1));

            for (int j = 0; j < 16; j++) {
                // x.b[j] = kuz_pi[x.b[j]];
                x.getB()[j] = KuznechikTables.kuz_pi[(x.getB()[j] & 0xFF)];
            }
            // kuz_l(&x);
            KuznechikMath.kuz_l(x);
        }

        // ((uint64_t *) blk)[0] = x.q[0] ^ key->k[9].q[0];
        // ((uint64_t *) blk)[1] = x.q[1] ^ key->k[9].q[1];
        ByteStrings.write(dest, destOffset, ByteStrings.longToBytes(x.getQ(0) ^ key.getK()[9].getQ(0)), 0, 8);
        ByteStrings.write(dest, destOffset + 8, ByteStrings.longToBytes(x.getQ(1) ^ key.getK()[9].getQ(1)), 0, 8);
    }