use of java.security.AlgorithmParameters in project jdk8u_jdk by JetBrains.
the class CipherForKeyProtector method protect.
/**
* Protects the given cleartext private key, using the password provided at
* construction time.
*/
byte[] protect(PrivateKey key) throws Exception {
// create a random salt (8 bytes)
byte[] salt = new byte[8];
SunJCE.getRandom().nextBytes(salt);
// create PBE parameters from salt and iteration count
PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20);
// create PBE key from password
PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
pbeKeySpec.clearPassword();
// encrypt private key
PBEWithMD5AndTripleDESCipher cipher;
cipher = new PBEWithMD5AndTripleDESCipher();
cipher.engineInit(Cipher.ENCRYPT_MODE, sKey, pbeSpec, null);
byte[] plain = key.getEncoded();
byte[] encrKey = cipher.engineDoFinal(plain, 0, plain.length);
// wrap encrypted private key in EncryptedPrivateKeyInfo
// (as defined in PKCS#8)
AlgorithmParameters pbeParams = AlgorithmParameters.getInstance("PBE", SunJCE.getInstance());
pbeParams.init(pbeSpec);
AlgorithmId encrAlg = new AlgorithmId(new ObjectIdentifier(PBE_WITH_MD5_AND_DES3_CBC_OID), pbeParams);
return new EncryptedPrivateKeyInfo(encrAlg, encrKey).getEncoded();
}
use of java.security.AlgorithmParameters in project jdk8u_jdk by JetBrains.
the class extObjectInputStream method unseal.
private Object unseal(Key key, String provider) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
/*
* Create the parameter object.
*/
AlgorithmParameters params = null;
if (this.encodedParams != null) {
try {
if (provider != null)
params = AlgorithmParameters.getInstance(this.paramsAlg, provider);
else
params = AlgorithmParameters.getInstance(this.paramsAlg);
} catch (NoSuchProviderException nspe) {
if (provider == null) {
throw new NoSuchAlgorithmException(this.paramsAlg + " not found");
} else {
throw new NoSuchProviderException(nspe.getMessage());
}
}
params.init(this.encodedParams);
}
/*
* Create and initialize the cipher.
*/
Cipher c;
try {
if (provider != null)
c = Cipher.getInstance(this.sealAlg, provider);
else
c = Cipher.getInstance(this.sealAlg);
} catch (NoSuchPaddingException nspe) {
throw new NoSuchAlgorithmException("Padding that was used in " + "sealing operation not " + "available");
} catch (NoSuchProviderException nspe) {
if (provider == null) {
throw new NoSuchAlgorithmException(this.sealAlg + " not found");
} else {
throw new NoSuchProviderException(nspe.getMessage());
}
}
try {
if (params != null)
c.init(Cipher.DECRYPT_MODE, key, params);
else
c.init(Cipher.DECRYPT_MODE, key);
} catch (InvalidAlgorithmParameterException iape) {
// parameters that were used in the sealing operation
throw new RuntimeException(iape.getMessage());
}
/*
* Unseal the object
*/
byte[] content = c.doFinal(this.encryptedContent);
/*
* De-serialize it
*/
// creating a stream pipe-line, from b to a
ByteArrayInputStream b = new ByteArrayInputStream(content);
ObjectInput a = new extObjectInputStream(b);
try {
Object obj = a.readObject();
return obj;
} finally {
a.close();
}
}
use of java.security.AlgorithmParameters in project jdk8u_jdk by JetBrains.
the class PKCS12KeyStore method engineGetKey.
/**
* Returns the key associated with the given alias, using the given
* password to recover it.
*
* @param alias the alias name
* @param password the password for recovering the key
*
* @return the requested key, or null if the given alias does not exist
* or does not identify a <i>key entry</i>.
*
* @exception NoSuchAlgorithmException if the algorithm for recovering the
* key cannot be found
* @exception UnrecoverableKeyException if the key cannot be recovered
* (e.g., the given password is wrong).
*/
public Key engineGetKey(String alias, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException {
Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
Key key = null;
if (entry == null || (!(entry instanceof KeyEntry))) {
return null;
}
// get the encoded private key or secret key
byte[] encrBytes = null;
if (entry instanceof PrivateKeyEntry) {
encrBytes = ((PrivateKeyEntry) entry).protectedPrivKey;
} else if (entry instanceof SecretKeyEntry) {
encrBytes = ((SecretKeyEntry) entry).protectedSecretKey;
} else {
throw new UnrecoverableKeyException("Error locating key");
}
byte[] encryptedKey;
AlgorithmParameters algParams;
ObjectIdentifier algOid;
try {
// get the encrypted private key
EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(encrBytes);
encryptedKey = encrInfo.getEncryptedData();
// parse Algorithm parameters
DerValue val = new DerValue(encrInfo.getAlgorithm().encode());
DerInputStream in = val.toDerInputStream();
algOid = in.getOID();
algParams = parseAlgParameters(algOid, in);
} catch (IOException ioe) {
UnrecoverableKeyException uke = new UnrecoverableKeyException("Private key not stored as " + "PKCS#8 EncryptedPrivateKeyInfo: " + ioe);
uke.initCause(ioe);
throw uke;
}
try {
byte[] keyInfo;
while (true) {
try {
// Use JCE
SecretKey skey = getPBEKey(password);
Cipher cipher = Cipher.getInstance(mapPBEParamsToAlgorithm(algOid, algParams));
cipher.init(Cipher.DECRYPT_MODE, skey, algParams);
keyInfo = cipher.doFinal(encryptedKey);
break;
} catch (Exception e) {
if (password.length == 0) {
// Retry using an empty password
// without a NULL terminator.
password = new char[1];
continue;
}
throw e;
}
}
/*
* Parse the key algorithm and then use a JCA key factory
* to re-create the key.
*/
DerValue val = new DerValue(keyInfo);
DerInputStream in = val.toDerInputStream();
int i = in.getInteger();
DerValue[] value = in.getSequence(2);
AlgorithmId algId = new AlgorithmId(value[0].getOID());
String keyAlgo = algId.getName();
// decode private key
if (entry instanceof PrivateKeyEntry) {
KeyFactory kfac = KeyFactory.getInstance(keyAlgo);
PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(keyInfo);
key = kfac.generatePrivate(kspec);
if (debug != null) {
debug.println("Retrieved a protected private key (" + key.getClass().getName() + ") at alias '" + alias + "'");
}
// decode secret key
} else {
byte[] keyBytes = in.getOctetString();
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, keyAlgo);
// Special handling required for PBE: needs a PBEKeySpec
if (keyAlgo.startsWith("PBE")) {
SecretKeyFactory sKeyFactory = SecretKeyFactory.getInstance(keyAlgo);
KeySpec pbeKeySpec = sKeyFactory.getKeySpec(secretKeySpec, PBEKeySpec.class);
key = sKeyFactory.generateSecret(pbeKeySpec);
} else {
key = secretKeySpec;
}
if (debug != null) {
debug.println("Retrieved a protected secret key (" + key.getClass().getName() + ") at alias '" + alias + "'");
}
}
} catch (Exception e) {
UnrecoverableKeyException uke = new UnrecoverableKeyException("Get Key failed: " + e.getMessage());
uke.initCause(e);
throw uke;
}
return key;
}
use of java.security.AlgorithmParameters in project jdk8u_jdk by JetBrains.
the class AlgorithmChecker method check.
@Override
public void check(Certificate cert, Collection<String> unresolvedCritExts) throws CertPathValidatorException {
if (!(cert instanceof X509Certificate) || constraints == null) {
// ignore the check for non-x.509 certificate or null constraints
return;
}
// check the key usage and key size
boolean[] keyUsage = ((X509Certificate) cert).getKeyUsage();
if (keyUsage != null && keyUsage.length < 9) {
throw new CertPathValidatorException("incorrect KeyUsage extension", null, null, -1, PKIXReason.INVALID_KEY_USAGE);
}
X509CertImpl x509Cert;
AlgorithmId algorithmId;
try {
x509Cert = X509CertImpl.toImpl((X509Certificate) cert);
algorithmId = (AlgorithmId) x509Cert.get(X509CertImpl.SIG_ALG);
} catch (CertificateException ce) {
throw new CertPathValidatorException(ce);
}
AlgorithmParameters currSigAlgParams = algorithmId.getParameters();
PublicKey currPubKey = cert.getPublicKey();
String currSigAlg = ((X509Certificate) cert).getSigAlgName();
// Check the signature algorithm and parameters against constraints.
if (!constraints.permits(SIGNATURE_PRIMITIVE_SET, currSigAlg, currSigAlgParams)) {
throw new CertPathValidatorException("Algorithm constraints check failed on signature " + "algorithm: " + currSigAlg, null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
}
// Assume all key usage bits are set if key usage is not present
Set<CryptoPrimitive> primitives = KU_PRIMITIVE_SET;
if (keyUsage != null) {
primitives = EnumSet.noneOf(CryptoPrimitive.class);
if (keyUsage[0] || keyUsage[1] || keyUsage[5] || keyUsage[6]) {
// keyUsage[0]: KeyUsage.digitalSignature
// keyUsage[1]: KeyUsage.nonRepudiation
// keyUsage[5]: KeyUsage.keyCertSign
// keyUsage[6]: KeyUsage.cRLSign
primitives.add(CryptoPrimitive.SIGNATURE);
}
if (keyUsage[2]) {
// KeyUsage.keyEncipherment
primitives.add(CryptoPrimitive.KEY_ENCAPSULATION);
}
if (keyUsage[3]) {
// KeyUsage.dataEncipherment
primitives.add(CryptoPrimitive.PUBLIC_KEY_ENCRYPTION);
}
if (keyUsage[4]) {
// KeyUsage.keyAgreement
primitives.add(CryptoPrimitive.KEY_AGREEMENT);
}
if (primitives.isEmpty()) {
throw new CertPathValidatorException("incorrect KeyUsage extension bits", null, null, -1, PKIXReason.INVALID_KEY_USAGE);
}
}
ConstraintsParameters cp = new ConstraintsParameters((X509Certificate) cert, trustedMatch, pkixdate, jarTimestamp, variant);
// Check against local constraints if it is DisabledAlgorithmConstraints
if (constraints instanceof DisabledAlgorithmConstraints) {
((DisabledAlgorithmConstraints) constraints).permits(currSigAlg, cp);
// DisabledAlgorithmsConstraints does not check primitives, so key
// additional key check.
} else {
// Perform the default constraints checking anyway.
certPathDefaultConstraints.permits(currSigAlg, cp);
// Call locally set constraints to check key with primitives.
if (!constraints.permits(primitives, currPubKey)) {
throw new CertPathValidatorException("Algorithm constraints check failed on key " + currPubKey.getAlgorithm() + " with size of " + sun.security.util.KeyUtil.getKeySize(currPubKey) + "bits", null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
}
}
// If there is no previous key, set one and exit
if (prevPubKey == null) {
prevPubKey = currPubKey;
return;
}
// Check with previous cert for signature algorithm and public key
if (!constraints.permits(SIGNATURE_PRIMITIVE_SET, currSigAlg, prevPubKey, currSigAlgParams)) {
throw new CertPathValidatorException("Algorithm constraints check failed on " + "signature algorithm: " + currSigAlg, null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
}
// Inherit key parameters from previous key
if (PKIX.isDSAPublicKeyWithoutParams(currPubKey)) {
// Inherit DSA parameters from previous key
if (!(prevPubKey instanceof DSAPublicKey)) {
throw new CertPathValidatorException("Input key is not " + "of a appropriate type for inheriting parameters");
}
DSAParams params = ((DSAPublicKey) prevPubKey).getParams();
if (params == null) {
throw new CertPathValidatorException("Key parameters missing from public key.");
}
try {
BigInteger y = ((DSAPublicKey) currPubKey).getY();
KeyFactory kf = KeyFactory.getInstance("DSA");
DSAPublicKeySpec ks = new DSAPublicKeySpec(y, params.getP(), params.getQ(), params.getG());
currPubKey = kf.generatePublic(ks);
} catch (GeneralSecurityException e) {
throw new CertPathValidatorException("Unable to generate " + "key with inherited parameters: " + e.getMessage(), e);
}
}
// reset the previous public key
prevPubKey = currPubKey;
}
use of java.security.AlgorithmParameters in project jdk8u_jdk by JetBrains.
the class AlgorithmChecker method check.
/**
* Check the signature algorithm with the specified public key.
*
* @param key the public key to verify the CRL signature
* @param algorithmId signature algorithm Algorithm ID
* @param variant is the Validator variants of the operation. A null value
* passed will set it to Validator.GENERIC.
*/
static void check(PublicKey key, AlgorithmId algorithmId, String variant) throws CertPathValidatorException {
String sigAlgName = algorithmId.getName();
AlgorithmParameters sigAlgParams = algorithmId.getParameters();
certPathDefaultConstraints.permits(new ConstraintsParameters(sigAlgName, sigAlgParams, key, variant));
}
Aggregations