java.security.AlgorithmParameters Java Examples

The following examples show how to use java.security.AlgorithmParameters. 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: SameBuffer.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private Cipher createCipher(int mode, AlgorithmParameters params)
        throws Exception {
    Cipher cipher = Cipher.getInstance(transformation, provider);
    if (Cipher.ENCRYPT_MODE == mode) {
        // initiate it with the saved parameters
        if (params != null) {
            cipher.init(Cipher.ENCRYPT_MODE, key, params);
        } else {
            // intiate the cipher and save parameters
            cipher.init(Cipher.ENCRYPT_MODE, key);
        }
    } else if (cipher != null) {
        cipher.init(Cipher.DECRYPT_MODE, key, params);
    } else {
        throw new RuntimeException("Can't create cipher");
    }

    return cipher;
}
 
Example #2
Source File: IESCipher.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
public AlgorithmParameters engineGetParameters()
{
    if (engineParam == null && engineSpec != null)
    {
        try
        {
            engineParam = helper.createAlgorithmParameters("IES");
            engineParam.init(engineSpec);
        }
        catch (Exception e)
        {
            throw new RuntimeException(e.toString());
        }
    }

    return engineParam;
}
 
Example #3
Source File: SupportedEllipticCurvesExtension.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static boolean isAvailableCurve(int curveId) {
    String oid = idToOidMap.get(curveId);
    if (oid != null) {
        AlgorithmParameters params = null;
        try {
            params = JsseJce.getAlgorithmParameters("EC");
            params.init(new ECGenParameterSpec(oid));
        } catch (Exception e) {
            return false;
        }

        // cache the parameters
        idToParams.put(curveId, params);

        return true;
    }

    return false;
}
 
Example #4
Source File: AbstractEncryptor.java    From alfresco-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public InputStream decrypt(String keyAlias, AlgorithmParameters params, InputStream input)
{
    Cipher cipher = getCipher(keyAlias, params, Cipher.DECRYPT_MODE);
    if (cipher == null)
    {
        return input;
    }

    try
    {
        return new CipherInputStream(input, cipher);
    }
    catch (Throwable e)
    {
        throw new AlfrescoRuntimeException("Decryption failed for key alias: " + keyAlias, e);
    }
}
 
Example #5
Source File: SameBuffer.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private Cipher createCipher(int mode, AlgorithmParameters params)
        throws Exception {
    Cipher cipher = Cipher.getInstance(transformation, provider);
    if (Cipher.ENCRYPT_MODE == mode) {
        // initiate it with the saved parameters
        if (params != null) {
            cipher.init(Cipher.ENCRYPT_MODE, key, params);
        } else {
            // intiate the cipher and save parameters
            cipher.init(Cipher.ENCRYPT_MODE, key);
        }
    } else if (cipher != null) {
        cipher.init(Cipher.DECRYPT_MODE, key, params);
    } else {
        throw new RuntimeException("Can't create cipher");
    }

    return cipher;
}
 
Example #6
Source File: EllipticCurvesExtension.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static boolean isAvailableCurve(int curveId) {
    String oid = idToOidMap.get(curveId);
    if (oid != null) {
        AlgorithmParameters params = null;
        try {
            params = JsseJce.getAlgorithmParameters("EC");
            params.init(new ECGenParameterSpec(oid));
        } catch (Exception e) {
            return false;
        }

        // cache the parameters
        idToParams.put(curveId, params);

        return true;
    }

    return false;
}
 
Example #7
Source File: SameBuffer.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void runGCMWithSameArray(int mode, byte[] array, int txtOffset,
        int length, AlgorithmParameters params) throws Exception {
    // first, generate cipher text at an allocated buffer
    Cipher cipher = createCipher(mode, params);
    cipher.updateAAD(array, 0, AADLength);
    byte[] outputText = cipher.doFinal(array, txtOffset, length);

    // new cipher for encrypt operation
    Cipher anotherCipher = createCipher(mode, params);
    anotherCipher.updateAAD(array, 0, AADLength);

    // next, generate cipher text again at the same buffer of plain text
    int off = anotherCipher.update(array, txtOffset, length,
            array, txtOffset);
    anotherCipher.doFinal(array, txtOffset + off);

    // check if two results are equal or not
    if (!isEqual(array, txtOffset, outputText, 0,
            outputText.length)) {
        throw new RuntimeException(
                "Two results are not equal, mode:" + mode);
    }
}
 
Example #8
Source File: DSAPrivateKey.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the DSA parameters associated with this key, or null if the
 * parameters could not be parsed.
 */
public DSAParams getParams() {
    try {
        if (algid instanceof DSAParams) {
            return (DSAParams)algid;
        } else {
            DSAParameterSpec paramSpec;
            AlgorithmParameters algParams = algid.getParameters();
            if (algParams == null) {
                return null;
            }
            paramSpec = algParams.getParameterSpec(DSAParameterSpec.class);
            return (DSAParams)paramSpec;
        }
    } catch (InvalidParameterSpecException e) {
        return null;
    }
}
 
Example #9
Source File: SameBuffer.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void doTestWithSeparateArrays(int offset,
        AlgorithmParameters params) throws Exception {
    // prepare buffers to test
    Cipher c = createCipher(Cipher.ENCRYPT_MODE, params);
    int outputLength = c.getOutputSize(textLength);
    int outputBufSize = outputLength + offset * 2;

    byte[] inputText = Helper.generateBytes(outputBufSize);
    byte[] AAD = Helper.generateBytes(AADLength);

    // do the test
    runGCMWithSeparateArray(Cipher.ENCRYPT_MODE, AAD, inputText, offset * 2,
            textLength, offset, params);
    int tagLength = c.getParameters()
            .getParameterSpec(GCMParameterSpec.class).getTLen() / 8;
    runGCMWithSeparateArray(Cipher.DECRYPT_MODE, AAD, inputText, offset,
            textLength + tagLength, offset, params);
}
 
Example #10
Source File: Encrypt.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void combination_12(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {

    // prepare ByteBuffer to test
    ByteBuffer buf = ByteBuffer.allocate(AAD.length);
    buf.put(AAD);
    buf.position(0);
    buf.limit(AAD.length);
    Cipher ci = createCipher(mode, params);
    ci.updateAAD(buf);

    // prepare an empty ByteBuffer
    ByteBuffer emptyBuf = ByteBuffer.allocate(0);
    emptyBuf.put(new byte[0]);
    ci.updateAAD(emptyBuf);
    byte[] part12_1 = new byte[ci.getOutputSize(plainText.length)];
    int offset = plainText.length > ARRAY_OFFSET ? ARRAY_OFFSET : 0;
    int len12 = ci.update(plainText, 0, plainText.length - offset,
            part12_1, 0);
    int rest12 = ci.doFinal(plainText, plainText.length - offset, offset,
            part12_1, len12);
    byte[] outputText12 = new byte[len12 + rest12];
    System.arraycopy(part12_1, 0, outputText12, 0, outputText12.length);
    results.add(outputText12);
}
 
Example #11
Source File: Encrypt.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private void combination_9(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {

    // prepare ByteBuffer to test
    ByteBuffer buf = ByteBuffer.allocate(AAD.length);
    buf.put(AAD);
    buf.position(0);
    buf.limit(AAD.length);

    // Get Cipher object and do the combination
    Cipher c = createCipher(mode, params);
    c.updateAAD(buf);
    byte[] part91 = c.update(plainText, 0, plainText.length);
    int part91_length = part91 == null ? 0 : part91.length;
    byte[] part92 = c.doFinal();
    byte[] outputText9 = new byte[part91_length + part92.length];

    // form result of the combination
    if (part91 != null) {
        System.arraycopy(part91, 0, outputText9, 0, part91_length);
    }
    System.arraycopy(part92, 0, outputText9, part91_length, part92.length);
    results.add(outputText9);
}
 
Example #12
Source File: Encrypt.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private void combination_6(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {
    Cipher c = createCipher(mode, params);
    c.updateAAD(AAD, 0, AAD.length / 2);
    c.updateAAD(AAD, AAD.length / 2, AAD.length - AAD.length / 2);
    int t = 0;
    int offset = 0;
    if (plainText.length > ARRAY_OFFSET) {
        t = plainText.length - ARRAY_OFFSET;
        offset = ARRAY_OFFSET;
    }
    byte[] part61 = c.update(plainText, 0, t);
    byte[] part62 = new byte[c.getOutputSize(plainText.length)];
    int len = c.doFinal(plainText, t, offset, part62, 0);
    int part61Length = part61 != null ? part61.length : 0;
    byte[] outputText6 = new byte[part61Length + len];
    if (part61 != null) {
        System.arraycopy(part61, 0, outputText6, 0, part61Length);
    }
    System.arraycopy(part62, 0, outputText6, part61Length, len);
    results.add(outputText6);
}
 
Example #13
Source File: SameBuffer.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void runGCMWithSameArray(int mode, byte[] array, int txtOffset,
        int length, AlgorithmParameters params) throws Exception {
    // first, generate cipher text at an allocated buffer
    Cipher cipher = createCipher(mode, params);
    cipher.updateAAD(array, 0, AADLength);
    byte[] outputText = cipher.doFinal(array, txtOffset, length);

    // new cipher for encrypt operation
    Cipher anotherCipher = createCipher(mode, params);
    anotherCipher.updateAAD(array, 0, AADLength);

    // next, generate cipher text again at the same buffer of plain text
    int off = anotherCipher.update(array, txtOffset, length,
            array, txtOffset);
    anotherCipher.doFinal(array, txtOffset + off);

    // check if two results are equal or not
    if (!isEqual(array, txtOffset, outputText, 0,
            outputText.length)) {
        throw new RuntimeException(
                "Two results are not equal, mode:" + mode);
    }
}
 
Example #14
Source File: DSAPublicKey.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the DSA parameters associated with this key, or null if the
 * parameters could not be parsed.
 */
public DSAParams getParams() {
    try {
        if (algid instanceof DSAParams) {
            return (DSAParams)algid;
        } else {
            DSAParameterSpec paramSpec;
            AlgorithmParameters algParams = algid.getParameters();
            if (algParams == null) {
                return null;
            }
            paramSpec = algParams.getParameterSpec(DSAParameterSpec.class);
            return (DSAParams)paramSpec;
        }
    } catch (InvalidParameterSpecException e) {
        return null;
    }
}
 
Example #15
Source File: OpenStegoCrypto.java    From openstego with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Method to decrypt the data
 *
 * @param input Data to be decrypted
 * @return Decrypted data (returns <code>null</code> if password is invalid)
 * @throws OpenStegoException
 */
public byte[] decrypt(byte[] input) throws OpenStegoException {
    try {
        // First byte is algo params length
        byte paramLen = input[0];
        // Copy algorithm params
        byte[] algoParamData = new byte[paramLen];
        System.arraycopy(input, 1, algoParamData, 0, paramLen);
        // Copy encrypted message
        byte[] msg = new byte[input.length - paramLen - 1];
        System.arraycopy(input, paramLen + 1, msg, 0, msg.length);

        AlgorithmParameters algoParams = AlgorithmParameters.getInstance(this.secretKey.getAlgorithm());
        algoParams.init(algoParamData);
        Cipher decryptCipher = Cipher.getInstance(this.secretKey.getAlgorithm());
        decryptCipher.init(Cipher.DECRYPT_MODE, this.secretKey, algoParams);
        return decryptCipher.doFinal(msg);
    } catch (BadPaddingException bpEx) {
        throw new OpenStegoException(bpEx, OpenStego.NAMESPACE, OpenStegoException.INVALID_PASSWORD);
    } catch (Exception ex) {
        throw new OpenStegoException(ex);
    }
}
 
Example #16
Source File: IESCipher.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
public void engineInit(
    int opmode,
    Key key,
    AlgorithmParameters params,
    SecureRandom random)
    throws InvalidKeyException, InvalidAlgorithmParameterException
{
    AlgorithmParameterSpec paramSpec = null;

    if (params != null)
    {
        try
        {
            paramSpec = params.getParameterSpec(IESParameterSpec.class);
        }
        catch (Exception e)
        {
            throw new InvalidAlgorithmParameterException("cannot recognise parameters: " + e.toString());
        }
    }

    engineParam = params;
    engineInit(opmode, key, paramSpec, random);
}
 
Example #17
Source File: DisabledAlgorithmConstraints.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
public boolean permits(String algorithm, AlgorithmParameters aps) {
    List<Constraint> list = getConstraints(algorithm);
    if (list == null) {
        return true;
    }

    for (Constraint constraint : list) {
        if (!constraint.permits(aps)) {
            if (debug != null) {
                debug.println("Constraints: failed algorithm " +
                        "parameters constraint check " + aps);
            }

            return false;
        }
    }

    return true;
}
 
Example #18
Source File: PKCS12KeyStore.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private AlgorithmParameters getAlgorithmParameters(String algorithm)
    throws IOException
{
    AlgorithmParameters algParams = null;

    // create PBE parameters from salt and iteration count
    PBEParameterSpec paramSpec =
            new PBEParameterSpec(getSalt(), iterationCount);
    try {
       algParams = AlgorithmParameters.getInstance(algorithm);
       algParams.init(paramSpec);
    } catch (Exception e) {
       throw new IOException("getAlgorithmParameters failed: " +
                             e.getMessage(), e);
    }
    return algParams;
}
 
Example #19
Source File: DSAPublicKey.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the DSA parameters associated with this key, or null if the
 * parameters could not be parsed.
 */
public DSAParams getParams() {
    try {
        if (algid instanceof DSAParams) {
            return (DSAParams)algid;
        } else {
            DSAParameterSpec paramSpec;
            AlgorithmParameters algParams = algid.getParameters();
            if (algParams == null) {
                return null;
            }
            paramSpec = algParams.getParameterSpec(DSAParameterSpec.class);
            return (DSAParams)paramSpec;
        }
    } catch (InvalidParameterSpecException e) {
        return null;
    }
}
 
Example #20
Source File: CipherSpi.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
protected AlgorithmParameters engineGetParameters() 
{
    if (engineParam == null)
    {
        if (engineParams != null)
        {
            String  name = "IES";

            try
            {
                engineParam = helper.createAlgorithmParameters(name);
                engineParam.init(engineParams);
            }
            catch (Exception e)
            {
                throw new RuntimeException(e.toString());
            }
        }
    }

    return engineParam;
}
 
Example #21
Source File: Encrypt.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void combination_11(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {

    // prepare ByteBuffer1 to test
    ByteBuffer buf1 = ByteBuffer.allocate(AAD.length / 2);
    buf1.put(AAD, 0, AAD.length / 2);
    buf1.position(0);
    buf1.limit(AAD.length / 2);

    // get a Cipher object and do combination
    Cipher ci = createCipher(mode, params);

    // process the first half of AAD data
    ci.updateAAD(buf1);

    // prepare ByteBuffer2 to test
    ByteBuffer buf2 = ByteBuffer.allocate(AAD.length - AAD.length / 2);
    buf2.put(AAD, AAD.length / 2, AAD.length - AAD.length / 2);
    buf2.position(0);
    buf2.limit(AAD.length - AAD.length / 2);

    // process the rest of AAD data
    ci.updateAAD(buf2);

    // encrypt plain text
    byte[] part11_1 = new byte[ci.getOutputSize(plainText.length)];
    int offset = plainText.length > ARRAY_OFFSET ? ARRAY_OFFSET : 0;
    int len_11 = ci.update(plainText, 0, plainText.length - offset,
            part11_1, 0);
    byte[] part11_2 = ci.doFinal(plainText, plainText.length - offset,
            offset);
    byte[] outputText11 = new byte[len_11 + part11_2.length];
    System.arraycopy(part11_1, 0, outputText11, 0, len_11);
    System.arraycopy(part11_2, 0, outputText11, len_11, part11_2.length);
    results.add(outputText11);
}
 
Example #22
Source File: PKCS12KeyStore.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private AlgorithmParameters parseAlgParameters(ObjectIdentifier algorithm,
    DerInputStream in) throws IOException
{
    AlgorithmParameters algParams = null;
    try {
        DerValue params;
        if (in.available() == 0) {
            params = null;
        } else {
            params = in.getDerValue();
            if (params.tag == DerValue.tag_Null) {
               params = null;
            }
        }
        if (params != null) {
            if (algorithm.equals(pbes2_OID)) {
                algParams = AlgorithmParameters.getInstance("PBES2");
            } else {
                algParams = AlgorithmParameters.getInstance("PBE");
            }
            algParams.init(params.toByteArray());
        }
    } catch (Exception e) {
       throw new IOException("parseAlgParameters failed: " +
                             e.getMessage(), e);
    }
    return algParams;
}
 
Example #23
Source File: Encrypt.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private void combination_11(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {

    // prepare ByteBuffer1 to test
    ByteBuffer buf1 = ByteBuffer.allocate(AAD.length / 2);
    buf1.put(AAD, 0, AAD.length / 2);
    buf1.position(0);
    buf1.limit(AAD.length / 2);

    // get a Cipher object and do combination
    Cipher ci = createCipher(mode, params);

    // process the first half of AAD data
    ci.updateAAD(buf1);

    // prepare ByteBuffer2 to test
    ByteBuffer buf2 = ByteBuffer.allocate(AAD.length - AAD.length / 2);
    buf2.put(AAD, AAD.length / 2, AAD.length - AAD.length / 2);
    buf2.position(0);
    buf2.limit(AAD.length - AAD.length / 2);

    // process the rest of AAD data
    ci.updateAAD(buf2);

    // encrypt plain text
    byte[] part11_1 = new byte[ci.getOutputSize(plainText.length)];
    int offset = plainText.length > ARRAY_OFFSET ? ARRAY_OFFSET : 0;
    int len_11 = ci.update(plainText, 0, plainText.length - offset,
            part11_1, 0);
    byte[] part11_2 = ci.doFinal(plainText, plainText.length - offset,
            offset);
    byte[] outputText11 = new byte[len_11 + part11_2.length];
    System.arraycopy(part11_1, 0, outputText11, 0, len_11);
    System.arraycopy(part11_2, 0, outputText11, len_11, part11_2.length);
    results.add(outputText11);
}
 
Example #24
Source File: Encrypt.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test AEAD combinations
 *
 * @param mode decryption or encryption
 * @param AAD additional data for AEAD operations
 * @param inputText plain text to decrypt/encrypt
 * @return output text after encrypt/decrypt
 */
public byte[] execute(int mode, byte[] AAD, byte[] inputText,
        AlgorithmParameters params) throws Exception {

    Cipher cipher = createCipher(mode, params);

    // results of each combination will be saved in the outputTexts
    List<byte[]> outputTexts = new ArrayList<>();

    // generate a standard outputText using a single-part en/de-cryption
    cipher.updateAAD(AAD);
    byte[] output = cipher.doFinal(inputText);

    // execute multiple-part encryption/decryption combinations
    combination_1(outputTexts, mode, AAD, inputText, params);
    combination_2(outputTexts, mode, AAD, inputText, params);
    combination_3(outputTexts, mode, AAD, inputText, params);
    combination_4(outputTexts, mode, AAD, inputText, params);
    combination_5(outputTexts, mode, AAD, inputText, params);
    combination_6(outputTexts, mode, AAD, inputText, params);
    combination_7(outputTexts, mode, AAD, inputText, params);
    combination_8(outputTexts, mode, AAD, inputText, params);
    combination_9(outputTexts, mode, AAD, inputText, params);
    combination_10(outputTexts, mode, AAD, inputText, params);
    combination_11(outputTexts, mode, AAD, inputText, params);
    combination_12(outputTexts, mode, AAD, inputText, params);
    combination_13(outputTexts, mode, AAD, inputText, params);
    combination_14(outputTexts, mode, AAD, inputText, params);
    combination_15(outputTexts, mode, AAD, inputText, params);
    combination_16(outputTexts, mode, AAD, inputText, params);

    for (int k = 0; k < outputTexts.size(); k++) {
        if (!Arrays.equals(output, outputTexts.get(k))) {
            throw new RuntimeException("Combination #" + k + " failed");
        }
    }
    return output;
}
 
Example #25
Source File: DisabledAlgorithmConstraints.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final boolean permits(Set<CryptoPrimitive> primitives,
        String algorithm, Key key, AlgorithmParameters parameters) {

    if (algorithm == null || algorithm.length() == 0) {
        throw new IllegalArgumentException("No algorithm name specified");
    }

    return checkConstraints(primitives, algorithm, key, parameters);
}
 
Example #26
Source File: Encrypt.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void combination_16(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {
    Cipher c = createCipher(mode, params);

    // prepare ByteBuffer to test
    ByteBuffer buf = ByteBuffer.allocateDirect(AAD.length);
    buf.put(AAD);
    buf.position(0);
    buf.limit(AAD.length);
    c.updateAAD(buf);

    // prepare empty ByteBuffer
    ByteBuffer emptyBuf = ByteBuffer.allocateDirect(0);
    emptyBuf.put(new byte[0]);
    c.updateAAD(emptyBuf);

    // prepare buffers to encrypt/decrypt
    ByteBuffer in = ByteBuffer.allocateDirect(plainText.length);
    in.put(plainText);
    in.position(0);
    in.limit(plainText.length);
    ByteBuffer output = ByteBuffer.allocateDirect(
            c.getOutputSize(in.limit()));
    output.position(0);
    output.limit(c.getOutputSize(in.limit()));

    // process input text with an empty buffer
    c.update(in, output);
    ByteBuffer emptyBuf2 = ByteBuffer.allocate(0);
    emptyBuf2.put(new byte[0]);
    c.doFinal(emptyBuf2, output);
    int resultSize = output.position();
    byte[] result16 = new byte[resultSize];
    output.position(0);
    output.limit(resultSize);
    output.get(result16, 0, resultSize);
    results.add(result16);
}
 
Example #27
Source File: Pkcs8Util.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * PKCS #8 encode and encrypt a private key.
 *
 * @return The encrypted encoding
 * @param privateKey
 *            The private key
 * @param pbeType
 *            PBE algorithm to use for encryption
 * @param password
 *            Encryption password
 * @throws CryptoException
 *             Problem encountered while getting the encoded private key
 * @throws IOException
 *             If an I/O error occurred
 */
public static byte[] getEncrypted(PrivateKey privateKey, Pkcs8PbeType pbeType, Password password)
		throws CryptoException, IOException {
	try {
		byte[] pkcs8 = get(privateKey);

		// Generate PBE secret key from password
		SecretKeyFactory keyFact = SecretKeyFactory.getInstance(pbeType.jce());
		PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
		SecretKey pbeKey = keyFact.generateSecret(pbeKeySpec);

		// Generate random salt and iteration count
		byte[] salt = generateSalt();
		int iterationCount = generateIterationCount();

		// Store in algorithm parameters
		PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, iterationCount);
		AlgorithmParameters params = AlgorithmParameters.getInstance(pbeType.jce());
		params.init(pbeParameterSpec);

		// Create PBE cipher from key and params
		Cipher cipher = Cipher.getInstance(pbeType.jce());
		cipher.init(Cipher.ENCRYPT_MODE, pbeKey, params);

		// Encrypt key
		byte[] encPkcs8 = cipher.doFinal(pkcs8);

		// Create and return encrypted private key information
		EncryptedPrivateKeyInfo encPrivateKeyInfo = new EncryptedPrivateKeyInfo(params, encPkcs8);

		return encPrivateKeyInfo.getEncoded();
	} catch (GeneralSecurityException ex) {
		throw new CryptoException("NoEncryptPkcs8PrivateKey.exception.message", ex);
	}
}
 
Example #28
Source File: Encrypt.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test AEAD combinations
 *
 * @param mode decryption or encryption
 * @param AAD additional data for AEAD operations
 * @param inputText plain text to decrypt/encrypt
 * @return output text after encrypt/decrypt
 */
public byte[] execute(int mode, byte[] AAD, byte[] inputText,
        AlgorithmParameters params) throws Exception {

    Cipher cipher = createCipher(mode, params);

    // results of each combination will be saved in the outputTexts
    List<byte[]> outputTexts = new ArrayList<>();

    // generate a standard outputText using a single-part en/de-cryption
    cipher.updateAAD(AAD);
    byte[] output = cipher.doFinal(inputText);

    // execute multiple-part encryption/decryption combinations
    combination_1(outputTexts, mode, AAD, inputText, params);
    combination_2(outputTexts, mode, AAD, inputText, params);
    combination_3(outputTexts, mode, AAD, inputText, params);
    combination_4(outputTexts, mode, AAD, inputText, params);
    combination_5(outputTexts, mode, AAD, inputText, params);
    combination_6(outputTexts, mode, AAD, inputText, params);
    combination_7(outputTexts, mode, AAD, inputText, params);
    combination_8(outputTexts, mode, AAD, inputText, params);
    combination_9(outputTexts, mode, AAD, inputText, params);
    combination_10(outputTexts, mode, AAD, inputText, params);
    combination_11(outputTexts, mode, AAD, inputText, params);
    combination_12(outputTexts, mode, AAD, inputText, params);
    combination_13(outputTexts, mode, AAD, inputText, params);
    combination_14(outputTexts, mode, AAD, inputText, params);
    combination_15(outputTexts, mode, AAD, inputText, params);
    combination_16(outputTexts, mode, AAD, inputText, params);

    for (int k = 0; k < outputTexts.size(); k++) {
        if (!Arrays.equals(output, outputTexts.get(k))) {
            throw new RuntimeException("Combination #" + k + " failed");
        }
    }
    return output;
}
 
Example #29
Source File: TestDSAGenParameterSpec.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static void testDSAGenParameterSpec(DataTuple dataTuple)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidParameterSpecException, InvalidAlgorithmParameterException {
    System.out.printf("Test case: primePLen=%d, " + "subprimeQLen=%d%n",
            dataTuple.primePLen, dataTuple.subprimeQLen);

    AlgorithmParameterGenerator apg =
            AlgorithmParameterGenerator.getInstance(ALGORITHM_NAME,
                    PROVIDER_NAME);

    DSAGenParameterSpec genParamSpec = createGenParameterSpec(dataTuple);
    // genParamSpec will be null if IllegalAE is thrown when expected.
    if (genParamSpec == null) {
        return;
    }

    try {
        apg.init(genParamSpec, null);
        AlgorithmParameters param = apg.generateParameters();

        checkParam(param, genParamSpec);
        System.out.println("Test case passed");
    } catch (InvalidParameterException ipe) {
        // The DSAGenParameterSpec API support this, but the real
        // implementation in SUN doesn't
        if (!dataTuple.isSunProviderSupported) {
            System.out.println("Test case passed: expected "
                    + "InvalidParameterException is caught");
        } else {
            throw new RuntimeException("Test case failed.", ipe);
        }
    }
}
 
Example #30
Source File: PKCS12KeyStore.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static String mapPBEParamsToAlgorithm(ObjectIdentifier algorithm,
    AlgorithmParameters algParams) throws NoSuchAlgorithmException {
    // Check for PBES2 algorithms
    if (algorithm.equals((Object)pbes2_OID) && algParams != null) {
        return algParams.toString();
    }
    return algorithm.toString();
}