Search in sources :

Example 11 with PBEKeySpec

use of javax.crypto.spec.PBEKeySpec in project nhin-d by DirectProject.

the class CertGenerator method writeCertAndKey.

private static void writeCertAndKey(X509Certificate cert, PrivateKey key, CertCreateFields fields) throws Exception {
    // write the cert
    FileUtils.writeByteArrayToFile(fields.getNewCertFile(), cert.getEncoded());
    if (fields.getNewPassword() == null || fields.getNewPassword().length == 0) {
        // no password... just write the file 
        FileUtils.writeByteArrayToFile(fields.getNewKeyFile(), key.getEncoded());
    } else {
        // encypt it, then write it
        // prime the salts
        byte[] salt = new byte[8];
        VMPCRandomGenerator ranGen = new VMPCRandomGenerator();
        ranGen.addSeedMaterial(new SecureRandom().nextLong());
        ranGen.nextBytes(salt);
        // create PBE parameters from salt and iteration count
        PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20);
        PBEKeySpec pbeKeySpec = new PBEKeySpec(fields.getNewPassword());
        SecretKey sKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES", CryptoExtensions.getJCEProviderName()).generateSecret(pbeKeySpec);
        // encrypt
        Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES", CryptoExtensions.getJCEProviderName());
        cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec, null);
        byte[] plain = (byte[]) key.getEncoded();
        byte[] encrKey = cipher.doFinal(plain, 0, plain.length);
        // set the algorithm parameters
        AlgorithmParameters pbeParams = AlgorithmParameters.getInstance(PBE_WITH_MD5_AND_DES_CBC_OID, Security.getProvider("SunJCE"));
        pbeParams.init(pbeSpec);
        // place in a EncryptedPrivateKeyInfo to encode to the proper file format
        EncryptedPrivateKeyInfo info = new EncryptedPrivateKeyInfo(pbeParams, encrKey);
        // now write it to the file
        FileUtils.writeByteArrayToFile(fields.getNewKeyFile(), info.getEncoded());
    }
    if (fields.getSignerCert() == null)
        fields.setSignerCert(cert);
    if (fields.getSignerKey() == null)
        fields.setSignerKey(key);
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKey(javax.crypto.SecretKey) VMPCRandomGenerator(org.bouncycastle.crypto.prng.VMPCRandomGenerator) SecureRandom(java.security.SecureRandom) EncryptedPrivateKeyInfo(javax.crypto.EncryptedPrivateKeyInfo) Cipher(javax.crypto.Cipher) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec) AlgorithmParameters(java.security.AlgorithmParameters)

Example 12 with PBEKeySpec

use of javax.crypto.spec.PBEKeySpec in project nhin-d by DirectProject.

the class CertLoader method loadCertificate.

public static CertCreateFields loadCertificate(File certFile, File keyFile, char[] password) throws Exception {
    byte[] certData = loadFileData(certFile);
    byte[] keyData = loadFileData(keyFile);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    InputStream inStr = new ByteArrayInputStream(certData);
    java.security.cert.Certificate holdCert = cf.generateCertificate(inStr);
    X509Certificate cert = (X509Certificate) holdCert;
    IOUtils.closeQuietly(inStr);
    KeyFactory kf = KeyFactory.getInstance("RSA", CryptoExtensions.getJCEProviderName());
    PKCS8EncodedKeySpec keysp = null;
    if (password != null && password.length > 0) {
        EncryptedPrivateKeyInfo encInfo = new EncryptedPrivateKeyInfo(keyData);
        PBEKeySpec keySpec = new PBEKeySpec(password);
        String alg = encInfo.getAlgName();
        SecretKeyFactory secFactory = SecretKeyFactory.getInstance(alg, CryptoExtensions.getJCEProviderName());
        SecretKey secKey = secFactory.generateSecret(keySpec);
        keysp = encInfo.getKeySpec(secKey, CryptoExtensions.getJCEProviderName());
    } else {
        keysp = new PKCS8EncodedKeySpec(keyData);
    }
    PrivateKey privKey = kf.generatePrivate(keysp);
    Map<String, Object> attributes = getAttributes(cert);
    Calendar now = Calendar.getInstance();
    Calendar exp = Calendar.getInstance();
    exp.setTime(cert.getNotAfter());
    long diff = exp.getTimeInMillis() - now.getTimeInMillis();
    long diffDays = diff / (24 * 60 * 60 * 1000);
    // TODO: get the key strength
    // just hard coded
    int keyStr = 1024;
    CertCreateFields retVal = new CertCreateFields(attributes, certFile, keyFile, password, (int) diffDays, keyStr, cert, privKey);
    return retVal;
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Calendar(java.util.Calendar) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) SecretKey(javax.crypto.SecretKey) ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) EncryptedPrivateKeyInfo(javax.crypto.EncryptedPrivateKeyInfo) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyFactory(java.security.KeyFactory) SecretKeyFactory(javax.crypto.SecretKeyFactory)

Example 13 with PBEKeySpec

use of javax.crypto.spec.PBEKeySpec in project nhin-d by DirectProject.

the class CreatePKCS12 method create.

/**
	 * Creates a PCKS12 file from the certificate and key files.
	 * @param certFile The X509 DER encoded certificate file.
	 * @param keyFile The PCKS8 DER encoded private key file.
	 * @param password Option password for the private key file.  This is required if the private key file is encrypted.  Should be null or empty
	 * if the private key file is not encrypted.
	 * @param createFile Optional file descriptor for the output file of the pkcs12 file.  If this is null, the file name is based on the 
	 * certificate file name.
	 * @return File descriptor of the created pcks12 file.  Null if an error occurred.  
	 */
public static File create(File certFile, File keyFile, String password, File createFile) {
    File pkcs12File = null;
    CreatePKCS12.certFile = certFile;
    CreatePKCS12.keyFile = keyFile;
    FileOutputStream outStr = null;
    InputStream inStr = null;
    // load cert file
    try {
        KeyStore localKeyStore = KeyStore.getInstance("PKCS12", CryptoExtensions.getJCEProviderName());
        localKeyStore.load(null, null);
        byte[] certData = loadFileData(certFile);
        byte[] keyData = loadFileData(keyFile);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        inStr = new ByteArrayInputStream(certData);
        java.security.cert.Certificate cert = cf.generateCertificate(inStr);
        IOUtils.closeQuietly(inStr);
        KeyFactory kf = KeyFactory.getInstance("RSA", CryptoExtensions.getJCEProviderName());
        PKCS8EncodedKeySpec keysp = null;
        if (password != null && !password.isEmpty()) {
            EncryptedPrivateKeyInfo encInfo = new EncryptedPrivateKeyInfo(keyData);
            PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
            String alg = encInfo.getAlgName();
            SecretKeyFactory secFactory = SecretKeyFactory.getInstance(alg, CryptoExtensions.getJCEProviderName());
            SecretKey secKey = secFactory.generateSecret(keySpec);
            keysp = encInfo.getKeySpec(secKey, CryptoExtensions.getJCEProviderName());
        } else {
            keysp = new PKCS8EncodedKeySpec(keyData);
        }
        Key privKey = kf.generatePrivate(keysp);
        char[] array = "".toCharArray();
        localKeyStore.setKeyEntry("privCert", privKey, array, new java.security.cert.Certificate[] { cert });
        pkcs12File = getPKCS12OutFile(createFile);
        outStr = new FileOutputStream(pkcs12File);
        localKeyStore.store(outStr, p12Pass.toCharArray());
    } catch (Exception e) {
        System.err.println("Failed to create pcks12 file: " + e.getMessage());
        e.printStackTrace(System.err);
        return null;
    } finally {
        IOUtils.closeQuietly(outStr);
        IOUtils.closeQuietly(inStr);
    }
    return pkcs12File;
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) KeyStore(java.security.KeyStore) CertificateFactory(java.security.cert.CertificateFactory) SecretKey(javax.crypto.SecretKey) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) EncryptedPrivateKeyInfo(javax.crypto.EncryptedPrivateKeyInfo) File(java.io.File) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyFactory(java.security.KeyFactory) SecretKeyFactory(javax.crypto.SecretKeyFactory) Key(java.security.Key) SecretKey(javax.crypto.SecretKey)

Example 14 with PBEKeySpec

use of javax.crypto.spec.PBEKeySpec in project midpoint by Evolveum.

the class ProtectorImpl method compareHashedPbkd.

private boolean compareHashedPbkd(HashedDataType hashedDataType, String algorithmName, char[] clearChars) throws EncryptionException {
    DigestMethodType digestMethodType = hashedDataType.getDigestMethod();
    byte[] salt = digestMethodType.getSalt();
    Integer workFactor = digestMethodType.getWorkFactor();
    byte[] digestValue = hashedDataType.getDigestValue();
    int keyLen = digestValue.length * 8;
    SecretKeyFactory secretKeyFactory;
    try {
        secretKeyFactory = SecretKeyFactory.getInstance(algorithmName);
    } catch (NoSuchAlgorithmException e) {
        throw new EncryptionException(e.getMessage(), e);
    }
    PBEKeySpec keySpec = new PBEKeySpec(clearChars, salt, workFactor, keyLen);
    SecretKey key;
    try {
        key = secretKeyFactory.generateSecret(keySpec);
    } catch (InvalidKeySpecException e) {
        throw new EncryptionException(e.getMessage(), e);
    }
    byte[] hashBytes = key.getEncoded();
    return Arrays.equals(digestValue, hashBytes);
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKey(javax.crypto.SecretKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) DigestMethodType(com.evolveum.prism.xml.ns._public.types_3.DigestMethodType) SecretKeyFactory(javax.crypto.SecretKeyFactory)

Example 15 with PBEKeySpec

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

Aggregations

PBEKeySpec (javax.crypto.spec.PBEKeySpec)249 SecretKeyFactory (javax.crypto.SecretKeyFactory)190 SecretKey (javax.crypto.SecretKey)118 Cipher (javax.crypto.Cipher)82 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)73 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)63 KeySpec (java.security.spec.KeySpec)59 PBEParameterSpec (javax.crypto.spec.PBEParameterSpec)59 SecretKeySpec (javax.crypto.spec.SecretKeySpec)49 IOException (java.io.IOException)25 KeyStoreException (java.security.KeyStoreException)23 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)22 EncryptedPrivateKeyInfo (javax.crypto.EncryptedPrivateKeyInfo)17 CertificateException (java.security.cert.CertificateException)15 GeneralSecurityException (java.security.GeneralSecurityException)14 UnrecoverableKeyException (java.security.UnrecoverableKeyException)14 AlgorithmParameters (java.security.AlgorithmParameters)13 Key (java.security.Key)13 KeyStore (java.security.KeyStore)13 InvalidKeyException (java.security.InvalidKeyException)12