Search in sources :

Example 6 with AlgorithmParameterSpec

use of java.security.spec.AlgorithmParameterSpec in project jdk8u_jdk by JetBrains.

the class DESCipherWrapper method execute.

public void execute(int edMode, byte[] inputText) throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, ShortBufferException, NoSuchAlgorithmException {
    AlgorithmParameterSpec aps = null;
    try {
        if (!mode.equalsIgnoreCase("ECB")) {
            aps = new IvParameterSpec(iv);
        }
        ci.init(edMode, key, aps);
        // Generate a resultText using a single-part enc/dec
        resultText = ci.doFinal(inputText);
        // Generate outputText for each multi-part en/de-cryption
        /* Combination #1:
            update(byte[], int, int)
            doFinal(byte[], int, int)
             */
        byte[] part11 = ci.update(inputText, 0, inputText.length);
        byte[] part12 = ci.doFinal();
        byte[] outputText1 = new byte[part11.length + part12.length];
        System.arraycopy(part11, 0, outputText1, 0, part11.length);
        System.arraycopy(part12, 0, outputText1, part11.length, part12.length);
        List<byte[]> outputTexts = new ArrayList<>(4);
        outputTexts.add(outputText1);
        /* Combination #2:
            update(byte[], int, int)
            doFinal(byte[], int, int, byte[], int)
             */
        byte[] part21 = ci.update(inputText, 0, inputText.length - 5);
        byte[] part22 = new byte[ci.getOutputSize(inputText.length)];
        int len2 = ci.doFinal(inputText, inputText.length - 5, 5, part22, 0);
        byte[] outputText2 = new byte[part21.length + len2];
        System.arraycopy(part21, 0, outputText2, 0, part21.length);
        System.arraycopy(part22, 0, outputText2, part21.length, len2);
        outputTexts.add(outputText2);
        /* Combination #3:
            update(byte[], int, int, byte[], int)
            doFinal(byte[], int, int)
             */
        byte[] part31 = new byte[ci.getOutputSize(inputText.length)];
        int len3 = ci.update(inputText, 0, inputText.length - 8, part31, 0);
        byte[] part32 = ci.doFinal(inputText, inputText.length - 8, 8);
        byte[] outputText3 = new byte[len3 + part32.length];
        System.arraycopy(part31, 0, outputText3, 0, len3);
        System.arraycopy(part32, 0, outputText3, len3, part32.length);
        outputTexts.add(outputText3);
        /* Combination #4:
            update(byte[], int, int, byte[], int)
            doFinal(byte[], int, int, byte[], int)
             */
        byte[] part41 = new byte[ci.getOutputSize(inputText.length)];
        int len4 = ci.update(inputText, 0, inputText.length - 8, part41, 0);
        int rest4 = ci.doFinal(inputText, inputText.length - 8, 8, part41, len4);
        byte[] outputText4 = new byte[len4 + rest4];
        System.arraycopy(part41, 0, outputText4, 0, outputText4.length);
        outputTexts.add(outputText4);
        // Compare results
        for (int k = 0; k < outputTexts.size(); k++) {
            if (!Arrays.equals(resultText, outputTexts.get(k))) {
                out.println(" Testing: " + algo + "/" + mode + "/" + pad);
                throw new RuntimeException("Compare value of resultText and combination " + k + " are not same. Test failed.");
            }
        }
        if (keyStrength > Cipher.getMaxAllowedKeyLength(algo)) {
            throw new RuntimeException("Expected exception uncaught, keyStrength " + keyStrength);
        }
    } catch (InvalidKeyException ex) {
        if (keyStrength <= Cipher.getMaxAllowedKeyLength(algo)) {
            out.println("Unexpected exception in " + algo + "/" + mode + "/" + pad + " ,  KeySize " + keyStrength);
            throw ex;
        }
        out.println("Caught InvalidKeyException as expected");
    }
}
Also used : ArrayList(java.util.ArrayList) IvParameterSpec(javax.crypto.spec.IvParameterSpec) InvalidKeyException(java.security.InvalidKeyException) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 7 with AlgorithmParameterSpec

use of java.security.spec.AlgorithmParameterSpec in project jdk8u_jdk by JetBrains.

the class TestCipherPBE method runTest.

private void runTest(String algorithm) throws InvalidKeySpecException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, ShortBufferException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
    out.println("=> Testing: " + algorithm);
    try {
        // Initialization
        AlgorithmParameterSpec algoParamSpec = new PBEParameterSpec(SALT, 6);
        SecretKey secretKey = SecretKeyFactory.getInstance(KEY_ALGO).generateSecret(new PBEKeySpec(("Secret Key Value").toCharArray()));
        Cipher ci = Cipher.getInstance(algorithm);
        ci.init(Cipher.ENCRYPT_MODE, secretKey, algoParamSpec);
        // Encryption
        byte[] cipherText = ci.doFinal(PLAIN_TEXT);
        // Decryption
        ci.init(Cipher.DECRYPT_MODE, secretKey, algoParamSpec);
        byte[] recoveredText = ci.doFinal(cipherText);
        if (algorithm.contains("TripleDES")) {
            throw new RuntimeException("Expected InvalidKeyException exception uncaugh");
        }
        // Comparison
        if (!Arrays.equals(PLAIN_TEXT, recoveredText)) {
            throw new RuntimeException("Test failed: plainText is not equal to recoveredText");
        }
        out.println("Test Passed.");
    } catch (InvalidKeyException ex) {
        if (algorithm.contains("TripleDES")) {
            out.println("Expected InvalidKeyException raised");
        } else {
            throw new RuntimeException(ex);
        }
    }
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKey(javax.crypto.SecretKey) Cipher(javax.crypto.Cipher) InvalidKeyException(java.security.InvalidKeyException) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec)

Example 8 with AlgorithmParameterSpec

use of java.security.spec.AlgorithmParameterSpec in project android_frameworks_base by AOSPA.

the class ApkSignatureSchemeV2Verifier method verifySigner.

private static X509Certificate[] verifySigner(ByteBuffer signerBlock, Map<Integer, byte[]> contentDigests, CertificateFactory certFactory) throws SecurityException, IOException {
    ByteBuffer signedData = getLengthPrefixedSlice(signerBlock);
    ByteBuffer signatures = getLengthPrefixedSlice(signerBlock);
    byte[] publicKeyBytes = readLengthPrefixedByteArray(signerBlock);
    int signatureCount = 0;
    int bestSigAlgorithm = -1;
    byte[] bestSigAlgorithmSignatureBytes = null;
    List<Integer> signaturesSigAlgorithms = new ArrayList<>();
    while (signatures.hasRemaining()) {
        signatureCount++;
        try {
            ByteBuffer signature = getLengthPrefixedSlice(signatures);
            if (signature.remaining() < 8) {
                throw new SecurityException("Signature record too short");
            }
            int sigAlgorithm = signature.getInt();
            signaturesSigAlgorithms.add(sigAlgorithm);
            if (!isSupportedSignatureAlgorithm(sigAlgorithm)) {
                continue;
            }
            if ((bestSigAlgorithm == -1) || (compareSignatureAlgorithm(sigAlgorithm, bestSigAlgorithm) > 0)) {
                bestSigAlgorithm = sigAlgorithm;
                bestSigAlgorithmSignatureBytes = readLengthPrefixedByteArray(signature);
            }
        } catch (IOException | BufferUnderflowException e) {
            throw new SecurityException("Failed to parse signature record #" + signatureCount, e);
        }
    }
    if (bestSigAlgorithm == -1) {
        if (signatureCount == 0) {
            throw new SecurityException("No signatures found");
        } else {
            throw new SecurityException("No supported signatures found");
        }
    }
    String keyAlgorithm = getSignatureAlgorithmJcaKeyAlgorithm(bestSigAlgorithm);
    Pair<String, ? extends AlgorithmParameterSpec> signatureAlgorithmParams = getSignatureAlgorithmJcaSignatureAlgorithm(bestSigAlgorithm);
    String jcaSignatureAlgorithm = signatureAlgorithmParams.first;
    AlgorithmParameterSpec jcaSignatureAlgorithmParams = signatureAlgorithmParams.second;
    boolean sigVerified;
    try {
        PublicKey publicKey = KeyFactory.getInstance(keyAlgorithm).generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        Signature sig = Signature.getInstance(jcaSignatureAlgorithm);
        sig.initVerify(publicKey);
        if (jcaSignatureAlgorithmParams != null) {
            sig.setParameter(jcaSignatureAlgorithmParams);
        }
        sig.update(signedData);
        sigVerified = sig.verify(bestSigAlgorithmSignatureBytes);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | InvalidAlgorithmParameterException | SignatureException e) {
        throw new SecurityException("Failed to verify " + jcaSignatureAlgorithm + " signature", e);
    }
    if (!sigVerified) {
        throw new SecurityException(jcaSignatureAlgorithm + " signature did not verify");
    }
    // Signature over signedData has verified.
    byte[] contentDigest = null;
    signedData.clear();
    ByteBuffer digests = getLengthPrefixedSlice(signedData);
    List<Integer> digestsSigAlgorithms = new ArrayList<>();
    int digestCount = 0;
    while (digests.hasRemaining()) {
        digestCount++;
        try {
            ByteBuffer digest = getLengthPrefixedSlice(digests);
            if (digest.remaining() < 8) {
                throw new IOException("Record too short");
            }
            int sigAlgorithm = digest.getInt();
            digestsSigAlgorithms.add(sigAlgorithm);
            if (sigAlgorithm == bestSigAlgorithm) {
                contentDigest = readLengthPrefixedByteArray(digest);
            }
        } catch (IOException | BufferUnderflowException e) {
            throw new IOException("Failed to parse digest record #" + digestCount, e);
        }
    }
    if (!signaturesSigAlgorithms.equals(digestsSigAlgorithms)) {
        throw new SecurityException("Signature algorithms don't match between digests and signatures records");
    }
    int digestAlgorithm = getSignatureAlgorithmContentDigestAlgorithm(bestSigAlgorithm);
    byte[] previousSignerDigest = contentDigests.put(digestAlgorithm, contentDigest);
    if ((previousSignerDigest != null) && (!MessageDigest.isEqual(previousSignerDigest, contentDigest))) {
        throw new SecurityException(getContentDigestAlgorithmJcaDigestAlgorithm(digestAlgorithm) + " contents digest does not match the digest specified by a preceding signer");
    }
    ByteBuffer certificates = getLengthPrefixedSlice(signedData);
    List<X509Certificate> certs = new ArrayList<>();
    int certificateCount = 0;
    while (certificates.hasRemaining()) {
        certificateCount++;
        byte[] encodedCert = readLengthPrefixedByteArray(certificates);
        X509Certificate certificate;
        try {
            certificate = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(encodedCert));
        } catch (CertificateException e) {
            throw new SecurityException("Failed to decode certificate #" + certificateCount, e);
        }
        certificate = new VerbatimX509Certificate(certificate, encodedCert);
        certs.add(certificate);
    }
    if (certs.isEmpty()) {
        throw new SecurityException("No certificates listed");
    }
    X509Certificate mainCertificate = certs.get(0);
    byte[] certificatePublicKeyBytes = mainCertificate.getPublicKey().getEncoded();
    if (!Arrays.equals(publicKeyBytes, certificatePublicKeyBytes)) {
        throw new SecurityException("Public key mismatch between certificate and signature record");
    }
    return certs.toArray(new X509Certificate[certs.size()]);
}
Also used : ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) BufferUnderflowException(java.nio.BufferUnderflowException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) DirectByteBuffer(java.nio.DirectByteBuffer) ByteBuffer(java.nio.ByteBuffer) X509Certificate(java.security.cert.X509Certificate) BigInteger(java.math.BigInteger) ByteArrayInputStream(java.io.ByteArrayInputStream) Signature(java.security.Signature) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 9 with AlgorithmParameterSpec

use of java.security.spec.AlgorithmParameterSpec in project robovm by robovm.

the class KeyPairGenerator1Test method testKeyPairGenerator11.

/**
     * Test for methods:
     * <code>initialize(int keysize)</code>
     * <code>initialize(int keysize, SecureRandom random)</code>
     * <code>initialize(AlgorithmParameterSpec param)</code>
     * <code>initialize(AlgorithmParameterSpec param, SecureRandom random)</code>
     * Assertion: throws InvalidParameterException or
     * InvalidAlgorithmParameterException when parameters keysize or param are
     * incorrect
     */
public void testKeyPairGenerator11() throws NoSuchAlgorithmException, NoSuchProviderException {
    if (!DSASupported) {
        fail(NotSupportMsg);
        return;
    }
    int[] keys = { -10000, -1024, -1, 0, 10000 };
    KeyPairGenerator[] kpg = createKPGen();
    assertNotNull("KeyPairGenerator objects were not created", kpg);
    SecureRandom random = new SecureRandom();
    AlgorithmParameterSpec aps = null;
    for (int i = 0; i < kpg.length; i++) {
        for (int j = 0; j < keys.length; j++) {
            try {
                kpg[i].initialize(keys[j]);
                kpg[i].initialize(keys[j], random);
            } catch (InvalidParameterException e) {
            }
        }
        try {
            kpg[i].initialize(aps);
            kpg[i].initialize(aps, random);
        } catch (InvalidAlgorithmParameterException e) {
        }
    }
}
Also used : InvalidParameterException(java.security.InvalidParameterException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) SecureRandom(java.security.SecureRandom) KeyPairGenerator(java.security.KeyPairGenerator) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 10 with AlgorithmParameterSpec

use of java.security.spec.AlgorithmParameterSpec in project robovm by robovm.

the class CipherSpi method engineInit.

protected void engineInit(int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
    AlgorithmParameterSpec paramSpec = null;
    if (params != null) {
        try {
            paramSpec = params.getParameterSpec(OAEPParameterSpec.class);
        } catch (InvalidParameterSpecException e) {
            throw new InvalidAlgorithmParameterException("cannot recognise parameters: " + e.toString(), e);
        }
    }
    engineParams = params;
    engineInit(opmode, key, paramSpec, random);
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) InvalidParameterSpecException(java.security.spec.InvalidParameterSpecException) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) OAEPParameterSpec(javax.crypto.spec.OAEPParameterSpec)

Aggregations

AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)186 IvParameterSpec (javax.crypto.spec.IvParameterSpec)59 Cipher (javax.crypto.Cipher)55 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)51 InvalidKeyException (java.security.InvalidKeyException)42 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)37 SecureRandom (java.security.SecureRandom)27 SecretKey (javax.crypto.SecretKey)27 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)24 BigInteger (java.math.BigInteger)21 BadPaddingException (javax.crypto.BadPaddingException)21 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)20 RSAKeyGenParameterSpec (java.security.spec.RSAKeyGenParameterSpec)19 ShortBufferException (javax.crypto.ShortBufferException)19 Key (java.security.Key)18 SecretKeySpec (javax.crypto.spec.SecretKeySpec)18 AlgorithmParameters (java.security.AlgorithmParameters)17 KeyGenerator (javax.crypto.KeyGenerator)17 OAEPParameterSpec (javax.crypto.spec.OAEPParameterSpec)15 IOException (java.io.IOException)14