Java Code Examples for javax.crypto.spec.IvParameterSpec#getIV()

The following examples show how to use javax.crypto.spec.IvParameterSpec#getIV() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SSLTrafficKeyDerivation.java    From openjsse with GNU General Public License v2.0 6 votes vote down vote up
SecretKey getTrafficKey(String algorithm) {
    switch (algorithm) {
        case "clientMacKey":
            return keyMaterialSpec.getClientMacKey();
        case "serverMacKey":
            return keyMaterialSpec.getServerMacKey();
        case "clientWriteKey":
            return keyMaterialSpec.getClientCipherKey();
        case "serverWriteKey":
            return keyMaterialSpec.getServerCipherKey();
        case "clientWriteIv":
            IvParameterSpec cliIvSpec = keyMaterialSpec.getClientIv();
            return  (cliIvSpec == null) ? null :
                    new SecretKeySpec(cliIvSpec.getIV(), "TlsIv");
        case "serverWriteIv":
            IvParameterSpec srvIvSpec = keyMaterialSpec.getServerIv();
            return  (srvIvSpec == null) ? null :
                    new SecretKeySpec(srvIvSpec.getIV(), "TlsIv");
    }

    return null;
}
 
Example 2
Source File: ChaCha20Poly1305Parameters.java    From openjsse with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initialize the ChaCha20Poly1305Parameters using an IvParameterSpec.
 *
 * @param paramSpec the {@code IvParameterSpec} used to configure
 *      this object.
 *
 * @throws InvalidParameterSpecException if an object of a type other
 *      than {@code IvParameterSpec} is used.
 */
@Override
protected void engineInit(AlgorithmParameterSpec paramSpec)
    throws InvalidParameterSpecException {

    if (!(paramSpec instanceof IvParameterSpec)) {
        throw new InvalidParameterSpecException
            ("Inappropriate parameter specification");
    }
    IvParameterSpec ivps = (IvParameterSpec)paramSpec;

    // Obtain the nonce
    nonce = ivps.getIV();
    if (nonce.length != 12) {
        throw new InvalidParameterSpecException("ChaCha20-Poly1305 nonce" +
                " must be 12 bytes in length");
    }
}
 
Example 3
Source File: Token.java    From fernet-java8 with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Initialise a new Token from raw components. No validation of the signature is performed. However, the other
 * fields are validated to ensure they conform to the Fernet specification.</p>
 *
 * <p>Warning: Subsequent modifications to the input arrays will write through to this object.</p>
 *
 * @param version
 *            The version of the Fernet token specification. Currently, only 0x80 is supported.
 * @param timestamp
 *            the time the token was generated
 * @param initializationVector
 *            the randomly-generated bytes used to initialise the encryption cipher
 * @param cipherText
 *            the encrypted the encrypted payload
 * @param hmac
 *            the signature of the token
 */
@SuppressWarnings({"PMD.ArrayIsStoredDirectly", "PMD.CyclomaticComplexity"})
protected Token(final byte version, final Instant timestamp, final IvParameterSpec initializationVector,
        final byte[] cipherText, final byte[] hmac) {
    if (version != supportedVersion) {
        throw new IllegalTokenException("Unsupported version: " + version);
    }
    if (timestamp == null) {
        throw new IllegalTokenException("timestamp cannot be null");
    }
    if (initializationVector == null || initializationVector.getIV().length != initializationVectorBytes) {
        throw new IllegalTokenException("Initialization Vector must be 128 bits");
    }
    if (cipherText == null || cipherText.length % cipherTextBlockSize != 0) {
        throw new IllegalTokenException("Ciphertext must be a multiple of 128 bits");
    }
    if (hmac == null || hmac.length != signatureBytes) {
        throw new IllegalTokenException("hmac must be 256 bits");
    }
    this.version = version;
    this.timestamp = timestamp;
    this.initializationVector = initializationVector;
    this.cipherText = cipherText;
    this.hmac = hmac;
}
 
Example 4
Source File: SSLTrafficKeyDerivation.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
SecretKey getTrafficKey(String algorithm) {
    switch (algorithm) {
        case "clientMacKey":
            return keyMaterialSpec.getClientMacKey();
        case "serverMacKey":
            return keyMaterialSpec.getServerMacKey();
        case "clientWriteKey":
            return keyMaterialSpec.getClientCipherKey();
        case "serverWriteKey":
            return keyMaterialSpec.getServerCipherKey();
        case "clientWriteIv":
            IvParameterSpec cliIvSpec = keyMaterialSpec.getClientIv();
            return  (cliIvSpec == null) ? null :
                    new SecretKeySpec(cliIvSpec.getIV(), "TlsIv");
        case "serverWriteIv":
            IvParameterSpec srvIvSpec = keyMaterialSpec.getServerIv();
            return  (srvIvSpec == null) ? null :
                    new SecretKeySpec(srvIvSpec.getIV(), "TlsIv");
    }

    return null;
}
 
Example 5
Source File: ChaCha20Poly1305Parameters.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the ChaCha20Poly1305Parameters using an IvParameterSpec.
 *
 * @param paramSpec the {@code IvParameterSpec} used to configure
 *      this object.
 *
 * @throws InvalidParameterSpecException if an object of a type other
 *      than {@code IvParameterSpec} is used.
 */
@Override
protected void engineInit(AlgorithmParameterSpec paramSpec)
    throws InvalidParameterSpecException {

    if (!(paramSpec instanceof IvParameterSpec)) {
        throw new InvalidParameterSpecException
            ("Inappropriate parameter specification");
    }
    IvParameterSpec ivps = (IvParameterSpec)paramSpec;

    // Obtain the nonce
    nonce = ivps.getIV();
    if (nonce.length != 12) {
        throw new InvalidParameterSpecException("ChaCha20-Poly1305 nonce" +
                " must be 12 bytes in length");
    }
}
 
Example 6
Source File: ValueEncryptionUtilities.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * This salts and encrypts a value and returns a base64 encoded version of the encrypted value.
 * @param value The value to be encrypted.
 * @param length The number on bytes to expand out to the source value to. This is so that all encryption
 *               operations generate the same length output. Watch out for multibyte characters as these will mean
 *               that your length must be more than the number of character in the string. If 0 then no padding is
 *               done.
 * @return A salted base64 encrypted version of the value.
 * @throws RuntimeException If encryption fails for any reason.
 */
public String encrypt(String value, int length) {
	try {
		byte[] salt = getSalt();
		SecretKey secret = getSecret(key, salt, getKeyLength());
		Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
		cipher.init(Cipher.ENCRYPT_MODE, secret);
		AlgorithmParameters params = cipher.getParameters();
		//get IV from cipher parameters
		IvParameterSpec parameterSpec = params.getParameterSpec(IvParameterSpec.class);
		// AES always has 128bit IV
		byte[] iv = parameterSpec.getIV();
		byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
		if (length != 0 && bytes.length > length) {
			throw new IllegalArgumentException("Can't encode as it's longer than our fixed length.");
		}
		int finalLength = (length == 0)?bytes.length: length;
		byte[] source = new byte[finalLength];
		System.arraycopy(bytes, 0, source, 0, bytes.length);
		// Fill the remainded of the array with illegal UTF-8 characters.
		Arrays.fill(source, bytes.length, source.length, (byte) UTF_8_ILLEGAL);
		byte[] ciphertext = cipher.doFinal(source);

		//create final array (in bytes) : IV + SALT + TEXT
		byte[] finalCiphertext = new byte[ciphertext.length+2*16];
		System.arraycopy(iv, 0, finalCiphertext, 0, 16);
		System.arraycopy(salt, 0, finalCiphertext, 16, 16);
		System.arraycopy(ciphertext, 0, finalCiphertext, 32, ciphertext.length);
		//encode all bytes in a Base64 string
		return encoder.encodeToString(finalCiphertext);
	} catch(Exception e){
		// We must not log out the value here so that the plaintext can't accidentally end up in the logs
		log.error("Error while encrypting.", e);
		return null;
	}
}
 
Example 7
Source File: IvParameterSpecTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testGetIV() {
    byte[] iv = new byte[] {1, 2, 3, 4, 5};
    IvParameterSpec ivps = new IvParameterSpec(iv);
    iv = ivps.getIV();
    iv[0] ++;
    assertFalse("The change of returned array should not cause "
                + "the change of internal array", iv[0] == ivps.getIV()[0]);
}
 
Example 8
Source File: ValueEncryptionUtilities.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * This salts and encrypts a value and returns a base64 encoded version of the encrypted value.
 * @param value The value to be encrypted.
 * @param length The number on bytes to expand out to the source value to. This is so that all encryption
 *               operations generate the same length output. Watch out for multibyte characters as these will mean
 *               that your length must be more than the number of character in the string. If 0 then no padding is
 *               done.
 * @return A salted base64 encrypted version of the value.
 * @throws RuntimeException If encryption fails for any reason.
 */
public String encrypt(String value, int length) {
	try {
		byte[] salt = getSalt();
		SecretKey secret = getSecret(key, salt, getKeyLength());
		Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
		cipher.init(Cipher.ENCRYPT_MODE, secret);
		AlgorithmParameters params = cipher.getParameters();
		//get IV from cipher parameters
		IvParameterSpec parameterSpec = params.getParameterSpec(IvParameterSpec.class);
		// AES always has 128bit IV
		byte[] iv = parameterSpec.getIV();
		byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
		if (length != 0 && bytes.length > length) {
			throw new IllegalArgumentException("Can't encode as it's longer than our fixed length.");
		}
		int finalLength = (length == 0)?bytes.length: length;
		byte[] source = new byte[finalLength];
		System.arraycopy(bytes, 0, source, 0, bytes.length);
		// Fill the remainded of the array with illegal UTF-8 characters.
		Arrays.fill(source, bytes.length, source.length, (byte) UTF_8_ILLEGAL);
		byte[] ciphertext = cipher.doFinal(source);

		//create final array (in bytes) : IV + SALT + TEXT
		byte[] finalCiphertext = new byte[ciphertext.length+2*16];
		System.arraycopy(iv, 0, finalCiphertext, 0, 16);
		System.arraycopy(salt, 0, finalCiphertext, 16, 16);
		System.arraycopy(ciphertext, 0, finalCiphertext, 32, ciphertext.length);
		//encode all bytes in a Base64 string
		return encoder.encodeToString(finalCiphertext);
	} catch(Exception e){
		// We must not log out the value here so that the plaintext can't accidentally end up in the logs
		log.error("Error while encrypting.", e);
		return null;
	}
}
 
Example 9
Source File: ChaCha20Cipher.java    From openjsse with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Initialize the engine using a key and secure random implementation.
 *
 * @param opmode the type of operation to do.  This value must be either
 *      {@code Cipher.ENCRYPT_MODE} or {@code Cipher.DECRYPT_MODE}
 * @param key a 256-bit key suitable for ChaCha20
 * @param params a {@code ChaCha20ParameterSpec} that will provide
 *      the nonce and initial block counter value.
 * @param random a {@code SecureRandom} implementation, this parameter
 *      is not used in this form of the initializer.
 *
 * @throws UnsupportedOperationException if the mode of operation
 *      is {@code Cipher.WRAP_MODE} or {@code Cipher.UNWRAP_MODE}
 *      (currently unsupported).
 * @throws InvalidKeyException if the key is of the wrong type or is
 *      not 256-bits in length.  This will also be thrown if the opmode
 *      parameter is not {@code Cipher.ENCRYPT_MODE} or
 *      {@code Cipher.DECRYPT_MODE} (excepting the UOE case above).
 * @throws InvalidAlgorithmParameterException if {@code params} is
 *      not a {@code ChaCha20ParameterSpec}
 * @throws NullPointerException if {@code params} is {@code null}
 */
@Override
protected void engineInit(int opmode, Key key,
        AlgorithmParameterSpec params, SecureRandom random)
        throws InvalidKeyException, InvalidAlgorithmParameterException {

    // If AlgorithmParameterSpec is null, then treat this like an init
    // of the form (int, Key, SecureRandom)
    if (params == null) {
        engineInit(opmode, key, random);
        return;
    }

    // We will ignore the secure random implementation and use the nonce
    // from the AlgorithmParameterSpec instead.
    byte[] newNonce = null;
    switch (mode) {
        case MODE_NONE:
            if (!(params instanceof ChaCha20ParameterSpec)) {
                throw new InvalidAlgorithmParameterException(
                    "ChaCha20 algorithm requires ChaCha20ParameterSpec");
            }
            ChaCha20ParameterSpec chaParams = (ChaCha20ParameterSpec)params;
            newNonce = chaParams.getNonce();
            counter = ((long)chaParams.getCounter()) & 0x00000000FFFFFFFFL;
            break;
        case MODE_AEAD:
            if (!(params instanceof IvParameterSpec)) {
                throw new InvalidAlgorithmParameterException(
                    "ChaCha20-Poly1305 requires IvParameterSpec");
            }
            IvParameterSpec ivParams = (IvParameterSpec)params;
            newNonce = ivParams.getIV();
            if (newNonce.length != 12) {
                throw new InvalidAlgorithmParameterException(
                    "ChaCha20-Poly1305 nonce must be 12 bytes in length");
            }
            break;
        default:
            // Should never happen
            throw new RuntimeException("ChaCha20 in unsupported mode");
    }
    init(opmode, key, newNonce);
}
 
Example 10
Source File: SecurityUtils.java    From RISE-V2G with MIT License 4 votes vote down vote up
/**
 * Applies the algorithm AES-CBC-128 according to NIST Special Publication 800-38A.
 * The initialization vector IV shall be randomly generated before encryption and shall have a 
 * length of 128 bit and never be reused.
 * The IV shall be transmitted in the 16 most significant bytes of the 
 * ContractSignatureEncryptedPrivateKey field.
 * 
 * @param sessionKey The symmetric session key with which the private key will be encrypted
 * @param contractCertPrivateKey The private key which is to be encrypted
 * @return The encrypted private key of the contract certificate given as a byte array
 */
private static byte[] encryptPrivateKey(SecretKey sessionKey, ECPrivateKey contractCertPrivateKey) {
	try {
		/*
		 * Padding of the plain text (private key) is not required as its length (256 bit) is a 
		 * multiple of the block size (128 bit) of the used encryption algorithm (AES)
		 */
		Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
		IvParameterSpec ivParamSpec = new IvParameterSpec(generateRandomNumber(16));
		cipher.init(Cipher.ENCRYPT_MODE, sessionKey, ivParamSpec);
		
		/*
		 * Not the complete ECPrivateKey container, but the private value s represents the 256 bit 
		 * private key which must be encoded. 
		 * The private key is stored as an ASN.1 integer which may need to have zero padding 
		 * in the most significant bits removed (if 33 bytes)
		 */
		byte[] encryptedKey;
		if (contractCertPrivateKey.getS().toByteArray().length == 33) {
			byte[] temp = new byte[32];
			System.arraycopy(contractCertPrivateKey.getS().toByteArray(), 1, temp, 0, contractCertPrivateKey.getS().toByteArray().length-1);
			encryptedKey = cipher.doFinal(temp);
		} else {
			encryptedKey = cipher.doFinal(contractCertPrivateKey.getS().toByteArray());
		}
		
		/*
		 * The IV must be transmitted in the 16 most significant bytes of the
		 * ContractSignatureEncryptedPrivateKey
		 */
		byte[] encryptedKeyWithIV = new byte[ivParamSpec.getIV().length + encryptedKey.length];
		System.arraycopy(ivParamSpec.getIV(), 0, encryptedKeyWithIV, 0, ivParamSpec.getIV().length);
		System.arraycopy(encryptedKey, 0, encryptedKeyWithIV, ivParamSpec.getIV().length, encryptedKey.length);
		getLogger().debug("Encrypted private key: " + ByteUtils.toHexString(encryptedKeyWithIV));
		
		return encryptedKeyWithIV;
	} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | 
			 InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred while trying to encrypt private key." +
						  "\nSession key (" + sessionKey.getEncoded().length + " bytes): " +
						  ByteUtils.toHexString(sessionKey.getEncoded()) +
						  "\nContract certificate private key (" + contractCertPrivateKey.getS().toByteArray().length + " bytes): " +
						  ByteUtils.toHexString(contractCertPrivateKey.getS().toByteArray()), e);
	} 
	
	return null;
}
 
Example 11
Source File: ChaCha20Cipher.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize the engine using a key and secure random implementation.
 *
 * @param opmode the type of operation to do.  This value must be either
 *      {@code Cipher.ENCRYPT_MODE} or {@code Cipher.DECRYPT_MODE}
 * @param key a 256-bit key suitable for ChaCha20
 * @param params a {@code ChaCha20ParameterSpec} that will provide
 *      the nonce and initial block counter value.
 * @param random a {@code SecureRandom} implementation, this parameter
 *      is not used in this form of the initializer.
 *
 * @throws UnsupportedOperationException if the mode of operation
 *      is {@code Cipher.WRAP_MODE} or {@code Cipher.UNWRAP_MODE}
 *      (currently unsupported).
 * @throws InvalidKeyException if the key is of the wrong type or is
 *      not 256-bits in length.  This will also be thrown if the opmode
 *      parameter is not {@code Cipher.ENCRYPT_MODE} or
 *      {@code Cipher.DECRYPT_MODE} (excepting the UOE case above).
 * @throws InvalidAlgorithmParameterException if {@code params} is
 *      not a {@code ChaCha20ParameterSpec}
 * @throws NullPointerException if {@code params} is {@code null}
 */
@Override
protected void engineInit(int opmode, Key key,
        AlgorithmParameterSpec params, SecureRandom random)
        throws InvalidKeyException, InvalidAlgorithmParameterException {

    // If AlgorithmParameterSpec is null, then treat this like an init
    // of the form (int, Key, SecureRandom)
    if (params == null) {
        engineInit(opmode, key, random);
        return;
    }

    // We will ignore the secure random implementation and use the nonce
    // from the AlgorithmParameterSpec instead.
    byte[] newNonce = null;
    switch (mode) {
        case MODE_NONE:
            if (!(params instanceof ChaCha20ParameterSpec)) {
                throw new InvalidAlgorithmParameterException(
                    "ChaCha20 algorithm requires ChaCha20ParameterSpec");
            }
            ChaCha20ParameterSpec chaParams = (ChaCha20ParameterSpec)params;
            newNonce = chaParams.getNonce();
            counter = ((long)chaParams.getCounter()) & 0x00000000FFFFFFFFL;
            break;
        case MODE_AEAD:
            if (!(params instanceof IvParameterSpec)) {
                throw new InvalidAlgorithmParameterException(
                    "ChaCha20-Poly1305 requires IvParameterSpec");
            }
            IvParameterSpec ivParams = (IvParameterSpec)params;
            newNonce = ivParams.getIV();
            if (newNonce.length != 12) {
                throw new InvalidAlgorithmParameterException(
                    "ChaCha20-Poly1305 nonce must be 12 bytes in length");
            }
            break;
        default:
            // Should never happen
            throw new RuntimeException("ChaCha20 in unsupported mode");
    }
    init(opmode, key, newNonce);
}
 
Example 12
Source File: BaseWrapCipher.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
protected void engineInit(
    int                     opmode,
    Key                     key,
    AlgorithmParameterSpec  params,
    SecureRandom            random)
throws InvalidKeyException, InvalidAlgorithmParameterException
{
    CipherParameters        param;

    if (key instanceof BCPBEKey)
    {
        BCPBEKey k = (BCPBEKey)key;

        if (params instanceof PBEParameterSpec)
        {
            param = PBE.Util.makePBEParameters(k, params, wrapEngine.getAlgorithmName());
        }
        else if (k.getParam() != null)
        {
            param = k.getParam();
        }
        else
        {
            throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set.");
        }
    }
    else
    {
        param = new KeyParameter(key.getEncoded());
    }

    if (params instanceof IvParameterSpec)
    {
        IvParameterSpec iv = (IvParameterSpec) params;
        param = new ParametersWithIV(param, iv.getIV());
    }

    if (param instanceof KeyParameter && ivSize != 0)
    {
        iv = new byte[ivSize];
        random.nextBytes(iv);
        param = new ParametersWithIV(param, iv);
    }

    if (random != null)
    {
        param = new ParametersWithRandom(param, random);
    }

    switch (opmode)
    {
    case Cipher.WRAP_MODE:
        wrapEngine.init(true, param);
        break;
    case Cipher.UNWRAP_MODE:
        wrapEngine.init(false, param);
        break;
    case Cipher.ENCRYPT_MODE:
    case Cipher.DECRYPT_MODE:
        throw new IllegalArgumentException("engine only valid for wrapping");
    default:
        System.out.println("eeek!");
    }
}
 
Example 13
Source File: BaseWrapCipher.java    From ripple-lib-java with ISC License 4 votes vote down vote up
protected void engineInit(
    int                     opmode,
    Key                     key,
    AlgorithmParameterSpec  params,
    SecureRandom            random)
throws InvalidKeyException, InvalidAlgorithmParameterException
{
    CipherParameters        param;

    if (key instanceof BCPBEKey)
    {
        BCPBEKey k = (BCPBEKey)key;

        if (params instanceof PBEParameterSpec)
        {
            param = PBE.Util.makePBEParameters(k, params, wrapEngine.getAlgorithmName());
        }
        else if (k.getParam() != null)
        {
            param = k.getParam();
        }
        else
        {
            throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set.");
        }
    }
    else
    {
        param = new KeyParameter(key.getEncoded());
    }

    if (params instanceof IvParameterSpec)
    {
        IvParameterSpec iv = (IvParameterSpec) params;
        param = new ParametersWithIV(param, iv.getIV());
    }

    if (param instanceof KeyParameter && ivSize != 0)
    {
        iv = new byte[ivSize];
        random.nextBytes(iv);
        param = new ParametersWithIV(param, iv);
    }

    if (random != null)
    {
        param = new ParametersWithRandom(param, random);
    }

    switch (opmode)
    {
    case Cipher.WRAP_MODE:
        wrapEngine.init(true, param);
        break;
    case Cipher.UNWRAP_MODE:
        wrapEngine.init(false, param);
        break;
    case Cipher.ENCRYPT_MODE:
    case Cipher.DECRYPT_MODE:
        throw new IllegalArgumentException("engine only valid for wrapping");
    default:
        System.out.println("eeek!");
    }
}