Create new cipher based on the valid mode from {@link Cipher} class.

@param mode Either Cipher.ENRYPT_MODE or Cipher.DECRYPT_MODE
@param spec Param spec (IV)
@return The cipher
@throws IOException For any unexpected exceptions
430807
private Cipher cipher(final int mode, final AlgorithmParameterSpec spec)
        throws IOException {
        try {
            final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(mode, this.key, spec, this.random);
            return cipher;
        } catch (final InvalidKeyException | NoSuchAlgorithmException
            | InvalidAlgorithmParameterException
            | NoSuchPaddingException ex) {
            throw new IOException(ex);
        }
    }
297307
@Restricted(NoExternalUse.class) // TODO pending ApI
    public Cipher decrypt(byte[] iv) {
        try {
            Cipher cipher = Secret.getCipher(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, getKey(), new IvParameterSpec(iv));
            return cipher;
        } catch (GeneralSecurityException e) {
            throw new AssertionError(e);
        }
    }
177849
public byte[] encrypt(final byte[] iv, final byte[] message) throws RuntimeException {

        AEADParameters aeadParams = new AEADParameters(
                new KeyParameter(key), TAG_LENGTH,
                iv,
                authData);

        cipher.init(true, aeadParams);
        byte[] cipherText = newBuffer(cipher.getOutputSize(message.length));
        int outputOffset = cipher.processBytes(message, 0, message.length, cipherText, 0);

        try {
            cipher.doFinal(cipherText, outputOffset);
        } catch (InvalidCipherTextException e) {
            throw new RuntimeException("Error: ", e);
        }

        return cipherText;
    }
1287252
private Cipher createCipher() throws GeneralSecurityException {
		if(algorithmProvider != null) {
			return Cipher.getInstance(algorithm, algorithmProvider);
		} else {
			return Cipher.getInstance(algorithm);
		}
	}
216589
protected void writeSpecToFile(Path specPath, Spec spec) throws IOException {
    byte[] serializedSpec = this.specSerDe.serialize(spec);
    try (FSDataOutputStream os = fs.create(specPath, true)) {
      os.write(serializedSpec);
    }
  }
260274
@Override
  public String cipherSuite()
  {
    SSLSocket sslSocket = _sslSocket;
    
    if (sslSocket == null) {
      return super.cipherSuite();
    }
    
    SSLSession sslSession = sslSocket.getSession();
    
    if (sslSession != null) {
      return sslSession.getCipherSuite();
    }
    else {
      return null;
    }
  }
285409
private void createStreams(SecretKey encryptionKey, SecretKey hmacKey,
      byte[] iv, OutputStream out) throws CryptorException {

    this.iv = iv;

    try {
      Cipher cipher = Cipher.getInstance(AES256JNCryptor.AES_CIPHER_ALGORITHM);
      cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, new IvParameterSpec(iv));

      try {
        Mac mac = Mac.getInstance(AES256JNCryptor.HMAC_ALGORITHM);
        mac.init(hmacKey);

        macOutputStream = new MacOutputStream(out, mac);
        cipherStream = new CipherOutputStream(macOutputStream, cipher);

      } catch (GeneralSecurityException e) {
        throw new CryptorException("Failed to initialize HMac", e);
      }

    } catch (GeneralSecurityException e) {
      throw new CryptorException("Failed to initialize AES cipher", e);
    }
  }
1298020
final byte[] crypto(final byte[] input, final int offset, final int len, final boolean decrypt)
			throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException,
			BadPaddingException {
		aesCipher.init(decrypt ? Cipher.DECRYPT_MODE : Cipher.ENCRYPT_MODE, aesKey, aesIV);
		return aesCipher.doFinal(input, offset, len);
	}
684887
private byte[] encryptInternal(SecretKeySpec key, String toEncrypt) {
        try {
            Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM + ENCRYPTION_ALGORITHM_MODIFIER);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(toEncrypt.getBytes(ENCODING));
        } catch (GeneralSecurityException e) {
            throw new RuntimeException("Exception during decryptInternal: " + e, e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Exception during encryptInternal: " + e, e);
        }
    }
280586
@SuppressWarnings("InsecureCryptoUsage") // Only used in known-weak crypto "legacy" mode.
  static byte[] aes128Encrypt(StringBuilder message, String key) {
    try {
      key = normalizeString(key, 16);
      rightPadString(message, '{', 16);
      Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
      cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
      return cipher.doFinal(message.toString().getBytes());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
920123
static ConnectionSpec convertSpec(com.squareup.okhttp.ConnectionSpec spec) {
    Preconditions.checkArgument(spec.isTls(), "plaintext ConnectionSpec is not accepted");

    List<com.squareup.okhttp.TlsVersion> tlsVersionList = spec.tlsVersions();
    String[] tlsVersions = new String[tlsVersionList.size()];
    for (int i = 0; i < tlsVersions.length; i++) {
      tlsVersions[i] = tlsVersionList.get(i).javaName();
    }

    List<com.squareup.okhttp.CipherSuite> cipherSuiteList = spec.cipherSuites();
    CipherSuite[] cipherSuites = new CipherSuite[cipherSuiteList.size()];
    for (int i = 0; i < cipherSuites.length; i++) {
      cipherSuites[i] = CipherSuite.valueOf(cipherSuiteList.get(i).name());
    }

    return new ConnectionSpec.Builder(spec.isTls())
        .supportsTlsExtensions(spec.supportsTlsExtensions())
        .tlsVersions(tlsVersions)
        .cipherSuites(cipherSuites)
        .build();
  }
737413
public static TermLengthOrPercent createLengthOrPercent(String spec)
    {
        spec = spec.trim();
        if (spec.endsWith("%"))
        {
            try {
                float val = Float.parseFloat(spec.substring(0, spec.length() - 1));
                TermPercent perc = CSSFactory.getTermFactory().createPercent(val);
                return perc;
            } catch (NumberFormatException e) {
                return null;
            }
        }
        else
        {
            try {
                float val = Float.parseFloat(spec);
                TermLength len = CSSFactory.getTermFactory().createLength(val, TermLength.Unit.px);
                return len;
            } catch (NumberFormatException e) {
                return null;
            }
        }
    }
492367
public static String getSchemePrefix(String spec) {
        int colon = spec.indexOf(':');

        if (colon < 1) {
            return null;
        }

        for (int i = 0; i < colon; i++) {
            char c = spec.charAt(i);
            if (!isValidSchemeChar(i, c)) {
                return null;
            }
        }

        return spec.substring(0, colon).toLowerCase(Locale.US);
    }
795529
public byte[] build(BuilderMode builderMode) {
        try {
            final Mac digest = Mac.getInstance(Validator.notNull(algorithm, "algorithm not null"));
            SecretKeySpec secretKey = new SecretKeySpec(apiSecret, algorithm);
            digest.init(secretKey);
            switch (builderMode) {
            case FULL:
                updateFullBuildDigest(digest);
                break;
            case ONLY_HEADER:
                updateOnlyHeaderBuildDigest(digest);
                break;
            default:
                System.err.println(String.format("不支持的参数类型: {}", builderMode));
                return null;
            }
            final byte[] signatureBytes = digest.doFinal();
            digest.reset();
            return signatureBytes;
        } catch (Throwable e) {
            System.err.println(e.getMessage());
            return null;
        }
    }
1172266
public byte[] getMIC(byte [] inBuf,
                         int off,
                         int len,
                         MessageProp prop)
        throws GSSException {
        throw new GSSException(GSSException.UNAVAILABLE);
/*TODO

        checkContext();

        logger.debug("enter getMic");

        if (prop != null && (prop.getQOP() != 0 || prop.getPrivacy())) {
            throw new GSSException(GSSException.BAD_QOP);
        }

        SSLCipherState st = this.conn.getWriteCipherState();
        SSLCipherSuite cs = st.getCipherSuite();
        long sequence = this.conn.getWriteSequence();

        byte [] mic = new byte[GSI_MESSAGE_DIGEST_PADDING + cs.getDigestOutputLength()];

        System.arraycopy(Util.toBytes(sequence), 0, mic, 0, GSI_SEQUENCE_SIZE);
        System.arraycopy(Util.toBytes(len, 4), 0, mic, GSI_SEQUENCE_SIZE, 4);

        this.conn.incrementWriteSequence();

        int pad_ct = (cs.getDigestOutputLength()==16) ? 48 : 40;

        try {
            MessageDigest md =
                MessageDigest.getInstance(cs.getDigestAlg());

            md.update(st.getMacKey());
            for(int i=0;i<pad_ct;i++) {
                md.update(SSLHandshake.pad_1);
            }
            md.update(mic, 0, GSI_MESSAGE_DIGEST_PADDING);
            md.update(inBuf, off, len);

            byte[] digest = md.digest();

            System.arraycopy(digest, 0, mic, GSI_MESSAGE_DIGEST_PADDING, digest.length);
        } catch (NoSuchAlgorithmException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        }

        if (prop != null) {
            prop.setPrivacy(false);
            prop.setQOP(0);
        }

        logger.debug("exit getMic");
        return mic;
*/
    }
503429
public static Cipher createAesCipher(Key key, int mode) throws Exception
    {
        // Use password key as seed for IV (must be 16 bytes)
        MessageDigest d = getMD5Digest();
        d.update(key.getEncoded());
        byte[] iv = d.digest();

        AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");        // CBC faster than CFB8/NoPadding (but file length changes)
        cipher.init(mode, key, paramSpec);
        return cipher;
    }
1069965
def spec(name, type = nil, mode = nil, &block)
      return specs(name, type) unless block_given?
      fail 'A type argument is required when defining a spec!' unless type
      _specs
      name = name_audit(name)
      fail 'Specification names must be of SPEC_TYPES Symbol or String and cannot start with a number' if name.nil?
      fail "Spec type must be one of #{SPEC_TYPES.join(', ')}" unless SPEC_TYPES.include? type
      type = type
      mode = get_mode if mode.nil?
      owner_name = ''
      if self.respond_to?(:name) && send(:name)
        owner_name = self.name.to_s.downcase.to_sym
      elsif self == Origen.top_level
        owner_name = self.class.to_s.split('::').last.downcase.to_sym
      else
        owner_name = self.class.to_s.split('::').last.downcase.to_sym
      end
      spec_placeholder = Spec
                         .new(name, type, mode, owner_name, &block)
      # Check if the spec already exists
      if has_spec?(name, type: type, mode: mode, sub_type: spec_placeholder.sub_type, creating_spec: true)
        # Spec already exists.  Go ahead flag error and drop processing.
        # This is a fatal error.
        fail "Spec already exists for name: #{name}, type: #{type}, mode: #{mode} for object #{self}"
      end
      @_specs[name][mode][type][spec_placeholder.sub_type] = spec_placeholder
    end