Java 类org.bouncycastle.asn1.pkcs.EncryptionScheme 实例源码

项目:Aki-SSL    文件:JcePKCSPBEOutputEncryptorBuilder.java   
public OutputEncryptor build(final char[] password)
    throws OperatorCreationException
{
    final Cipher cipher;
    SecretKey key;

    if (random == null)
    {
        random = new SecureRandom();
    }

    final AlgorithmIdentifier encryptionAlg;
    final byte[] salt = new byte[20];

    random.nextBytes(salt);

    try
    {
        if (algorithm.on(PKCSObjectIdentifiers.pkcs_12PbeIds))
        {
            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))
        {
            SecretKeyFactory keyFact = helper.createSecretKeyFactory(PKCSObjectIdentifiers.id_PBKDF2.getId());

            key = keyFact.generateSecret(new PBEKeySpec(password, salt, iterationCount, keySizeProvider.getKeySize(new AlgorithmIdentifier(keyEncAlgorithm))));

            cipher = helper.createCipher(keyEncAlgorithm.getId());

            cipher.init(Cipher.ENCRYPT_MODE, key, random);

            PBES2Parameters algParams = new PBES2Parameters(
                               new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, new PBKDF2Params(salt, iterationCount)),
                               new EncryptionScheme(keyEncAlgorithm, ASN1Primitive.fromByteArray(cipher.getParameters().getEncoded())));

            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, PKCS5PasswordToBytes(password));
                }
                else
                {
                    return new GenericKey(encryptionAlg, PKCS12PasswordToBytes(password));
                }
            }
        };
    }
    catch (Exception e)
    {
        throw new OperatorCreationException("unable to create OutputEncryptor: " + e.getMessage(), e);
    }
}