Ensures that the client receives the AES key.
352833
def _handshake(self, conn, addr):
        '''
        
        '''
        # waiting for the magic request message
        msg = conn.recv(len(MAGIC_REQ))
        log.debug('Received message %s from %s', msg, addr)
        if msg != MAGIC_REQ:
            log.warning('%s is not a valid REQ message from %s', msg, addr)
            return
        log.debug('Sending the private key')
        conn.send(self.__key)
        # wait for explicit ACK
        log.debug('Waiting for the client to confirm')
        msg = conn.recv(len(MAGIC_ACK))
        if msg != MAGIC_ACK:
            return
        log.debug('Sending the signature key')
        conn.send(self.__sgn)
        # wait for explicit ACK
        log.debug('Waiting for the client to confirm')
        msg = conn.recv(len(MAGIC_ACK))
        if msg != MAGIC_ACK:
            return
        log.info('%s is now authenticated', addr)
        self.keep_alive(conn)
774368
def pre_fork(self, _):
        '''
        
        '''
        if 'aes' not in salt.master.SMaster.secrets:
            # TODO: This is still needed only for the unit tests
            # 'tcp_test.py' and 'zeromq_test.py'. Fix that. In normal
            # cases, 'aes' is already set in the secrets.
            salt.master.SMaster.secrets['aes'] = {
                'secret': multiprocessing.Array(
                    ctypes.c_char,
                    salt.utils.stringutils.to_bytes(salt.crypt.Crypticle.generate_key_string())
                ),
                'reload': salt.crypt.Crypticle.generate_key_string
            }
1251547
function hmac(data, key) {
  mctx.init(key);
  mctx.update(data);
  return mctx.finish();
}
293058
function( input, key ) {

    if( !Buffer.isBuffer( input ) )
      throw new TypeError( 'Input must be a buffer' )

    if( this.type === 'PLAIN' )
      return Buffer.allocUnsafe(0)

    if( !Buffer.isBuffer( key ) )
      throw new TypeError( 'Key must be a buffer' )

    var signature = this.type === 'HS' ?
      crypto.createHmac( this.algorithm + this.bits, key ) :
      crypto.createSign( this.algorithm + this.bits )

    signature.update( input )

    var digest = this.type === 'HS' ?
      signature.digest() :
      signature.sign( key )

    if( this.type === 'ES' )
      digest = this._signECDSA( digest )

    return digest

  }
1025117
public static byte[] generateAesKey(int keysize) {
		try {
			KeyGenerator keyGenerator = KeyGenerator.getInstance(AES_ALG);
			keyGenerator.init(keysize);
			SecretKey secretKey = keyGenerator.generateKey();
			return secretKey.getEncoded();
		} catch (GeneralSecurityException e) {
			throw ExceptionUtil.unchecked(e);
		}
	}
284875
def aes_key(self, data):
        
        old = self.key
        if data:
            new = self._decode_input_string(data)
            if len(new) == 16:
                self.key = new
            else:
                raise yubico_exception.InputError('AES128 key must be exactly 16 bytes')

        return old
637533
function(keyId) {
    var res = this.get("25519KeysignedKey" + keyId);
    if (res !== undefined) {
      if (!(res.pubKey instanceof ArrayBuffer)) {
        res.pubKey = convertToArrayBuffer(res.pubKey);
      }
      if (!(res.privKey instanceof ArrayBuffer)) {
        res.privKey = convertToArrayBuffer(res.privKey);
      }
      res = { pubKey: res.pubKey, privKey: res.privKey };
    }
    return Promise.resolve(res);
  }
68178
function Verifier(givenMasterKey) {
  var masterKey = givenMasterKey || MASTER_KEY;
  if (!masterKey) {
    throw new errors.ValidationFailed('invalid master key');
  }
  this.masterKey = base64url.toBuffer(masterKey);
}
764517
function publicKeyVerify(key) {
  if (key.length === 0)
    return false;

  switch (key[0]) {
    case 0x02:
    case 0x03:
      return key.length === 33;
    case 0x04:
      if (key.length !== 65)
        return false;

      return secp256k1.publicKeyVerify(key);
    default:
      return false;
  }
}
1295543
def _handle_aes(self, data):
        '''
        
        '''
        if 'cmd' not in data:
            log.error('Received malformed command %s', data)
            return {}
        cmd = data['cmd']
        log.trace('AES payload received with command %s', data['cmd'])
        if cmd.startswith('__'):
            return False
        if self.opts['master_stats']:
            start = time.time()

        def run_func(data):
            return self.aes_funcs.run_func(data['cmd'], data)

        with StackContext(functools.partial(RequestContext,
                                            {'data': data,
                                             'opts': self.opts})):
            ret = run_func(data)

        if self.opts['master_stats']:
            stats = salt.utils.event.update_stats(self.stats, start, data)
            self._post_stats(stats)
        return ret
983488
def encrypt(plaintext_str, keys):
    
    assert keys, 'Must provide at least one key to encrypt with'
    ctx = gpg.core.Context(armor=True)
    out = ctx.encrypt(plaintext_str, recipients=keys, sign=False,
                      always_trust=True)[0]
    return out
833277
def _handle_status(self, key, value):
        
        if key in (
                'NO_SECKEY',
                'BEGIN_DECRYPTION',
                'DECRYPTION_FAILED',
                'END_DECRYPTION',
                'GOOD_PASSPHRASE',
                'BAD_PASSPHRASE',
                'KEY_CONSIDERED'
            ):
            pass
        elif key == 'NODATA':
            self.status = nodata(value)
        elif key == 'ENC_TO':
            key, _, _ = value.split()
            if not self.key:
                self.key = key
            self.encrypted_to.append(key)
        elif key in ('NEED_PASSPHRASE', 'MISSING_PASSPHRASE'):
            self.need_passphrase = True
        elif key == 'NEED_PASSPHRASE_SYM':
            self.need_passphrase_sym = True
        elif key == 'USERID_HINT':
            self.userid_hint = value.strip().split()
        else:
            raise ValueError("Unknown status message: %r" % key)
340806
public static byte[] AesDecryptByBytes(byte[] encryptBytes,byte[] decryptKey) throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
		secureRandom.setSeed(decryptKey);
		kgen.init(128,secureRandom);
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
		byte[] decryptBytes = cipher.doFinal(encryptBytes);
		return decryptBytes;
	}
1161816
function AESKey(key, bits) {
  if (!(this instanceof AESKey))
    return new AESKey(key, bits);

  this.rounds = null;
  this.userKey = key;
  this.bits = bits;

  switch (this.bits) {
    case 128:
      this.rounds = 10;
      break;
    case 192:
      this.rounds = 12;
      break;
    case 256:
      this.rounds = 14;
      break;
    default:
      throw new Error('Bad key size.');
  }

  assert(Buffer.isBuffer(key));
  assert(key.length === this.bits / 8);

  this.decryptKey = null;
  this.encryptKey = null;
}
772978
private static byte[] withCorrectBlockSize(final byte[] key) {
        if (key.length != CcAes.BLOCK) {
            throw new IllegalArgumentException(
                String.format(
                    "the length of the AES key must be exactly %d bytes",
                    CcAes.BLOCK
                )
            );
        }
        return key;
    }
1362744
function aesEncrypt(msg, key, iv) {
    var logger = getLogger('security.cipher.aesEncrypt');
    // Check if padding is needed
    var padding = msg.length % 16;
    if (padding > 0) {
        var paddingBuffer = utility.createRandomBuffer(16 - padding);
        msg = Buffer.concat([msg, paddingBuffer]);
    }
    // Convert buffers to wordArrays
    var plainMsg = buffer2WordArray(msg);
    var keyWordArray = buffer2WordArray(key);
    var ivWordArray = buffer2WordArray(iv);
    if (logger.isDebugEnabled()) {
        logger.debug('plainMsg = %s\nkeyWordArray = %s\nivWordArray = %s',
            JSON.stringify(plainMsg), JSON.stringify(keyWordArray), JSON.stringify(ivWordArray));
    }
    // Encrypt plain message
    var encryptedWordArray = CryptoJS.AES.encrypt(plainMsg, keyWordArray, {
        iv: ivWordArray,
        padding: CryptoJS.pad.NoPadding,
        mode: CryptoJS.mode.IGE
    }).ciphertext;
    if (logger.isDebugEnabled()) {
        logger.debug('encryptedWordArray = %s', JSON.stringify(encryptedWordArray));
    }
    // Return the encrypted buffer
    return wordArray2Buffer(encryptedWordArray);
}
225765
def handle_get_passphrase(self, conn, _):
        """"""
        p1 = self.client.device.ui.get_passphrase('Symmetric encryption:')
        p2 = self.client.device.ui.get_passphrase('Re-enter encryption:')
        if p1 == p2:
            result = b'D ' + util.assuan_serialize(p1.encode('ascii'))
            keyring.sendline(conn, result, confidential=True)
        else:
            log.warning('Passphrase does not match!')