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);
}
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;
}
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;
}
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);
}
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);
}
}
}
Aggregations