Search in sources :

Example 36 with SecretKeyFactory

use of javax.crypto.SecretKeyFactory 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 37 with SecretKeyFactory

use of javax.crypto.SecretKeyFactory 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 38 with SecretKeyFactory

use of javax.crypto.SecretKeyFactory 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 39 with SecretKeyFactory

use of javax.crypto.SecretKeyFactory in project android_frameworks_base by DirtyUnicorns.

the class AndroidKeyStoreCipherSpiBase method engineWrap.

@Override
protected final byte[] engineWrap(Key key) throws IllegalBlockSizeException, InvalidKeyException {
    if (mKey == null) {
        throw new IllegalStateException("Not initilized");
    }
    if (!isEncrypting()) {
        throw new IllegalStateException("Cipher must be initialized in Cipher.WRAP_MODE to wrap keys");
    }
    if (key == null) {
        throw new NullPointerException("key == null");
    }
    byte[] encoded = null;
    if (key instanceof SecretKey) {
        if ("RAW".equalsIgnoreCase(key.getFormat())) {
            encoded = key.getEncoded();
        }
        if (encoded == null) {
            try {
                SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(key.getAlgorithm());
                SecretKeySpec spec = (SecretKeySpec) keyFactory.getKeySpec((SecretKey) key, SecretKeySpec.class);
                encoded = spec.getEncoded();
            } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                throw new InvalidKeyException("Failed to wrap key because it does not export its key material", e);
            }
        }
    } else if (key instanceof PrivateKey) {
        if ("PKCS8".equalsIgnoreCase(key.getFormat())) {
            encoded = key.getEncoded();
        }
        if (encoded == null) {
            try {
                KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
                PKCS8EncodedKeySpec spec = keyFactory.getKeySpec(key, PKCS8EncodedKeySpec.class);
                encoded = spec.getEncoded();
            } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                throw new InvalidKeyException("Failed to wrap key because it does not export its key material", e);
            }
        }
    } else if (key instanceof PublicKey) {
        if ("X.509".equalsIgnoreCase(key.getFormat())) {
            encoded = key.getEncoded();
        }
        if (encoded == null) {
            try {
                KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
                X509EncodedKeySpec spec = keyFactory.getKeySpec(key, X509EncodedKeySpec.class);
                encoded = spec.getEncoded();
            } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                throw new InvalidKeyException("Failed to wrap key because it does not export its key material", e);
            }
        }
    } else {
        throw new InvalidKeyException("Unsupported key type: " + key.getClass().getName());
    }
    if (encoded == null) {
        throw new InvalidKeyException("Failed to wrap key because it does not export its key material");
    }
    try {
        return engineDoFinal(encoded, 0, encoded.length);
    } catch (BadPaddingException e) {
        throw (IllegalBlockSizeException) new IllegalBlockSizeException().initCause(e);
    }
}
Also used : PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) SecretKeyFactory(javax.crypto.SecretKeyFactory) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyFactory(java.security.KeyFactory)

Example 40 with SecretKeyFactory

use of javax.crypto.SecretKeyFactory in project android_frameworks_base by DirtyUnicorns.

the class BackupManagerService method buildCharArrayKey.

private SecretKey buildCharArrayKey(String algorithm, char[] pwArray, byte[] salt, int rounds) {
    try {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
        KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
        return keyFactory.generateSecret(ks);
    } catch (InvalidKeySpecException e) {
        Slog.e(TAG, "Invalid key spec for PBKDF2!");
    } catch (NoSuchAlgorithmException e) {
        Slog.e(TAG, "PBKDF2 unavailable!");
    }
    return null;
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKeySpec(javax.crypto.spec.SecretKeySpec) KeySpec(java.security.spec.KeySpec) PBEKeySpec(javax.crypto.spec.PBEKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SecretKeyFactory(javax.crypto.SecretKeyFactory)

Aggregations

SecretKeyFactory (javax.crypto.SecretKeyFactory)129 SecretKey (javax.crypto.SecretKey)84 PBEKeySpec (javax.crypto.spec.PBEKeySpec)75 Cipher (javax.crypto.Cipher)58 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)39 DESKeySpec (javax.crypto.spec.DESKeySpec)28 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)26 PBEParameterSpec (javax.crypto.spec.PBEParameterSpec)26 KeySpec (java.security.spec.KeySpec)25 SecretKeySpec (javax.crypto.spec.SecretKeySpec)23 SecureRandom (java.security.SecureRandom)18 KeyStoreException (java.security.KeyStoreException)16 IOException (java.io.IOException)15 InvalidKeyException (java.security.InvalidKeyException)14 PrivateKey (java.security.PrivateKey)12 CertificateException (java.security.cert.CertificateException)12 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)12 UnrecoverableKeyException (java.security.UnrecoverableKeyException)11 Key (java.security.Key)10 KeyFactory (java.security.KeyFactory)10