Search in sources :

Example 6 with PBEParameterSpec

use of javax.crypto.spec.PBEParameterSpec in project robovm by robovm.

the class PKCS12KeyStoreSpi method cryptData.

protected byte[] cryptData(boolean forEncryption, AlgorithmIdentifier algId, char[] password, boolean wrongPKCS12Zero, byte[] data) throws IOException {
    String algorithm = algId.getAlgorithm().getId();
    PKCS12PBEParams pbeParams = PKCS12PBEParams.getInstance(algId.getParameters());
    PBEKeySpec pbeSpec = new PBEKeySpec(password);
    try {
        SecretKeyFactory keyFact = SecretKeyFactory.getInstance(algorithm, bcProvider);
        PBEParameterSpec defParams = new PBEParameterSpec(pbeParams.getIV(), pbeParams.getIterations().intValue());
        BCPBEKey key = (BCPBEKey) keyFact.generateSecret(pbeSpec);
        key.setTryWrongPKCS12Zero(wrongPKCS12Zero);
        Cipher cipher = Cipher.getInstance(algorithm, bcProvider);
        int mode = forEncryption ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE;
        cipher.init(mode, key, defParams);
        return cipher.doFinal(data);
    } catch (Exception e) {
        throw new IOException("exception decrypting data - " + e.toString());
    }
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) PKCS12PBEParams(org.bouncycastle.asn1.pkcs.PKCS12PBEParams) BCPBEKey(org.bouncycastle.jcajce.provider.symmetric.util.BCPBEKey) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERBMPString(org.bouncycastle.asn1.DERBMPString) DEROctetString(org.bouncycastle.asn1.DEROctetString) BEROctetString(org.bouncycastle.asn1.BEROctetString) Cipher(javax.crypto.Cipher) IOException(java.io.IOException) SecretKeyFactory(javax.crypto.SecretKeyFactory) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException)

Example 7 with PBEParameterSpec

use of javax.crypto.spec.PBEParameterSpec in project robovm by robovm.

the class BaseMac method engineInit.

protected void engineInit(Key key, AlgorithmParameterSpec params) throws InvalidKeyException, InvalidAlgorithmParameterException {
    CipherParameters param;
    if (key == null) {
        throw new InvalidKeyException("key is null");
    }
    if (key instanceof BCPBEKey) {
        BCPBEKey k = (BCPBEKey) key;
        if (k.getParam() != null) {
            param = k.getParam();
        } else if (params instanceof PBEParameterSpec) {
            param = PBE.Util.makePBEMacParameters(k, params);
        } else {
            throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set.");
        }
    } else if (params instanceof IvParameterSpec) {
        param = new ParametersWithIV(new KeyParameter(key.getEncoded()), ((IvParameterSpec) params).getIV());
    } else if (params == null) {
        param = new KeyParameter(key.getEncoded());
    } else {
        throw new InvalidAlgorithmParameterException("unknown parameter type.");
    }
    macEngine.init(param);
}
Also used : CipherParameters(org.bouncycastle.crypto.CipherParameters) ParametersWithIV(org.bouncycastle.crypto.params.ParametersWithIV) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) KeyParameter(org.bouncycastle.crypto.params.KeyParameter) IvParameterSpec(javax.crypto.spec.IvParameterSpec) InvalidKeyException(java.security.InvalidKeyException) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec)

Example 8 with PBEParameterSpec

use of javax.crypto.spec.PBEParameterSpec in project robovm by robovm.

the class CipherPBEThread method crypt.

@Override
public void crypt() throws Exception {
    byte[] output = new byte[128];
    byte[] decrypted = new byte[128];
    byte[] input = getData().getBytes();
    byte[] salt = new byte[8];
    SecureRandom sr = new SecureRandom();
    PBEKeySpec keySpec = new PBEKeySpec("top sicret password".toCharArray());
    SecretKeyFactory skf = SecretKeyFactory.getInstance(getAlgName());
    SecretKey key = skf.generateSecret(keySpec);
    Cipher cip = Cipher.getInstance(getAlgName() + "/" + getMode() + "/" + getPadding());
    sr.nextBytes(salt);
    PBEParameterSpec parSpec = new PBEParameterSpec(salt, getKeyLength());
    cip.init(Cipher.ENCRYPT_MODE, key, parSpec);
    cip.doFinal(input, 0, input.length, output);
    int outputSize = cip.getOutputSize(input.length);
    cip.init(Cipher.DECRYPT_MODE, key, parSpec);
    cip.doFinal(output, 0, outputSize, decrypted);
    checkEncodedData(getData().getBytes(), decrypted);
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKey(javax.crypto.SecretKey) SecureRandom(java.security.SecureRandom) Cipher(javax.crypto.Cipher) SecretKeyFactory(javax.crypto.SecretKeyFactory) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec)

Example 9 with PBEParameterSpec

use of javax.crypto.spec.PBEParameterSpec in project robovm by robovm.

the class PBEParameterSpecTest method testGetIterationCount.

/**
     * getIterationCount() method testing. Tests that returned value is equal
     * to the value specified in the constructor.
     */
public void testGetIterationCount() {
    byte[] salt = new byte[] { 1, 2, 3, 4, 5 };
    int iterationCount = 10;
    PBEParameterSpec pbeps = new PBEParameterSpec(salt, iterationCount);
    assertTrue("The returned iterationCount is not equal to the specified " + "in the constructor.", pbeps.getIterationCount() == iterationCount);
}
Also used : PBEParameterSpec(javax.crypto.spec.PBEParameterSpec)

Example 10 with PBEParameterSpec

use of javax.crypto.spec.PBEParameterSpec 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)

Aggregations

PBEParameterSpec (javax.crypto.spec.PBEParameterSpec)56 SecretKey (javax.crypto.SecretKey)35 Cipher (javax.crypto.Cipher)32 PBEKeySpec (javax.crypto.spec.PBEKeySpec)31 SecretKeyFactory (javax.crypto.SecretKeyFactory)26 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)13 IvParameterSpec (javax.crypto.spec.IvParameterSpec)13 KeyStoreException (java.security.KeyStoreException)11 UnrecoverableKeyException (java.security.UnrecoverableKeyException)11 CertificateException (java.security.cert.CertificateException)11 InvalidKeyException (java.security.InvalidKeyException)10 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)9 CipherParameters (org.bouncycastle.crypto.CipherParameters)9 KeyParameter (org.bouncycastle.crypto.params.KeyParameter)9 ParametersWithIV (org.bouncycastle.crypto.params.ParametersWithIV)9 IOException (java.io.IOException)8 AlgorithmParameters (java.security.AlgorithmParameters)8 SecureRandom (java.security.SecureRandom)8 CertificateEncodingException (java.security.cert.CertificateEncodingException)8 AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)7