use of javax.crypto.spec.PBEParameterSpec in project symmetric-ds by JumpMind.
the class SecurityService method initializeCipher.
protected void initializeCipher(Cipher cipher, int mode) throws Exception {
AlgorithmParameterSpec paramSpec = Cipher.getMaxAllowedParameterSpec(cipher.getAlgorithm());
if (paramSpec instanceof PBEParameterSpec || (paramSpec == null && cipher.getAlgorithm().startsWith("PBE"))) {
paramSpec = new PBEParameterSpec(SecurityConstants.SALT, SecurityConstants.ITERATION_COUNT);
cipher.init(mode, secretKey, paramSpec);
} else if (paramSpec instanceof IvParameterSpec) {
paramSpec = new IvParameterSpec(SecurityConstants.SALT);
cipher.init(mode, secretKey, paramSpec);
} else {
cipher.init(mode, secretKey, (AlgorithmParameterSpec) null);
}
}
use of javax.crypto.spec.PBEParameterSpec in project yyl_example by Relucent.
the class PBEWithMD5AndDES_Encrypt method encrypt.
/**
* 将传进来的明文以PBEWithMD5AndDES算法进行加密
*
* @param text String
* @return String
*/
public String encrypt(String text) throws Exception {
if (text == null || text.length() == 0) {
return "";
}
PBEKeySpec pbks = new PBEKeySpec(password.toCharArray());
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey k = skf.generateSecret(pbks);
byte[] salt = new byte[8];
Random r = new Random();
r.nextBytes(salt);
Cipher cp = Cipher.getInstance("PBEWithMD5AndDES");
PBEParameterSpec ps = new PBEParameterSpec(salt, 1000);
cp.init(Cipher.ENCRYPT_MODE, k, ps);
byte[] ptext = text.getBytes(encoding);
byte[] ctext = cp.doFinal(ptext);
String result = "";
for (int i = 0; i < salt.length; i++) {
result += salt[i] + " ";
}
for (int i = 0; i < ctext.length; i++) {
result += ctext[i] + " ";
}
return string2hex(result);
}
use of javax.crypto.spec.PBEParameterSpec in project wildfly by wildfly.
the class VaultSession method computeMaskedPassword.
/**
* Method to compute masked password based on class attributes.
*
* @return masked password prefixed with {link @PicketBoxSecurityVault.PASS_MASK_PREFIX}.
* @throws Exception
*/
private String computeMaskedPassword() throws Exception {
// Create the PBE secret key
SecretKeyFactory factory = SecretKeyFactory.getInstance(VAULT_ENC_ALGORITHM);
char[] password = "somearbitrarycrazystringthatdoesnotmatter".toCharArray();
PBEParameterSpec cipherSpec = new PBEParameterSpec(salt.getBytes(), iterationCount);
PBEKeySpec keySpec = new PBEKeySpec(password);
SecretKey cipherKey = factory.generateSecret(keySpec);
String maskedPass = PBEUtils.encode64(keystorePassword.getBytes(), VAULT_ENC_ALGORITHM, cipherKey, cipherSpec);
return PicketBoxSecurityVault.PASS_MASK_PREFIX + maskedPass;
}
use of javax.crypto.spec.PBEParameterSpec in project jdk8u_jdk by JetBrains.
the class HmacPKCS12PBESHA1 method engineInit.
/**
* Initializes the HMAC with the given secret key and algorithm parameters.
*
* @param key the secret key.
* @param params the algorithm parameters.
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this MAC.
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this MAC.
*/
protected void engineInit(Key key, AlgorithmParameterSpec params) throws InvalidKeyException, InvalidAlgorithmParameterException {
char[] passwdChars;
byte[] salt = null;
int iCount = 0;
if (key instanceof javax.crypto.interfaces.PBEKey) {
javax.crypto.interfaces.PBEKey pbeKey = (javax.crypto.interfaces.PBEKey) key;
passwdChars = pbeKey.getPassword();
// maybe null if unspecified
salt = pbeKey.getSalt();
// maybe 0 if unspecified
iCount = pbeKey.getIterationCount();
} else if (key instanceof SecretKey) {
byte[] passwdBytes = key.getEncoded();
if ((passwdBytes == null) || !(key.getAlgorithm().regionMatches(true, 0, "PBE", 0, 3))) {
throw new InvalidKeyException("Missing password");
}
passwdChars = new char[passwdBytes.length];
for (int i = 0; i < passwdChars.length; i++) {
passwdChars[i] = (char) (passwdBytes[i] & 0x7f);
}
} else {
throw new InvalidKeyException("SecretKey of PBE type required");
}
if (params == null) {
// retrieve the generated defaults.
if ((salt == null) || (iCount == 0)) {
throw new InvalidAlgorithmParameterException("PBEParameterSpec required for salt and iteration count");
}
} else if (!(params instanceof PBEParameterSpec)) {
throw new InvalidAlgorithmParameterException("PBEParameterSpec type required");
} else {
PBEParameterSpec pbeParams = (PBEParameterSpec) params;
// make sure the parameter values are consistent
if (salt != null) {
if (!Arrays.equals(salt, pbeParams.getSalt())) {
throw new InvalidAlgorithmParameterException("Inconsistent value of salt between key and params");
}
} else {
salt = pbeParams.getSalt();
}
if (iCount != 0) {
if (iCount != pbeParams.getIterationCount()) {
throw new InvalidAlgorithmParameterException("Different iteration count between key and params");
}
} else {
iCount = pbeParams.getIterationCount();
}
}
// which is what PKCS#5 recommends and openssl does.
if (salt.length < 8) {
throw new InvalidAlgorithmParameterException("Salt must be at least 8 bytes long");
}
if (iCount <= 0) {
throw new InvalidAlgorithmParameterException("IterationCount must be a positive number");
}
byte[] derivedKey = PKCS12PBECipherCore.derive(passwdChars, salt, iCount, engineGetMacLength(), PKCS12PBECipherCore.MAC_KEY);
SecretKey cipherKey = new SecretKeySpec(derivedKey, "HmacSHA1");
super.engineInit(cipherKey, null);
}
use of javax.crypto.spec.PBEParameterSpec in project jdk8u_jdk by JetBrains.
the class PKCS12KeyStore method engineLoad.
/**
* Loads the keystore from the given input stream.
*
* <p>If a password is given, it is used to check the integrity of the
* keystore data. Otherwise, the integrity of the keystore is not checked.
*
* @param stream the input stream from which the keystore is loaded
* @param password the (optional) password used to check the integrity of
* the keystore.
*
* @exception IOException if there is an I/O or format problem with the
* keystore data
* @exception NoSuchAlgorithmException if the algorithm used to check
* the integrity of the keystore cannot be found
* @exception CertificateException if any of the certificates in the
* keystore could not be loaded
*/
public synchronized void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException {
DataInputStream dis;
CertificateFactory cf = null;
ByteArrayInputStream bais = null;
byte[] encoded = null;
if (stream == null)
return;
// reset the counter
counter = 0;
DerValue val = new DerValue(stream);
DerInputStream s = val.toDerInputStream();
int version = s.getInteger();
if (version != VERSION_3) {
throw new IOException("PKCS12 keystore not in version 3 format");
}
entries.clear();
/*
* Read the authSafe.
*/
byte[] authSafeData;
ContentInfo authSafe = new ContentInfo(s);
ObjectIdentifier contentType = authSafe.getContentType();
if (contentType.equals((Object) ContentInfo.DATA_OID)) {
authSafeData = authSafe.getData();
} else /* signed data */
{
throw new IOException("public key protected PKCS12 not supported");
}
DerInputStream as = new DerInputStream(authSafeData);
DerValue[] safeContentsArray = as.getSequence(2);
int count = safeContentsArray.length;
// reset the counters at the start
privateKeyCount = 0;
secretKeyCount = 0;
certificateCount = 0;
/*
* Spin over the ContentInfos.
*/
for (int i = 0; i < count; i++) {
byte[] safeContentsData;
ContentInfo safeContents;
DerInputStream sci;
byte[] eAlgId = null;
sci = new DerInputStream(safeContentsArray[i].toByteArray());
safeContents = new ContentInfo(sci);
contentType = safeContents.getContentType();
safeContentsData = null;
if (contentType.equals((Object) ContentInfo.DATA_OID)) {
if (debug != null) {
debug.println("Loading PKCS#7 data content-type");
}
safeContentsData = safeContents.getData();
} else if (contentType.equals((Object) ContentInfo.ENCRYPTED_DATA_OID)) {
if (password == null) {
if (debug != null) {
debug.println("Warning: skipping PKCS#7 encryptedData" + " content-type - no password was supplied");
}
continue;
}
if (debug != null) {
debug.println("Loading PKCS#7 encryptedData content-type");
}
DerInputStream edi = safeContents.getContent().toDerInputStream();
int edVersion = edi.getInteger();
DerValue[] seq = edi.getSequence(2);
ObjectIdentifier edContentType = seq[0].getOID();
eAlgId = seq[1].toByteArray();
if (!seq[2].isContextSpecific((byte) 0)) {
throw new IOException("encrypted content not present!");
}
byte newTag = DerValue.tag_OctetString;
if (seq[2].isConstructed())
newTag |= 0x20;
seq[2].resetTag(newTag);
safeContentsData = seq[2].getOctetString();
// parse Algorithm parameters
DerInputStream in = seq[1].toDerInputStream();
ObjectIdentifier algOid = in.getOID();
AlgorithmParameters algParams = parseAlgParameters(algOid, in);
while (true) {
try {
// Use JCE
SecretKey skey = getPBEKey(password);
Cipher cipher = Cipher.getInstance(algOid.toString());
cipher.init(Cipher.DECRYPT_MODE, skey, algParams);
safeContentsData = cipher.doFinal(safeContentsData);
break;
} catch (Exception e) {
if (password.length == 0) {
// Retry using an empty password
// without a NULL terminator.
password = new char[1];
continue;
}
throw new IOException("keystore password was incorrect", new UnrecoverableKeyException("failed to decrypt safe contents entry: " + e));
}
}
} else {
throw new IOException("public key protected PKCS12" + " not supported");
}
DerInputStream sc = new DerInputStream(safeContentsData);
loadSafeContents(sc, password);
}
// The MacData is optional.
if (password != null && s.available() > 0) {
MacData macData = new MacData(s);
try {
String algName = macData.getDigestAlgName().toUpperCase(Locale.ENGLISH);
// Change SHA-1 to SHA1
algName = algName.replace("-", "");
// generate MAC (MAC key is created within JCE)
Mac m = Mac.getInstance("HmacPBE" + algName);
PBEParameterSpec params = new PBEParameterSpec(macData.getSalt(), macData.getIterations());
SecretKey key = getPBEKey(password);
m.init(key, params);
m.update(authSafeData);
byte[] macResult = m.doFinal();
if (debug != null) {
debug.println("Checking keystore integrity " + "(MAC algorithm: " + m.getAlgorithm() + ")");
}
if (!MessageDigest.isEqual(macData.getDigest(), macResult)) {
throw new UnrecoverableKeyException("Failed PKCS12" + " integrity checking");
}
} catch (Exception e) {
throw new IOException("Integrity check failed: " + e, e);
}
}
/*
* Match up private keys with certificate chains.
*/
PrivateKeyEntry[] list = keyList.toArray(new PrivateKeyEntry[keyList.size()]);
for (int m = 0; m < list.length; m++) {
PrivateKeyEntry entry = list[m];
if (entry.keyId != null) {
ArrayList<X509Certificate> chain = new ArrayList<X509Certificate>();
X509Certificate cert = findMatchedCertificate(entry);
mainloop: while (cert != null) {
// Check for loops in the certificate chain
if (!chain.isEmpty()) {
for (X509Certificate chainCert : chain) {
if (cert.equals(chainCert)) {
if (debug != null) {
debug.println("Loop detected in " + "certificate chain. Skip adding " + "repeated cert to chain. Subject: " + cert.getSubjectX500Principal().toString());
}
break mainloop;
}
}
}
chain.add(cert);
X500Principal issuerDN = cert.getIssuerX500Principal();
if (issuerDN.equals(cert.getSubjectX500Principal())) {
break;
}
cert = certsMap.get(issuerDN);
}
/* Update existing KeyEntry in entries table */
if (chain.size() > 0)
entry.chain = chain.toArray(new Certificate[chain.size()]);
}
}
if (debug != null) {
if (privateKeyCount > 0) {
debug.println("Loaded " + privateKeyCount + " protected private key(s)");
}
if (secretKeyCount > 0) {
debug.println("Loaded " + secretKeyCount + " protected secret key(s)");
}
if (certificateCount > 0) {
debug.println("Loaded " + certificateCount + " certificate(s)");
}
}
certEntries.clear();
certsMap.clear();
keyList.clear();
}
Aggregations