javax.crypto.Cipher.getIV()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(10.5k)|赞(0)|评价(0)|浏览(337)

本文整理了Java中javax.crypto.Cipher.getIV()方法的一些代码示例,展示了Cipher.getIV()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Cipher.getIV()方法的具体详情如下:
包路径:javax.crypto.Cipher
类名称:Cipher
方法名:getIV

Cipher.getIV介绍

[英]Returns the initialization vector for this cipher instance.
[中]返回此密码实例的初始化向量。

代码示例

代码示例来源:origin: aws/aws-sdk-java

/**
 * Returns the initialization vector (IV) in a new buffer.
 *
 * <p>This is useful in the case where a random IV was created,
 * or in the context of password-based encryption or
 * decryption, where the IV is derived from a user-supplied password.
 *
 * @return the initialization vector in a new buffer, or null if the
 * underlying algorithm does not use an IV, or if the IV has not yet
 * been set.
 */
final byte[] getIV() {
  return cipher.getIV();
}

代码示例来源:origin: apache/incubator-gobblin

private void initCipher() {
 if (origStream == null) {
  throw new IllegalStateException("Can't initCipher stream before encodeOutputStream() has been called!");
 }
 try {
  cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  cipher.init(Cipher.ENCRYPT_MODE, secretKey.getSecretKey());
  byte[] iv = cipher.getIV();
  base64Iv = DatatypeConverter.printBase64Binary(iv);
  this.headerWritten = false;
 } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
  throw new IllegalStateException("Error creating AES algorithm? Should always exist in JRE");
 } catch (InvalidKeyException e) {
  throw new IllegalStateException("Key " + secretKey.getKeyId() + " is illegal - please check credential store");
 }
}

代码示例来源:origin: aws/aws-sdk-java

/**
 * Recreates a new instance of CipherLite from the current one.
 */
CipherLite recreate() {
  return scheme.createCipherLite(secreteKey, cipher.getIV(),
      this.cipherMode, cipher.getProvider(), true);
}

代码示例来源:origin: aws/aws-sdk-java

/**
 * Returns the inverse of the current {@link CipherLite}.
 */
CipherLite createInverse() throws InvalidKeyException,
    NoSuchAlgorithmException, NoSuchProviderException,
    NoSuchPaddingException, InvalidAlgorithmParameterException {
  int inversedMode;
  if (cipherMode == Cipher.DECRYPT_MODE)
    inversedMode = Cipher.ENCRYPT_MODE;
  else if (cipherMode == Cipher.ENCRYPT_MODE)
    inversedMode = Cipher.DECRYPT_MODE;
  else
    throw new UnsupportedOperationException();
  return scheme.createCipherLite(secreteKey, cipher.getIV(),
      inversedMode, cipher.getProvider(), true);
}

代码示例来源:origin: signalapp/Signal-Server

private byte[] getCiphertext(byte[] plaintext, SecretKeySpec cipherKey, SecretKeySpec macKey)
  throws CryptoEncodingException
{
 try {
  Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  cipher.init(Cipher.ENCRYPT_MODE, cipherKey);
  Mac hmac = Mac.getInstance("HmacSHA256");
  hmac.init(macKey);
  hmac.update(VERSION);
  byte[] ivBytes = cipher.getIV();
  hmac.update(ivBytes);
  byte[] ciphertext   = cipher.doFinal(plaintext);
  byte[] mac          = hmac.doFinal(ciphertext);
  byte[] truncatedMac = new byte[MAC_SIZE];
  System.arraycopy(mac, 0, truncatedMac, 0, truncatedMac.length);
  return Util.combine(VERSION, ivBytes, ciphertext, truncatedMac);
 } catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
  throw new AssertionError(e);
 } catch (InvalidKeyException e) {
  logger.warn("Invalid Key", e);
  throw new CryptoEncodingException("Invalid key!");
 }
}

代码示例来源:origin: aws/aws-sdk-java

/**
 * Returns an auxiliary {@link CipherLite} for partial plaintext
 * re-encryption (or re-decryption) purposes.
 *
 * @param startingBytePos
 *            the starting byte position of the plaintext. Must be a
 *            multiple of the cipher block size.
 */
CipherLite createAuxiliary(long startingBytePos)
    throws InvalidKeyException, NoSuchAlgorithmException,
    NoSuchProviderException, NoSuchPaddingException,
    InvalidAlgorithmParameterException {
  return scheme.createAuxillaryCipher(secreteKey, cipher.getIV(),
      cipherMode, cipher.getProvider(), startingBytePos);
}

代码示例来源:origin: wildfly/wildfly

private void saveSecretKey(String ksAlias, ObjectOutputStream oos, KeyStore.SecretKeyEntry entry) throws IOException, GeneralSecurityException {
  ByteArrayOutputStream entryData = new ByteArrayOutputStream(1024);
  ObjectOutputStream entryOos = new ObjectOutputStream(entryData);
  entryOos.writeUTF(ksAlias);
  writeBytes(entry.getSecretKey().getEncoded(), entryOos);
  entryOos.flush();
  encrypt.init(Cipher.ENCRYPT_MODE, storageSecretKey, (AlgorithmParameterSpec) null); // ELY-1308: third param need to workaround BouncyCastle bug
  int blockSize = encrypt.getBlockSize();
  if (blockSize == 0) throw log.algorithmNotBlockBased(encrypt.getAlgorithm());
  Assert.checkMaximumParameter("cipher block size", 256, blockSize);
  byte[] padded = pkcs7Pad(entryData.toByteArray(), blockSize);
  byte[] encrypted = encrypt.doFinal(padded);
  byte[] iv = encrypt.getIV();
  if (iv == null) throw log.algorithmNotIV(encrypt.getAlgorithm());
  oos.writeInt(SECRET_KEY_ENTRY_TYPE);
  writeBytes(encrypted, oos);
  writeBytes(iv, oos);
}

代码示例来源:origin: apache/nifi

@Override
  public void process(final InputStream in, final OutputStream out) throws IOException {
    // Initialize cipher provider
    KeyedCipherProvider cipherProvider = (KeyedCipherProvider) CipherProviderFactory.getCipherProvider(KeyDerivationFunction.NONE);
    // Generate cipher
    try {
      Cipher cipher = cipherProvider.getCipher(encryptionMethod, key, iv, true);
      cipherProvider.writeIV(cipher.getIV(), out);
      CipherUtility.processStreams(cipher, in, out);
    } catch (Exception e) {
      throw new ProcessException(e);
    }
  }
}

代码示例来源:origin: apache/nifi

logger.debug("Encrypting provenance record " + recordId + " with key ID " + keyId);
Cipher cipher = initCipher(EncryptionMethod.AES_GCM, Cipher.ENCRYPT_MODE, keyProvider.getKey(keyId), ivBytes);
ivBytes = cipher.getIV();

代码示例来源:origin: aws-amplify/aws-sdk-android

/**
 * Returns the initialization vector (IV) in a new buffer.
 * <p>
 * This is useful in the case where a random IV was created, or in the
 * context of password-based encryption or decryption, where the IV is
 * derived from a user-supplied password.
 *
 * @return the initialization vector in a new buffer, or null if the
 *         underlying algorithm does not use an IV, or if the IV has not yet
 *         been set.
 */
final byte[] getIV() {
  return cipher.getIV();
}

代码示例来源:origin: apache/nifi

@Override
  public void process(final InputStream in, final OutputStream out) throws IOException {
    // Initialize cipher provider
    PBECipherProvider cipherProvider = (PBECipherProvider) CipherProviderFactory.getCipherProvider(kdf);
    // Generate salt
    byte[] salt;
    // NiFi legacy code determined the salt length based on the cipher block size
    if (cipherProvider instanceof org.apache.nifi.security.util.crypto.NiFiLegacyCipherProvider) {
      salt = ((org.apache.nifi.security.util.crypto.NiFiLegacyCipherProvider) cipherProvider).generateSalt(encryptionMethod);
    } else {
      salt = cipherProvider.generateSalt();
    }
    // Write to output stream
    cipherProvider.writeSalt(salt, out);
    // Determine necessary key length
    int keyLength = CipherUtility.parseKeyLengthFromAlgorithm(encryptionMethod.getAlgorithm());
    // Generate cipher
    try {
      Cipher cipher = cipherProvider.getCipher(encryptionMethod, new String(password.getPassword()), salt, keyLength, true);
      // Write IV if necessary
      if (cipherProvider instanceof RandomIVPBECipherProvider) {
        ((RandomIVPBECipherProvider) cipherProvider).writeIV(cipher.getIV(), out);
      }
      CipherUtility.processStreams(cipher, in, out);
    } catch (Exception e) {
      throw new ProcessException(e);
    }
  }
}

代码示例来源:origin: aws-amplify/aws-sdk-android

/**
 * Creates a new Cipher instance based on the crypto parameters specified in
 * the constructor. Each Cipher instance is identical to any other Cipher
 * produced by this CipherFactory.
 *
 * @return A new Cipher instance, identical to each Cipher produced by this
 *         factory instance.
 */
public Cipher createCipher() {
  Cipher cipher = EncryptionUtils.createSymmetricCipher(symmetricKey, cipherMode,
      cryptoProvider, initVectorBytes);
  // If we weren't given an IV to use, make sure we store the one the
  // first Cipher
  // used so we can use it for all future Ciphers created by this
  // instance.
  if (initVectorBytes == null)
    initVectorBytes = cipher.getIV();
  return cipher;
}

代码示例来源:origin: aws-amplify/aws-sdk-android

/**
 * Recreates a new instance of CipherLite from the current one.
 */
CipherLite recreate() {
  return scheme.createCipherLite(secreteKey, cipher.getIV(),
      this.cipherMode, cipher.getProvider());
}

代码示例来源:origin: stackoverflow.com

final byte[] iv = encryptCipher.getIV();
final byte[] encrypted = encryptCipher.doFinal(data);

代码示例来源:origin: aws-amplify/aws-sdk-android

/**
 * Returns the inverse of the current {@link CipherLite}.
 */
CipherLite createInverse() throws InvalidKeyException,
    NoSuchAlgorithmException, NoSuchProviderException,
    NoSuchPaddingException, InvalidAlgorithmParameterException {
  int inversedMode;
  if (cipherMode == Cipher.DECRYPT_MODE)
    inversedMode = Cipher.ENCRYPT_MODE;
  else if (cipherMode == Cipher.ENCRYPT_MODE)
    inversedMode = Cipher.DECRYPT_MODE;
  else
    throw new UnsupportedOperationException();
  return scheme.createCipherLite(secreteKey, cipher.getIV(),
      inversedMode, cipher.getProvider());
}

代码示例来源:origin: aws-amplify/aws-sdk-android

/**
 * Returns an auxiliary {@link CipherLite} for partial plaintext
 * re-encryption (or re-decryption) purposes.
 *
 * @param startingBytePos the starting byte position of the plaintext. Must
 *            be a multiple of the cipher block size.
 */
CipherLite createAuxiliary(long startingBytePos)
    throws InvalidKeyException, NoSuchAlgorithmException,
    NoSuchProviderException, NoSuchPaddingException,
    InvalidAlgorithmParameterException {
  return scheme.createAuxillaryCipher(secreteKey, cipher.getIV(),
      cipherMode, cipher.getProvider(), startingBytePos);
}

代码示例来源:origin: aws-amplify/aws-sdk-android

/**
 * Returns a JSONObject representation of the instruction object.
 */
private static Map<String, String> convertInstructionToJSONObject(
    EncryptionInstruction instruction) {
  Map<String, String> instructionJSON = new HashMap<String, String>();
  String materialsDescription = JsonUtils.mapToString(instruction.getMaterialsDescription());
  instructionJSON.put(Headers.MATERIALS_DESCRIPTION, materialsDescription);
  instructionJSON.put(Headers.CRYPTO_KEY,
      Base64.encodeAsString(instruction.getEncryptedSymmetricKey()));
  byte[] iv = instruction.getSymmetricCipher().getIV();
  instructionJSON.put(Headers.CRYPTO_IV, Base64.encodeAsString(iv));
  return instructionJSON;
}

代码示例来源:origin: org.nuxeo.ecm.core/nuxeo-core-api

byte[] iv = cipher.getIV();
data.writeInt(iv.length);
data.write(iv);

代码示例来源:origin: aws-amplify/aws-sdk-android

private static void updateMetadata(ObjectMetadata metadata, byte[] keyBytesToStoreInMetadata,
    Cipher symmetricCipher, Map<String, String> materialsDescription) {
  // If we generated a symmetric key to encrypt the data, store it in the
  // object metadata.
  if (keyBytesToStoreInMetadata != null) {
    metadata.addUserMetadata(Headers.CRYPTO_KEY,
        Base64.encodeAsString(keyBytesToStoreInMetadata));
  }
  // Put the cipher initialization vector (IV) into the object metadata
  metadata.addUserMetadata(Headers.CRYPTO_IV,
      Base64.encodeAsString(symmetricCipher.getIV()));
  // Put the materials description into the object metadata as JSON
  String description = JsonUtils.mapToString(materialsDescription);
  metadata.addUserMetadata(Headers.MATERIALS_DESCRIPTION, description);
}

代码示例来源:origin: ggrandes/bouncer

public byte[] getIV() throws IOException, GeneralSecurityException {
  final Cipher enc = getCoder(false);
  if (enc != null)
    return enc.getIV();
  return null;
}

相关文章