Search in sources :

Example 21 with AlgorithmParameters

use of java.security.AlgorithmParameters in project robovm by robovm.

the class SealedObject method getObject.

/**
     * Returns the wrapped object, decrypting it using the specified key. The
     * specified provider is used to retrieve the cipher algorithm.
     *
     * @param key
     *            the key to decrypt the data.
     * @param provider
     *            the name of the provider that provides the cipher algorithm.
     * @return the encapsulated object.
     * @throws IOException
     *             if deserialization fails.
     * @throws ClassNotFoundException
     *             if deserialization fails.
     * @throws NoSuchAlgorithmException
     *             if the algorithm used to decrypt the data is not available.
     * @throws NoSuchProviderException
     *             if the specified provider is not available.
     * @throws InvalidKeyException
     *             if the specified key cannot be used to decrypt the data.
     */
public final Object getObject(Key key, String provider) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
    if (provider == null || provider.isEmpty()) {
        throw new IllegalArgumentException("provider name empty or null");
    }
    try {
        Cipher cipher = Cipher.getInstance(sealAlg, provider);
        if ((paramsAlg != null) && (paramsAlg.length() != 0)) {
            AlgorithmParameters params = AlgorithmParameters.getInstance(paramsAlg);
            params.init(encodedParams);
            cipher.init(Cipher.DECRYPT_MODE, key, params);
        } else {
            cipher.init(Cipher.DECRYPT_MODE, key);
        }
        byte[] serialized = cipher.doFinal(encryptedContent);
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(serialized));
        return ois.readObject();
    } catch (NoSuchPaddingException e) {
        // with existing padding
        throw new NoSuchAlgorithmException(e.toString());
    } catch (InvalidAlgorithmParameterException e) {
        // with correct algorithm parameters
        throw new NoSuchAlgorithmException(e.toString());
    } catch (IllegalBlockSizeException e) {
        // was correctly made
        throw new NoSuchAlgorithmException(e.toString());
    } catch (BadPaddingException e) {
        // was correctly made
        throw new NoSuchAlgorithmException(e.toString());
    } catch (IllegalStateException e) {
        // should never be thrown because cipher is initialized
        throw new NoSuchAlgorithmException(e.toString());
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) ByteArrayInputStream(java.io.ByteArrayInputStream) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AlgorithmParameters(java.security.AlgorithmParameters) ObjectInputStream(java.io.ObjectInputStream)

Example 22 with AlgorithmParameters

use of java.security.AlgorithmParameters in project robovm by robovm.

the class OperatorHelper method createRawSignature.

public Signature createRawSignature(AlgorithmIdentifier algorithm) {
    Signature sig;
    try {
        String algName = getSignatureName(algorithm);
        algName = "NONE" + algName.substring(algName.indexOf("WITH"));
        sig = helper.createSignature(algName);
        // the AlgorithmIdentifier parameters field MUST contain RSASSA-PSS-params.
        if (algorithm.getAlgorithm().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) {
            AlgorithmParameters params = helper.createAlgorithmParameters(algName);
            params.init(algorithm.getParameters().toASN1Primitive().getEncoded(), "ASN.1");
            PSSParameterSpec spec = (PSSParameterSpec) params.getParameterSpec(PSSParameterSpec.class);
            sig.setParameter(spec);
        }
    } catch (Exception e) {
        return null;
    }
    return sig;
}
Also used : PSSParameterSpec(java.security.spec.PSSParameterSpec) Signature(java.security.Signature) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException) AlgorithmParameters(java.security.AlgorithmParameters)

Example 23 with AlgorithmParameters

use of java.security.AlgorithmParameters in project robovm by robovm.

the class OldDHTest method testDHGen.

@BrokenTest("Suffers from DH slowness, disabling for now")
public void testDHGen() throws Exception {
    KeyPairGenerator gen = null;
    try {
        gen = KeyPairGenerator.getInstance("DH");
    } catch (NoSuchAlgorithmException e) {
        fail(e.getMessage());
    }
    AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance("DH");
    algorithmparametergenerator.init(1024, new SecureRandom());
    AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters();
    DHParameterSpec dhparameterspec = algorithmparameters.getParameterSpec(DHParameterSpec.class);
    //gen.initialize(1024);
    gen.initialize(dhparameterspec);
    KeyPair key = gen.generateKeyPair();
}
Also used : KeyPair(java.security.KeyPair) AlgorithmParameterGenerator(java.security.AlgorithmParameterGenerator) SecureRandom(java.security.SecureRandom) DHParameterSpec(javax.crypto.spec.DHParameterSpec) KeyPairGenerator(java.security.KeyPairGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AlgorithmParameters(java.security.AlgorithmParameters) BrokenTest(dalvik.annotation.BrokenTest)

Example 24 with AlgorithmParameters

use of java.security.AlgorithmParameters in project robovm by robovm.

the class CipherTest method test_Cipher.

private void test_Cipher(Cipher c) throws Exception {
    String algorithm = c.getAlgorithm().toUpperCase(Locale.US);
    String providerName = c.getProvider().getName();
    if (!isSupported(algorithm, providerName)) {
        return;
    }
    String cipherID = algorithm + ":" + providerName;
    try {
        c.getOutputSize(0);
    } catch (IllegalStateException expected) {
    }
    // TODO: test keys from different factories (e.g. OpenSSLRSAPrivateKey vs JCERSAPrivateKey)
    Key encryptKey = getEncryptKey(algorithm);
    final AlgorithmParameterSpec encryptSpec = getEncryptAlgorithmParameterSpec(algorithm);
    int encryptMode = getEncryptMode(algorithm);
    // Bouncycastle doesn't return a default PBEParameterSpec
    if (isPBE(algorithm) && !"BC".equals(providerName)) {
        assertNotNull(cipherID + " getParameters()", c.getParameters());
        assertNotNull(c.getParameters().getParameterSpec(PBEParameterSpec.class));
    } else {
        assertNull(cipherID + " getParameters()", c.getParameters());
    }
    try {
        assertNull(cipherID + " getIV()", c.getIV());
    } catch (NullPointerException e) {
        // Bouncycastle apparently has a bug here with AESWRAP, et al.
        if (!("BC".equals(providerName) && isOnlyWrappingAlgorithm(algorithm))) {
            throw e;
        }
    }
    c.init(encryptMode, encryptKey, encryptSpec);
    assertEquals(cipherID + " getBlockSize() encryptMode", getExpectedBlockSize(algorithm, encryptMode, providerName), c.getBlockSize());
    assertEquals(cipherID + " getOutputSize(0) encryptMode", getExpectedOutputSize(algorithm, encryptMode, providerName), c.getOutputSize(0));
    final AlgorithmParameterSpec decryptSpec = getDecryptAlgorithmParameterSpec(encryptSpec, c);
    int decryptMode = getDecryptMode(algorithm);
    c.init(decryptMode, encryptKey, decryptSpec);
    assertEquals(cipherID + " getBlockSize() decryptMode", getExpectedBlockSize(algorithm, decryptMode, providerName), c.getBlockSize());
    assertEquals(cipherID + " getOutputSize(0) decryptMode", getExpectedOutputSize(algorithm, decryptMode, providerName), c.getOutputSize(0));
    if (isPBE(algorithm)) {
        if (algorithm.endsWith("RC4")) {
            assertNull(cipherID + " getIV()", c.getIV());
        } else {
            assertNotNull(cipherID + " getIV()", c.getIV());
        }
    } else if (decryptSpec instanceof IvParameterSpec) {
        assertEquals(cipherID + " getIV()", Arrays.toString(((IvParameterSpec) decryptSpec).getIV()), Arrays.toString(c.getIV()));
    } else {
        try {
            assertNull(cipherID + " getIV()", c.getIV());
        } catch (NullPointerException e) {
            // Bouncycastle apparently has a bug here with AESWRAP, et al.
            if (!("BC".equals(providerName) && isOnlyWrappingAlgorithm(algorithm))) {
                throw e;
            }
        }
    }
    AlgorithmParameters params = c.getParameters();
    if (decryptSpec == null) {
        assertNull(cipherID + " getParameters()", params);
    } else if (decryptSpec instanceof IvParameterSpec) {
        IvParameterSpec ivDecryptSpec = (IvParameterSpec) params.getParameterSpec(IvParameterSpec.class);
        assertEquals(cipherID + " getIV()", Arrays.toString(((IvParameterSpec) decryptSpec).getIV()), Arrays.toString(ivDecryptSpec.getIV()));
    } else if (decryptSpec instanceof PBEParameterSpec) {
        // Bouncycastle seems to be schizophrenic about whther it returns this or not
        if (!"BC".equals(providerName)) {
            assertNotNull(cipherID + " getParameters()", params);
        }
    }
    assertNull(cipherID, c.getExemptionMechanism());
    // Test wrapping a key.  Every cipher should be able to wrap. Except those that can't.
    if (isSupportedForWrapping(algorithm)) {
        // Generate a small SecretKey for AES.
        KeyGenerator kg = KeyGenerator.getInstance("AES");
        kg.init(128);
        SecretKey sk = kg.generateKey();
        // Wrap it
        c.init(Cipher.WRAP_MODE, encryptKey, encryptSpec);
        byte[] cipherText = c.wrap(sk);
        // Unwrap it
        c.init(Cipher.UNWRAP_MODE, getDecryptKey(algorithm), decryptSpec);
        Key decryptedKey = c.unwrap(cipherText, sk.getAlgorithm(), Cipher.SECRET_KEY);
        assertEquals(cipherID + " sk.getAlgorithm()=" + sk.getAlgorithm() + " decryptedKey.getAlgorithm()=" + decryptedKey.getAlgorithm() + " encryptKey.getEncoded()=" + Arrays.toString(sk.getEncoded()) + " decryptedKey.getEncoded()=" + Arrays.toString(decryptedKey.getEncoded()), sk, decryptedKey);
    }
    if (!isOnlyWrappingAlgorithm(algorithm)) {
        c.init(Cipher.ENCRYPT_MODE, encryptKey, encryptSpec);
        byte[] cipherText = c.doFinal(getActualPlainText(algorithm));
        c.init(Cipher.DECRYPT_MODE, getDecryptKey(algorithm), decryptSpec);
        byte[] decryptedPlainText = c.doFinal(cipherText);
        assertEquals(cipherID, Arrays.toString(getExpectedPlainText(algorithm, providerName)), Arrays.toString(decryptedPlainText));
    }
}
Also used : SecretKey(javax.crypto.SecretKey) IvParameterSpec(javax.crypto.spec.IvParameterSpec) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) KeyGenerator(javax.crypto.KeyGenerator) RSAPublicKey(java.security.interfaces.RSAPublicKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec) AlgorithmParameters(java.security.AlgorithmParameters)

Example 25 with AlgorithmParameters

use of java.security.AlgorithmParameters in project robovm by robovm.

the class AlgorithmParameterGeneratorSpi method engineGenerateParameters.

protected AlgorithmParameters engineGenerateParameters() {
    DHParametersGenerator pGen = new DHParametersGenerator();
    if (random != null) {
        pGen.init(strength, 20, random);
    } else {
        pGen.init(strength, 20, new SecureRandom());
    }
    DHParameters p = pGen.generateParameters();
    AlgorithmParameters params;
    try {
        params = AlgorithmParameters.getInstance("DH", BouncyCastleProvider.PROVIDER_NAME);
        params.init(new DHParameterSpec(p.getP(), p.getG(), l));
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
    }
    return params;
}
Also used : DHParameters(org.bouncycastle.crypto.params.DHParameters) SecureRandom(java.security.SecureRandom) DHParameterSpec(javax.crypto.spec.DHParameterSpec) DHParametersGenerator(org.bouncycastle.crypto.generators.DHParametersGenerator) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) AlgorithmParameters(java.security.AlgorithmParameters)

Aggregations

AlgorithmParameters (java.security.AlgorithmParameters)107 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)39 IOException (java.io.IOException)31 InvalidParameterSpecException (java.security.spec.InvalidParameterSpecException)22 Cipher (javax.crypto.Cipher)22 SecretKey (javax.crypto.SecretKey)18 AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)13 NoSuchProviderException (java.security.NoSuchProviderException)12 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)11 Key (java.security.Key)11 SecureRandom (java.security.SecureRandom)10 EncryptedPrivateKeyInfo (javax.crypto.EncryptedPrivateKeyInfo)10 InvalidKeyException (java.security.InvalidKeyException)8 PBEParameterSpec (javax.crypto.spec.PBEParameterSpec)8 UnrecoverableKeyException (java.security.UnrecoverableKeyException)7 KeyPair (java.security.KeyPair)6 KeyPairGenerator (java.security.KeyPairGenerator)6 AlgorithmId (sun.security.x509.AlgorithmId)6 Nullable (android.annotation.Nullable)5 Asn1Integer (com.android.hotspot2.asn1.Asn1Integer)5