Search in sources :

Example 1 with PKCS12KeyWithParameters

use of com.github.zhenwei.provider.jcajce.PKCS12KeyWithParameters in project LinLong-Java by zhenwei1108.

the class JceOpenSSLPKCS8EncryptorBuilder method build.

public OutputEncryptor build() throws OperatorCreationException {
    final AlgorithmIdentifier algID;
    if (random == null) {
        random = new SecureRandom();
    }
    try {
        this.cipher = helper.createCipher(algOID.getId());
        if (PEMUtilities.isPKCS5Scheme2(algOID)) {
            this.paramGen = helper.createAlgorithmParameterGenerator(algOID.getId());
        }
    } catch (GeneralSecurityException e) {
        throw new OperatorCreationException(algOID + " not available: " + e.getMessage(), e);
    }
    if (PEMUtilities.isPKCS5Scheme2(algOID)) {
        salt = new byte[PEMUtilities.getSaltSize(prf.getAlgorithm())];
        random.nextBytes(salt);
        params = paramGen.generateParameters();
        try {
            EncryptionScheme scheme = new EncryptionScheme(algOID, ASN1Primitive.fromByteArray(params.getEncoded()));
            KeyDerivationFunc func = new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, new PBKDF2Params(salt, iterationCount, prf));
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(func);
            v.add(scheme);
            algID = new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, PBES2Parameters.getInstance(new DERSequence(v)));
        } catch (IOException e) {
            throw new OperatorCreationException(e.getMessage(), e);
        }
        try {
            if (PEMUtilities.isHmacSHA1(prf)) {
                key = PEMUtilities.generateSecretKeyForPKCS5Scheme2(helper, algOID.getId(), password, salt, iterationCount);
            } else {
                key = PEMUtilities.generateSecretKeyForPKCS5Scheme2(helper, algOID.getId(), password, salt, iterationCount, prf);
            }
            cipher.init(Cipher.ENCRYPT_MODE, key, params);
        } catch (GeneralSecurityException e) {
            throw new OperatorCreationException(e.getMessage(), e);
        }
    } else if (PEMUtilities.isPKCS12(algOID)) {
        ASN1EncodableVector v = new ASN1EncodableVector();
        salt = new byte[20];
        random.nextBytes(salt);
        v.add(new DEROctetString(salt));
        v.add(new ASN1Integer(iterationCount));
        algID = new AlgorithmIdentifier(algOID, PKCS12PBEParams.getInstance(new DERSequence(v)));
        try {
            cipher.init(Cipher.ENCRYPT_MODE, new PKCS12KeyWithParameters(password, salt, iterationCount));
        } catch (GeneralSecurityException e) {
            throw new OperatorCreationException(e.getMessage(), e);
        }
    } else {
        throw new OperatorCreationException("unknown algorithm: " + algOID, null);
    }
    return new OutputEncryptor() {

        public AlgorithmIdentifier getAlgorithmIdentifier() {
            return algID;
        }

        public OutputStream getOutputStream(OutputStream encOut) {
            return new CipherOutputStream(encOut, cipher);
        }

        public GenericKey getKey() {
            return new JceGenericKey(algID, key);
        }
    };
}
Also used : EncryptionScheme(com.github.zhenwei.core.asn1.pkcs.EncryptionScheme) CipherOutputStream(com.github.zhenwei.provider.jcajce.io.CipherOutputStream) GeneralSecurityException(java.security.GeneralSecurityException) OutputStream(java.io.OutputStream) CipherOutputStream(com.github.zhenwei.provider.jcajce.io.CipherOutputStream) SecureRandom(java.security.SecureRandom) IOException(java.io.IOException) ASN1Integer(com.github.zhenwei.core.asn1.ASN1Integer) DEROctetString(com.github.zhenwei.core.asn1.DEROctetString) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) DERSequence(com.github.zhenwei.core.asn1.DERSequence) JceGenericKey(com.github.zhenwei.pkix.operator.jcajce.JceGenericKey) KeyDerivationFunc(com.github.zhenwei.core.asn1.pkcs.KeyDerivationFunc) PBKDF2Params(com.github.zhenwei.core.asn1.pkcs.PBKDF2Params) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector) OperatorCreationException(com.github.zhenwei.pkix.operator.OperatorCreationException) PKCS12KeyWithParameters(com.github.zhenwei.provider.jcajce.PKCS12KeyWithParameters) OutputEncryptor(com.github.zhenwei.pkix.operator.OutputEncryptor)

Example 2 with PKCS12KeyWithParameters

use of com.github.zhenwei.provider.jcajce.PKCS12KeyWithParameters in project LinLong-Java by zhenwei1108.

the class JcePKCSPBEInputDecryptorProviderBuilder method build.

public InputDecryptorProvider build(final char[] password) {
    return new InputDecryptorProvider() {

        private Cipher cipher;

        private AlgorithmIdentifier encryptionAlg;

        public InputDecryptor get(final AlgorithmIdentifier algorithmIdentifier) throws OperatorCreationException {
            SecretKey key;
            ASN1ObjectIdentifier algorithm = algorithmIdentifier.getAlgorithm();
            try {
                if (algorithm.on(PKCSObjectIdentifiers.pkcs_12PbeIds)) {
                    PKCS12PBEParams pbeParams = PKCS12PBEParams.getInstance(algorithmIdentifier.getParameters());
                    cipher = helper.createCipher(algorithm.getId());
                    cipher.init(Cipher.DECRYPT_MODE, new PKCS12KeyWithParameters(password, wrongPKCS12Zero, pbeParams.getIV(), pbeParams.getIterations().intValue()));
                    encryptionAlg = algorithmIdentifier;
                } else if (algorithm.equals(PKCSObjectIdentifiers.id_PBES2)) {
                    PBES2Parameters alg = PBES2Parameters.getInstance(algorithmIdentifier.getParameters());
                    if (MiscObjectIdentifiers.id_scrypt.equals(alg.getKeyDerivationFunc().getAlgorithm())) {
                        ScryptParams params = ScryptParams.getInstance(alg.getKeyDerivationFunc().getParameters());
                        AlgorithmIdentifier encScheme = AlgorithmIdentifier.getInstance(alg.getEncryptionScheme());
                        SecretKeyFactory keyFact = helper.createSecretKeyFactory("SCRYPT");
                        key = keyFact.generateSecret(new ScryptKeySpec(password, params.getSalt(), params.getCostParameter().intValue(), params.getBlockSize().intValue(), params.getParallelizationParameter().intValue(), keySizeProvider.getKeySize(encScheme)));
                    } else {
                        SecretKeyFactory keyFact = helper.createSecretKeyFactory(alg.getKeyDerivationFunc().getAlgorithm().getId());
                        PBKDF2Params func = PBKDF2Params.getInstance(alg.getKeyDerivationFunc().getParameters());
                        AlgorithmIdentifier encScheme = AlgorithmIdentifier.getInstance(alg.getEncryptionScheme());
                        if (func.isDefaultPrf()) {
                            key = keyFact.generateSecret(new PBEKeySpec(password, func.getSalt(), func.getIterationCount().intValue(), keySizeProvider.getKeySize(encScheme)));
                        } else {
                            key = keyFact.generateSecret(new PBKDF2KeySpec(password, func.getSalt(), func.getIterationCount().intValue(), keySizeProvider.getKeySize(encScheme), func.getPrf()));
                        }
                    }
                    cipher = helper.createCipher(alg.getEncryptionScheme().getAlgorithm().getId());
                    encryptionAlg = AlgorithmIdentifier.getInstance(alg.getEncryptionScheme());
                    ASN1Encodable encParams = alg.getEncryptionScheme().getParameters();
                    if (encParams instanceof ASN1OctetString) {
                        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ASN1OctetString.getInstance(encParams).getOctets()));
                    } else if (encParams instanceof ASN1Sequence && isCCMorGCM(alg.getEncryptionScheme())) {
                        AlgorithmParameters params = AlgorithmParameters.getInstance(alg.getEncryptionScheme().getAlgorithm().getId());
                        params.init(((ASN1Sequence) encParams).getEncoded());
                        cipher.init(Cipher.DECRYPT_MODE, key, params);
                    } else if (// absent parameters
                    encParams == null) {
                        cipher.init(Cipher.DECRYPT_MODE, key);
                    } else {
                        // TODO: at the moment it's just GOST, but...
                        GOST28147Parameters gParams = GOST28147Parameters.getInstance(encParams);
                        cipher.init(Cipher.DECRYPT_MODE, key, new GOST28147ParameterSpec(gParams.getEncryptionParamSet(), gParams.getIV()));
                    }
                } else if (algorithm.equals(PKCSObjectIdentifiers.pbeWithMD5AndDES_CBC) || algorithm.equals(PKCSObjectIdentifiers.pbeWithSHA1AndDES_CBC)) {
                    PBEParameter pbeParams = PBEParameter.getInstance(algorithmIdentifier.getParameters());
                    cipher = helper.createCipher(algorithm.getId());
                    cipher.init(Cipher.DECRYPT_MODE, new PBKDF1Key(password, PasswordConverter.ASCII), new PBEParameterSpec(pbeParams.getSalt(), pbeParams.getIterationCount().intValue()));
                } else {
                    throw new OperatorCreationException("unable to create InputDecryptor: algorithm " + algorithm + " unknown.");
                }
            } catch (Exception e) {
                throw new OperatorCreationException("unable to create InputDecryptor: " + e.getMessage(), e);
            }
            return new InputDecryptor() {

                public AlgorithmIdentifier getAlgorithmIdentifier() {
                    return encryptionAlg;
                }

                public InputStream getInputStream(InputStream input) {
                    return new CipherInputStream(input, cipher);
                }
            };
        }
    };
}
Also used : ASN1OctetString(com.github.zhenwei.core.asn1.ASN1OctetString) PBEKeySpec(javax.crypto.spec.PBEKeySpec) GOST28147Parameters(com.github.zhenwei.core.asn1.cryptopro.GOST28147Parameters) GOST28147ParameterSpec(com.github.zhenwei.provider.jcajce.spec.GOST28147ParameterSpec) PBKDF2KeySpec(com.github.zhenwei.provider.jcajce.spec.PBKDF2KeySpec) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) PBKDF1Key(com.github.zhenwei.provider.jcajce.PBKDF1Key) PBKDF2Params(com.github.zhenwei.core.asn1.pkcs.PBKDF2Params) ASN1Encodable(com.github.zhenwei.core.asn1.ASN1Encodable) OperatorCreationException(com.github.zhenwei.pkix.operator.OperatorCreationException) ScryptParams(com.github.zhenwei.core.asn1.misc.ScryptParams) SecretKeyFactory(javax.crypto.SecretKeyFactory) PKCS12KeyWithParameters(com.github.zhenwei.provider.jcajce.PKCS12KeyWithParameters) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec) PBEParameter(com.github.zhenwei.core.asn1.pkcs.PBEParameter) PBES2Parameters(com.github.zhenwei.core.asn1.pkcs.PBES2Parameters) CipherInputStream(com.github.zhenwei.provider.jcajce.io.CipherInputStream) InputDecryptor(com.github.zhenwei.pkix.operator.InputDecryptor) CipherInputStream(com.github.zhenwei.provider.jcajce.io.CipherInputStream) InputStream(java.io.InputStream) ScryptKeySpec(com.github.zhenwei.provider.jcajce.spec.ScryptKeySpec) OperatorCreationException(com.github.zhenwei.pkix.operator.OperatorCreationException) SecretKey(javax.crypto.SecretKey) ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence) InputDecryptorProvider(com.github.zhenwei.pkix.operator.InputDecryptorProvider) PKCS12PBEParams(com.github.zhenwei.core.asn1.pkcs.PKCS12PBEParams) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier) AlgorithmParameters(java.security.AlgorithmParameters)

Example 3 with PKCS12KeyWithParameters

use of com.github.zhenwei.provider.jcajce.PKCS12KeyWithParameters in project LinLong-Java by zhenwei1108.

the class JcePKCSPBEOutputEncryptorBuilder method build.

public OutputEncryptor build(final char[] password) throws OperatorCreationException {
    final Cipher cipher;
    SecretKey key;
    if (random == null) {
        random = new SecureRandom();
    }
    final AlgorithmIdentifier encryptionAlg;
    try {
        if (isPKCS12(algorithm)) {
            byte[] salt = new byte[20];
            random.nextBytes(salt);
            cipher = helper.createCipher(algorithm.getId());
            cipher.init(Cipher.ENCRYPT_MODE, new PKCS12KeyWithParameters(password, salt, iterationCount));
            encryptionAlg = new AlgorithmIdentifier(algorithm, new PKCS12PBEParams(salt, iterationCount));
        } else if (algorithm.equals(PKCSObjectIdentifiers.id_PBES2)) {
            PBKDFConfig pbkDef = (pbkdf == null) ? pbkdfBuilder.build() : pbkdf;
            if (MiscObjectIdentifiers.id_scrypt.equals(pbkDef.getAlgorithm())) {
                ScryptConfig skdf = (ScryptConfig) pbkDef;
                byte[] salt = new byte[skdf.getSaltLength()];
                random.nextBytes(salt);
                ScryptParams params = new ScryptParams(salt, skdf.getCostParameter(), skdf.getBlockSize(), skdf.getParallelizationParameter());
                SecretKeyFactory keyFact = helper.createSecretKeyFactory("SCRYPT");
                key = keyFact.generateSecret(new ScryptKeySpec(password, salt, skdf.getCostParameter(), skdf.getBlockSize(), skdf.getParallelizationParameter(), keySizeProvider.getKeySize(new AlgorithmIdentifier(keyEncAlgorithm))));
                cipher = helper.createCipher(keyEncAlgorithm.getId());
                cipher.init(Cipher.ENCRYPT_MODE, simplifyPbeKey(key), random);
                AlgorithmParameters algP = cipher.getParameters();
                PBES2Parameters algParams;
                if (algP != null) {
                    algParams = new PBES2Parameters(new KeyDerivationFunc(MiscObjectIdentifiers.id_scrypt, params), new EncryptionScheme(keyEncAlgorithm, ASN1Primitive.fromByteArray(cipher.getParameters().getEncoded())));
                } else {
                    algParams = new PBES2Parameters(new KeyDerivationFunc(MiscObjectIdentifiers.id_scrypt, params), new EncryptionScheme(keyEncAlgorithm));
                }
                encryptionAlg = new AlgorithmIdentifier(algorithm, algParams);
            } else {
                PBKDF2Config pkdf = (PBKDF2Config) pbkDef;
                byte[] salt = new byte[pkdf.getSaltLength()];
                random.nextBytes(salt);
                SecretKeyFactory keyFact = helper.createSecretKeyFactory(JceUtils.getAlgorithm(pkdf.getPRF().getAlgorithm()));
                key = keyFact.generateSecret(new PBEKeySpec(password, salt, pkdf.getIterationCount(), keySizeProvider.getKeySize(new AlgorithmIdentifier(keyEncAlgorithm))));
                cipher = helper.createCipher(keyEncAlgorithm.getId());
                cipher.init(Cipher.ENCRYPT_MODE, simplifyPbeKey(key), random);
                AlgorithmParameters algP = cipher.getParameters();
                PBES2Parameters algParams;
                if (algP != null) {
                    algParams = new PBES2Parameters(new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, new PBKDF2Params(salt, pkdf.getIterationCount(), pkdf.getPRF())), new EncryptionScheme(keyEncAlgorithm, ASN1Primitive.fromByteArray(cipher.getParameters().getEncoded())));
                } else {
                    algParams = new PBES2Parameters(new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, new PBKDF2Params(salt, pkdf.getIterationCount(), pkdf.getPRF())), new EncryptionScheme(keyEncAlgorithm));
                }
                encryptionAlg = new AlgorithmIdentifier(algorithm, algParams);
            }
        } else {
            throw new OperatorCreationException("unrecognised algorithm");
        }
        return new OutputEncryptor() {

            public AlgorithmIdentifier getAlgorithmIdentifier() {
                return encryptionAlg;
            }

            public OutputStream getOutputStream(OutputStream out) {
                return new CipherOutputStream(out, cipher);
            }

            public GenericKey getKey() {
                if (isPKCS12(encryptionAlg.getAlgorithm())) {
                    return new GenericKey(encryptionAlg, PKCS12PasswordToBytes(password));
                } else {
                    return new GenericKey(encryptionAlg, PKCS5PasswordToBytes(password));
                }
            }
        };
    } catch (Exception e) {
        throw new OperatorCreationException("unable to create OutputEncryptor: " + e.getMessage(), e);
    }
}
Also used : PBKDF2Config(com.github.zhenwei.core.crypto.util.PBKDF2Config) PBEKeySpec(javax.crypto.spec.PBEKeySpec) EncryptionScheme(com.github.zhenwei.core.asn1.pkcs.EncryptionScheme) CipherOutputStream(com.github.zhenwei.provider.jcajce.io.CipherOutputStream) OutputStream(java.io.OutputStream) CipherOutputStream(com.github.zhenwei.provider.jcajce.io.CipherOutputStream) ScryptConfig(com.github.zhenwei.core.crypto.util.ScryptConfig) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) KeyDerivationFunc(com.github.zhenwei.core.asn1.pkcs.KeyDerivationFunc) PBKDF2Params(com.github.zhenwei.core.asn1.pkcs.PBKDF2Params) GenericKey(com.github.zhenwei.pkix.operator.GenericKey) OperatorCreationException(com.github.zhenwei.pkix.operator.OperatorCreationException) ScryptParams(com.github.zhenwei.core.asn1.misc.ScryptParams) SecretKeyFactory(javax.crypto.SecretKeyFactory) PKCS12KeyWithParameters(com.github.zhenwei.provider.jcajce.PKCS12KeyWithParameters) PBKDFConfig(com.github.zhenwei.core.crypto.util.PBKDFConfig) PBES2Parameters(com.github.zhenwei.core.asn1.pkcs.PBES2Parameters) SecureRandom(java.security.SecureRandom) ScryptKeySpec(com.github.zhenwei.provider.jcajce.spec.ScryptKeySpec) OperatorCreationException(com.github.zhenwei.pkix.operator.OperatorCreationException) SecretKey(javax.crypto.SecretKey) PKCS12PBEParams(com.github.zhenwei.core.asn1.pkcs.PKCS12PBEParams) Cipher(javax.crypto.Cipher) OutputEncryptor(com.github.zhenwei.pkix.operator.OutputEncryptor) AlgorithmParameters(java.security.AlgorithmParameters)

Example 4 with PKCS12KeyWithParameters

use of com.github.zhenwei.provider.jcajce.PKCS12KeyWithParameters in project LinLong-Java by zhenwei1108.

the class BaseBlockCipher method engineInit.

protected void engineInit(int opmode, Key key, final AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
    CipherParameters param;
    this.pbeSpec = null;
    this.pbeAlgorithm = null;
    this.engineParams = null;
    this.aeadParams = null;
    // 
    if (!(key instanceof SecretKey)) {
        throw new InvalidKeyException("Key for algorithm " + ((key != null) ? key.getAlgorithm() : null) + " not suitable for symmetric enryption.");
    }
    // 
    if (params == null && (baseEngine != null && baseEngine.getAlgorithmName().startsWith("RC5-64"))) {
        throw new InvalidAlgorithmParameterException("RC5 requires an RC5ParametersSpec to be passed in.");
    }
    // 
    if (scheme == PKCS12 || key instanceof PKCS12Key) {
        SecretKey k;
        try {
            k = (SecretKey) key;
        } catch (Exception e) {
            throw new InvalidKeyException("PKCS12 requires a SecretKey/PBEKey");
        }
        if (params instanceof PBEParameterSpec) {
            pbeSpec = (PBEParameterSpec) params;
        }
        if (k instanceof PBEKey && pbeSpec == null) {
            PBEKey pbeKey = (PBEKey) k;
            if (pbeKey.getSalt() == null) {
                throw new InvalidAlgorithmParameterException("PBEKey requires parameters to specify salt");
            }
            pbeSpec = new PBEParameterSpec(pbeKey.getSalt(), pbeKey.getIterationCount());
        }
        if (pbeSpec == null && !(k instanceof PBEKey)) {
            throw new InvalidKeyException("Algorithm requires a PBE key");
        }
        if (key instanceof BCPBEKey) {
            // PKCS#12 sets an IV, if we get a key that doesn't have ParametersWithIV we need to reject it. If the
            // key has no parameters it means it's an old-school JCE PBE Key - we use getEncoded() on it.
            CipherParameters pbeKeyParam = ((BCPBEKey) key).getParam();
            if (pbeKeyParam instanceof ParametersWithIV) {
                param = pbeKeyParam;
            } else if (pbeKeyParam == null) {
                param = Util.makePBEParameters(k.getEncoded(), PKCS12, digest, keySizeInBits, ivLength * 8, pbeSpec, cipher.getAlgorithmName());
            } else {
                throw new InvalidKeyException("Algorithm requires a PBE key suitable for PKCS12");
            }
        } else {
            param = Util.makePBEParameters(k.getEncoded(), PKCS12, digest, keySizeInBits, ivLength * 8, pbeSpec, cipher.getAlgorithmName());
        }
        if (param instanceof ParametersWithIV) {
            ivParam = (ParametersWithIV) param;
        }
    } else if (key instanceof PBKDF1Key) {
        PBKDF1Key k = (PBKDF1Key) key;
        if (params instanceof PBEParameterSpec) {
            pbeSpec = (PBEParameterSpec) params;
        }
        if (k instanceof PBKDF1KeyWithParameters && pbeSpec == null) {
            pbeSpec = new PBEParameterSpec(((PBKDF1KeyWithParameters) k).getSalt(), ((PBKDF1KeyWithParameters) k).getIterationCount());
        }
        param = Util.makePBEParameters(k.getEncoded(), PKCS5S1, digest, keySizeInBits, ivLength * 8, pbeSpec, cipher.getAlgorithmName());
        if (param instanceof ParametersWithIV) {
            ivParam = (ParametersWithIV) param;
        }
    } else if (key instanceof BCPBEKey) {
        BCPBEKey k = (BCPBEKey) key;
        if (k.getOID() != null) {
            pbeAlgorithm = k.getOID().getId();
        } else {
            pbeAlgorithm = k.getAlgorithm();
        }
        if (k.getParam() != null) {
            param = adjustParameters(params, k.getParam());
        } else if (params instanceof PBEParameterSpec) {
            pbeSpec = (PBEParameterSpec) params;
            param = Util.makePBEParameters(k, params, cipher.getUnderlyingCipher().getAlgorithmName());
        } else {
            throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set.");
        }
        if (param instanceof ParametersWithIV) {
            ivParam = (ParametersWithIV) param;
        }
    } else if (key instanceof PBEKey) {
        PBEKey k = (PBEKey) key;
        pbeSpec = (PBEParameterSpec) params;
        if (k instanceof PKCS12KeyWithParameters && pbeSpec == null) {
            pbeSpec = new PBEParameterSpec(k.getSalt(), k.getIterationCount());
        }
        param = Util.makePBEParameters(k.getEncoded(), scheme, digest, keySizeInBits, ivLength * 8, pbeSpec, cipher.getAlgorithmName());
        if (param instanceof ParametersWithIV) {
            ivParam = (ParametersWithIV) param;
        }
    } else if (!(key instanceof RepeatedSecretKeySpec)) {
        if (scheme == PKCS5S1 || scheme == PKCS5S1_UTF8 || scheme == PKCS5S2 || scheme == PKCS5S2_UTF8) {
            throw new InvalidKeyException("Algorithm requires a PBE key");
        }
        param = new KeyParameter(key.getEncoded());
    } else {
        param = null;
    }
    if (params instanceof AEADParameterSpec) {
        if (!isAEADModeName(modeName) && !(cipher instanceof AEADGenericBlockCipher)) {
            throw new InvalidAlgorithmParameterException("AEADParameterSpec can only be used with AEAD modes.");
        }
        AEADParameterSpec aeadSpec = (AEADParameterSpec) params;
        KeyParameter keyParam;
        if (param instanceof ParametersWithIV) {
            keyParam = (KeyParameter) ((ParametersWithIV) param).getParameters();
        } else {
            keyParam = (KeyParameter) param;
        }
        param = aeadParams = new AEADParameters(keyParam, aeadSpec.getMacSizeInBits(), aeadSpec.getNonce(), aeadSpec.getAssociatedData());
    } else if (params instanceof IvParameterSpec) {
        if (ivLength != 0) {
            IvParameterSpec p = (IvParameterSpec) params;
            if (p.getIV().length != ivLength && !(cipher instanceof AEADGenericBlockCipher) && fixedIv) {
                throw new InvalidAlgorithmParameterException("IV must be " + ivLength + " bytes long.");
            }
            if (param instanceof ParametersWithIV) {
                param = new ParametersWithIV(((ParametersWithIV) param).getParameters(), p.getIV());
            } else {
                param = new ParametersWithIV(param, p.getIV());
            }
            ivParam = (ParametersWithIV) param;
        } else {
            if (modeName != null && modeName.equals("ECB")) {
                throw new InvalidAlgorithmParameterException("ECB mode does not use an IV");
            }
        }
    } else if (params instanceof GOST28147ParameterSpec) {
        GOST28147ParameterSpec gost28147Param = (GOST28147ParameterSpec) params;
        param = new ParametersWithSBox(new KeyParameter(key.getEncoded()), ((GOST28147ParameterSpec) params).getSbox());
        if (gost28147Param.getIV() != null && ivLength != 0) {
            if (param instanceof ParametersWithIV) {
                param = new ParametersWithIV(((ParametersWithIV) param).getParameters(), gost28147Param.getIV());
            } else {
                param = new ParametersWithIV(param, gost28147Param.getIV());
            }
            ivParam = (ParametersWithIV) param;
        }
    } else if (params instanceof RC2ParameterSpec) {
        RC2ParameterSpec rc2Param = (RC2ParameterSpec) params;
        param = new RC2Parameters(key.getEncoded(), ((RC2ParameterSpec) params).getEffectiveKeyBits());
        if (rc2Param.getIV() != null && ivLength != 0) {
            if (param instanceof ParametersWithIV) {
                param = new ParametersWithIV(((ParametersWithIV) param).getParameters(), rc2Param.getIV());
            } else {
                param = new ParametersWithIV(param, rc2Param.getIV());
            }
            ivParam = (ParametersWithIV) param;
        }
    } else if (params instanceof RC5ParameterSpec) {
        RC5ParameterSpec rc5Param = (RC5ParameterSpec) params;
        param = new RC5Parameters(key.getEncoded(), ((RC5ParameterSpec) params).getRounds());
        if (baseEngine.getAlgorithmName().startsWith("RC5")) {
            if (baseEngine.getAlgorithmName().equals("RC5-32")) {
                if (rc5Param.getWordSize() != 32) {
                    throw new InvalidAlgorithmParameterException("RC5 already set up for a word size of 32 not " + rc5Param.getWordSize() + ".");
                }
            } else if (baseEngine.getAlgorithmName().equals("RC5-64")) {
                if (rc5Param.getWordSize() != 64) {
                    throw new InvalidAlgorithmParameterException("RC5 already set up for a word size of 64 not " + rc5Param.getWordSize() + ".");
                }
            }
        } else {
            throw new InvalidAlgorithmParameterException("RC5 parameters passed to a cipher that is not RC5.");
        }
        if ((rc5Param.getIV() != null) && (ivLength != 0)) {
            if (param instanceof ParametersWithIV) {
                param = new ParametersWithIV(((ParametersWithIV) param).getParameters(), rc5Param.getIV());
            } else {
                param = new ParametersWithIV(param, rc5Param.getIV());
            }
            ivParam = (ParametersWithIV) param;
        }
    } else if (params instanceof FPEParameterSpec) {
        FPEParameterSpec spec = (FPEParameterSpec) params;
        param = new FPEParameters((KeyParameter) param, spec.getRadix(), spec.getTweak(), spec.isUsingInverseFunction());
    } else if (gcmSpecClass != null && gcmSpecClass.isInstance(params)) {
        if (!isAEADModeName(modeName) && !(cipher instanceof AEADGenericBlockCipher)) {
            throw new InvalidAlgorithmParameterException("GCMParameterSpec can only be used with AEAD modes.");
        }
        final KeyParameter keyParam;
        if (param instanceof ParametersWithIV) {
            keyParam = (KeyParameter) ((ParametersWithIV) param).getParameters();
        } else {
            keyParam = (KeyParameter) param;
        }
        param = aeadParams = GcmSpecUtil.extractAeadParameters(keyParam, params);
    } else if (params != null && !(params instanceof PBEParameterSpec)) {
        throw new InvalidAlgorithmParameterException("unknown parameter type.");
    }
    if ((ivLength != 0) && !(param instanceof ParametersWithIV) && !(param instanceof AEADParameters)) {
        SecureRandom ivRandom = random;
        if (ivRandom == null) {
            ivRandom = CryptoServicesRegistrar.getSecureRandom();
        }
        if ((opmode == Cipher.ENCRYPT_MODE) || (opmode == Cipher.WRAP_MODE)) {
            byte[] iv = new byte[ivLength];
            ivRandom.nextBytes(iv);
            param = new ParametersWithIV(param, iv);
            ivParam = (ParametersWithIV) param;
        } else if (cipher.getUnderlyingCipher().getAlgorithmName().indexOf("PGPCFB") < 0) {
            throw new InvalidAlgorithmParameterException("no IV set when one expected");
        }
    }
    if (random != null && padded) {
        param = new ParametersWithRandom(param, random);
    }
    try {
        switch(opmode) {
            case Cipher.ENCRYPT_MODE:
            case Cipher.WRAP_MODE:
                cipher.init(true, param);
                break;
            case Cipher.DECRYPT_MODE:
            case Cipher.UNWRAP_MODE:
                cipher.init(false, param);
                break;
            default:
                throw new InvalidParameterException("unknown opmode " + opmode + " passed");
        }
        if (cipher instanceof AEADGenericBlockCipher && aeadParams == null) {
            AEADCipher aeadCipher = ((AEADGenericBlockCipher) cipher).cipher;
            aeadParams = new AEADParameters((KeyParameter) ivParam.getParameters(), aeadCipher.getMac().length * 8, ivParam.getIV());
        }
    } catch (IllegalArgumentException e) {
        throw new InvalidAlgorithmParameterException(e.getMessage(), e);
    } catch (Exception e) {
        throw new InvalidKeyOrParametersException(e.getMessage(), e);
    }
}
Also used : RepeatedSecretKeySpec(com.github.zhenwei.provider.jcajce.spec.RepeatedSecretKeySpec) PBKDF1KeyWithParameters(com.github.zhenwei.provider.jcajce.PBKDF1KeyWithParameters) KeyParameter(com.github.zhenwei.core.crypto.params.KeyParameter) GOST28147ParameterSpec(com.github.zhenwei.provider.jcajce.spec.GOST28147ParameterSpec) PBEKey(javax.crypto.interfaces.PBEKey) AEADCipher(com.github.zhenwei.core.crypto.modes.AEADCipher) RC5ParameterSpec(javax.crypto.spec.RC5ParameterSpec) InvalidParameterException(java.security.InvalidParameterException) PBKDF1Key(com.github.zhenwei.provider.jcajce.PBKDF1Key) RC5Parameters(com.github.zhenwei.core.crypto.params.RC5Parameters) RC2ParameterSpec(javax.crypto.spec.RC2ParameterSpec) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec) PKCS12KeyWithParameters(com.github.zhenwei.provider.jcajce.PKCS12KeyWithParameters) FPEParameters(com.github.zhenwei.core.crypto.params.FPEParameters) RC2Parameters(com.github.zhenwei.core.crypto.params.RC2Parameters) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) SecureRandom(java.security.SecureRandom) ParametersWithRandom(com.github.zhenwei.core.crypto.params.ParametersWithRandom) InvalidKeyException(java.security.InvalidKeyException) OutputLengthException(com.github.zhenwei.core.crypto.OutputLengthException) InvalidParameterException(java.security.InvalidParameterException) InvalidCipherTextException(com.github.zhenwei.core.crypto.InvalidCipherTextException) ShortBufferException(javax.crypto.ShortBufferException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) BadPaddingException(javax.crypto.BadPaddingException) DataLengthException(com.github.zhenwei.core.crypto.DataLengthException) AEADParameterSpec(com.github.zhenwei.provider.jcajce.spec.AEADParameterSpec) CipherParameters(com.github.zhenwei.core.crypto.CipherParameters) ParametersWithIV(com.github.zhenwei.core.crypto.params.ParametersWithIV) SecretKey(javax.crypto.SecretKey) AEADParameters(com.github.zhenwei.core.crypto.params.AEADParameters) FPEParameterSpec(com.github.zhenwei.provider.jcajce.spec.FPEParameterSpec) ParametersWithSBox(com.github.zhenwei.core.crypto.params.ParametersWithSBox) IvParameterSpec(javax.crypto.spec.IvParameterSpec) PKCS12Key(com.github.zhenwei.provider.jcajce.PKCS12Key)

Example 5 with PKCS12KeyWithParameters

use of com.github.zhenwei.provider.jcajce.PKCS12KeyWithParameters in project LinLong-Java by zhenwei1108.

the class BaseStreamCipher method engineInit.

protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
    CipherParameters param;
    this.pbeSpec = null;
    this.pbeAlgorithm = null;
    this.engineParams = null;
    // 
    if (!(key instanceof SecretKey)) {
        throw new InvalidKeyException("Key for algorithm " + key.getAlgorithm() + " not suitable for symmetric enryption.");
    }
    if (key instanceof PKCS12Key) {
        PKCS12Key k = (PKCS12Key) key;
        pbeSpec = (PBEParameterSpec) params;
        if (k instanceof PKCS12KeyWithParameters && pbeSpec == null) {
            pbeSpec = new PBEParameterSpec(((PKCS12KeyWithParameters) k).getSalt(), ((PKCS12KeyWithParameters) k).getIterationCount());
        }
        param = Util.makePBEParameters(k.getEncoded(), PKCS12, digest, keySizeInBits, ivLength * 8, pbeSpec, cipher.getAlgorithmName());
    } else if (key instanceof BCPBEKey) {
        BCPBEKey k = (BCPBEKey) key;
        if (k.getOID() != null) {
            pbeAlgorithm = k.getOID().getId();
        } else {
            pbeAlgorithm = k.getAlgorithm();
        }
        if (k.getParam() != null) {
            param = k.getParam();
            pbeSpec = new PBEParameterSpec(k.getSalt(), k.getIterationCount());
        } else if (params instanceof PBEParameterSpec) {
            param = Util.makePBEParameters(k, params, cipher.getAlgorithmName());
            pbeSpec = (PBEParameterSpec) params;
        } else {
            throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set.");
        }
        if (k.getIvSize() != 0) {
            ivParam = (ParametersWithIV) param;
        }
    } else if (params == null) {
        if (digest > 0) {
            throw new InvalidKeyException("Algorithm requires a PBE key");
        }
        param = new KeyParameter(key.getEncoded());
    } else if (params instanceof IvParameterSpec) {
        param = new ParametersWithIV(new KeyParameter(key.getEncoded()), ((IvParameterSpec) params).getIV());
        ivParam = (ParametersWithIV) param;
    } else {
        throw new InvalidAlgorithmParameterException("unknown parameter type.");
    }
    if ((ivLength != 0) && !(param instanceof ParametersWithIV)) {
        SecureRandom ivRandom = random;
        if (ivRandom == null) {
            ivRandom = CryptoServicesRegistrar.getSecureRandom();
        }
        if ((opmode == Cipher.ENCRYPT_MODE) || (opmode == Cipher.WRAP_MODE)) {
            byte[] iv = new byte[ivLength];
            ivRandom.nextBytes(iv);
            param = new ParametersWithIV(param, iv);
            ivParam = (ParametersWithIV) param;
        } else {
            throw new InvalidAlgorithmParameterException("no IV set when one expected");
        }
    }
    try {
        switch(opmode) {
            case Cipher.ENCRYPT_MODE:
            case Cipher.WRAP_MODE:
                cipher.init(true, param);
                break;
            case Cipher.DECRYPT_MODE:
            case Cipher.UNWRAP_MODE:
                cipher.init(false, param);
                break;
            default:
                throw new InvalidParameterException("unknown opmode " + opmode + " passed");
        }
    } catch (Exception e) {
        throw new InvalidKeyException(e.getMessage());
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) KeyParameter(com.github.zhenwei.core.crypto.params.KeyParameter) SecureRandom(java.security.SecureRandom) InvalidKeyException(java.security.InvalidKeyException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) InvalidParameterException(java.security.InvalidParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) DataLengthException(com.github.zhenwei.core.crypto.DataLengthException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) ShortBufferException(javax.crypto.ShortBufferException) CipherParameters(com.github.zhenwei.core.crypto.CipherParameters) ParametersWithIV(com.github.zhenwei.core.crypto.params.ParametersWithIV) InvalidParameterException(java.security.InvalidParameterException) SecretKey(javax.crypto.SecretKey) IvParameterSpec(javax.crypto.spec.IvParameterSpec) PKCS12Key(com.github.zhenwei.provider.jcajce.PKCS12Key) PKCS12KeyWithParameters(com.github.zhenwei.provider.jcajce.PKCS12KeyWithParameters) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec)

Aggregations

PKCS12KeyWithParameters (com.github.zhenwei.provider.jcajce.PKCS12KeyWithParameters)6 SecretKey (javax.crypto.SecretKey)5 PBKDF2Params (com.github.zhenwei.core.asn1.pkcs.PBKDF2Params)4 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)4 OperatorCreationException (com.github.zhenwei.pkix.operator.OperatorCreationException)4 SecureRandom (java.security.SecureRandom)4 EncryptionScheme (com.github.zhenwei.core.asn1.pkcs.EncryptionScheme)3 KeyDerivationFunc (com.github.zhenwei.core.asn1.pkcs.KeyDerivationFunc)3 PBES2Parameters (com.github.zhenwei.core.asn1.pkcs.PBES2Parameters)3 PKCS12PBEParams (com.github.zhenwei.core.asn1.pkcs.PKCS12PBEParams)3 AlgorithmParameters (java.security.AlgorithmParameters)3 Cipher (javax.crypto.Cipher)3 IvParameterSpec (javax.crypto.spec.IvParameterSpec)3 ScryptParams (com.github.zhenwei.core.asn1.misc.ScryptParams)2 PBEParameter (com.github.zhenwei.core.asn1.pkcs.PBEParameter)2 CipherParameters (com.github.zhenwei.core.crypto.CipherParameters)2 DataLengthException (com.github.zhenwei.core.crypto.DataLengthException)2 KeyParameter (com.github.zhenwei.core.crypto.params.KeyParameter)2 ParametersWithIV (com.github.zhenwei.core.crypto.params.ParametersWithIV)2 PBKDF1KeyWithParameters (com.github.zhenwei.provider.jcajce.PBKDF1KeyWithParameters)2