use of sun.security.util.ObjectIdentifier in project jdk8u_jdk by JetBrains.
the class PKCS12KeyStore method encryptPrivateKey.
/*
* Encrypt private key using Password-based encryption (PBE)
* as defined in PKCS#5.
*
* NOTE: By default, pbeWithSHAAnd3-KeyTripleDES-CBC algorithmID is
* used to derive the key and IV.
*
* @return encrypted private key encoded as EncryptedPrivateKeyInfo
*/
private byte[] encryptPrivateKey(byte[] data, KeyStore.PasswordProtection passwordProtection) throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException {
byte[] key = null;
try {
String algorithm;
AlgorithmParameters algParams;
AlgorithmId algid;
// Initialize PBE algorithm and parameters
algorithm = passwordProtection.getProtectionAlgorithm();
if (algorithm != null) {
AlgorithmParameterSpec algParamSpec = passwordProtection.getProtectionParameters();
if (algParamSpec != null) {
algParams = AlgorithmParameters.getInstance(algorithm);
algParams.init(algParamSpec);
} else {
algParams = getAlgorithmParameters(algorithm);
}
} else {
// Check default key protection algorithm for PKCS12 keystores
algorithm = AccessController.doPrivileged(new PrivilegedAction<String>() {
public String run() {
String prop = Security.getProperty(KEY_PROTECTION_ALGORITHM[0]);
if (prop == null) {
prop = Security.getProperty(KEY_PROTECTION_ALGORITHM[1]);
}
return prop;
}
});
if (algorithm == null || algorithm.isEmpty()) {
algorithm = "PBEWithSHA1AndDESede";
}
algParams = getAlgorithmParameters(algorithm);
}
ObjectIdentifier pbeOID = mapPBEAlgorithmToOID(algorithm);
if (pbeOID == null) {
throw new IOException("PBE algorithm '" + algorithm + " 'is not supported for key entry protection");
}
// Use JCE
SecretKey skey = getPBEKey(passwordProtection.getPassword());
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);
byte[] encryptedKey = cipher.doFinal(data);
algid = new AlgorithmId(pbeOID, cipher.getParameters());
if (debug != null) {
debug.println(" (Cipher algorithm: " + cipher.getAlgorithm() + ")");
}
// wrap encrypted private key in EncryptedPrivateKeyInfo
// as defined in PKCS#8
EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(algid, encryptedKey);
key = encrInfo.getEncoded();
} catch (Exception e) {
UnrecoverableKeyException uke = new UnrecoverableKeyException("Encrypt Private Key failed: " + e.getMessage());
uke.initCause(e);
throw uke;
}
return key;
}
use of sun.security.util.ObjectIdentifier in project jdk8u_jdk by JetBrains.
the class KeyProtector method protect.
/*
* Protects the given plaintext key, using the password provided at
* construction time.
*/
public byte[] protect(Key key) throws KeyStoreException {
int i;
int numRounds;
byte[] digest;
// offset in xorKey where next digest will be stored
int xorOffset;
int encrKeyOffset = 0;
if (key == null) {
throw new IllegalArgumentException("plaintext key can't be null");
}
if (!"PKCS#8".equalsIgnoreCase(key.getFormat())) {
throw new KeyStoreException("Cannot get key bytes, not PKCS#8 encoded");
}
byte[] plainKey = key.getEncoded();
if (plainKey == null) {
throw new KeyStoreException("Cannot get key bytes, encoding not supported");
}
// Determine the number of digest rounds
numRounds = plainKey.length / DIGEST_LEN;
if ((plainKey.length % DIGEST_LEN) != 0)
numRounds++;
// Create a random salt
byte[] salt = new byte[SALT_LEN];
SecureRandom random = new SecureRandom();
random.nextBytes(salt);
// Set up the byte array which will be XORed with "plainKey"
byte[] xorKey = new byte[plainKey.length];
// Compute the digests, and store them in "xorKey"
for (i = 0, xorOffset = 0, digest = salt; i < numRounds; i++, xorOffset += DIGEST_LEN) {
md.update(passwdBytes);
md.update(digest);
digest = md.digest();
md.reset();
// Copy the digest into "xorKey"
if (i < numRounds - 1) {
System.arraycopy(digest, 0, xorKey, xorOffset, digest.length);
} else {
System.arraycopy(digest, 0, xorKey, xorOffset, xorKey.length - xorOffset);
}
}
// XOR "plainKey" with "xorKey", and store the result in "tmpKey"
byte[] tmpKey = new byte[plainKey.length];
for (i = 0; i < tmpKey.length; i++) {
tmpKey[i] = (byte) (plainKey[i] ^ xorKey[i]);
}
// Store salt and "tmpKey" in "encrKey"
byte[] encrKey = new byte[salt.length + tmpKey.length + DIGEST_LEN];
System.arraycopy(salt, 0, encrKey, encrKeyOffset, salt.length);
encrKeyOffset += salt.length;
System.arraycopy(tmpKey, 0, encrKey, encrKeyOffset, tmpKey.length);
encrKeyOffset += tmpKey.length;
// Append digest(password, plainKey) as an integrity check to "encrKey"
md.update(passwdBytes);
Arrays.fill(passwdBytes, (byte) 0x00);
passwdBytes = null;
md.update(plainKey);
digest = md.digest();
md.reset();
System.arraycopy(digest, 0, encrKey, encrKeyOffset, digest.length);
// wrap the protected private key in a PKCS#8-style
// EncryptedPrivateKeyInfo, and returns its encoding
AlgorithmId encrAlg;
try {
encrAlg = new AlgorithmId(new ObjectIdentifier(KEY_PROTECTOR_OID));
return new EncryptedPrivateKeyInfo(encrAlg, encrKey).getEncoded();
} catch (IOException ioe) {
throw new KeyStoreException(ioe.getMessage());
}
}
use of sun.security.util.ObjectIdentifier in project jdk8u_jdk by JetBrains.
the class TSRequest method encode.
public byte[] encode() throws IOException {
DerOutputStream request = new DerOutputStream();
// encode version
request.putInteger(version);
// encode messageImprint
DerOutputStream messageImprint = new DerOutputStream();
hashAlgorithmId.encode(messageImprint);
messageImprint.putOctetString(hashValue);
request.write(DerValue.tag_Sequence, messageImprint);
if (policyId != null) {
request.putOID(new ObjectIdentifier(policyId));
}
if (nonce != null) {
request.putInteger(nonce);
}
if (returnCertificate) {
request.putBoolean(true);
}
DerOutputStream out = new DerOutputStream();
out.write(DerValue.tag_Sequence, request);
return out.toByteArray();
}
use of sun.security.util.ObjectIdentifier in project jdk8u_jdk by JetBrains.
the class Pair method createV3Extensions.
/**
* Create X509v3 extensions from a string representation. Note that the
* SubjectKeyIdentifierExtension will always be created non-critical besides
* the extension requested in the <code>extstr</code> argument.
*
* @param reqex the requested extensions, can be null, used for -gencert
* @param ext the original extensions, can be null, used for -selfcert
* @param extstrs -ext values, Read keytool doc
* @param pkey the public key for the certificate
* @param akey the public key for the authority (issuer)
* @return the created CertificateExtensions
*/
private CertificateExtensions createV3Extensions(CertificateExtensions reqex, CertificateExtensions ext, List<String> extstrs, PublicKey pkey, PublicKey akey) throws Exception {
if (ext != null && reqex != null) {
// This should not happen
throw new Exception("One of request and original should be null.");
}
if (ext == null)
ext = new CertificateExtensions();
try {
// Honoring requested extensions
if (reqex != null) {
for (String extstr : extstrs) {
if (extstr.toLowerCase(Locale.ENGLISH).startsWith("honored=")) {
List<String> list = Arrays.asList(extstr.toLowerCase(Locale.ENGLISH).substring(8).split(","));
// First check existence of "all"
if (list.contains("all")) {
// we know ext was null
ext = reqex;
}
// one by one for others
for (String item : list) {
if (item.equals("all"))
continue;
// add or remove
boolean add = true;
// -1, unchanged, 0 crtical, 1 non-critical
int action = -1;
String type = null;
if (item.startsWith("-")) {
add = false;
type = item.substring(1);
} else {
int colonpos = item.indexOf(':');
if (colonpos >= 0) {
type = item.substring(0, colonpos);
action = oneOf(item.substring(colonpos + 1), "critical", "non-critical");
if (action == -1) {
throw new Exception(rb.getString("Illegal.value.") + item);
}
}
}
String n = reqex.getNameByOid(findOidForExtName(type));
if (add) {
Extension e = reqex.get(n);
if (!e.isCritical() && action == 0 || e.isCritical() && action == 1) {
e = Extension.newExtension(e.getExtensionId(), !e.isCritical(), e.getExtensionValue());
ext.set(n, e);
}
} else {
ext.delete(n);
}
}
break;
}
}
}
for (String extstr : extstrs) {
String name, value;
boolean isCritical = false;
int eqpos = extstr.indexOf('=');
if (eqpos >= 0) {
name = extstr.substring(0, eqpos);
value = extstr.substring(eqpos + 1);
} else {
name = extstr;
value = null;
}
int colonpos = name.indexOf(':');
if (colonpos >= 0) {
if (oneOf(name.substring(colonpos + 1), "critical") == 0) {
isCritical = true;
}
name = name.substring(0, colonpos);
}
if (name.equalsIgnoreCase("honored")) {
continue;
}
int exttype = oneOf(name, extSupported);
switch(exttype) {
case // BC
0:
int pathLen = -1;
boolean isCA = false;
if (value == null) {
isCA = true;
} else {
try {
// the abbr format
pathLen = Integer.parseInt(value);
isCA = true;
} catch (NumberFormatException ufe) {
// ca:true,pathlen:1
for (String part : value.split(",")) {
String[] nv = part.split(":");
if (nv.length != 2) {
throw new Exception(rb.getString("Illegal.value.") + extstr);
} else {
if (nv[0].equalsIgnoreCase("ca")) {
isCA = Boolean.parseBoolean(nv[1]);
} else if (nv[0].equalsIgnoreCase("pathlen")) {
pathLen = Integer.parseInt(nv[1]);
} else {
throw new Exception(rb.getString("Illegal.value.") + extstr);
}
}
}
}
}
ext.set(BasicConstraintsExtension.NAME, new BasicConstraintsExtension(isCritical, isCA, pathLen));
break;
case // KU
1:
if (value != null) {
boolean[] ok = new boolean[9];
for (String s : value.split(",")) {
int p = oneOf(s, // (0),
"digitalSignature", // (1)
"nonRepudiation", // (2),
"keyEncipherment", // (3),
"dataEncipherment", // (4),
"keyAgreement", // (5),
"keyCertSign", // (6),
"cRLSign", // (7),
"encipherOnly", // (8)
"decipherOnly", // also (1)
"contentCommitment");
if (p < 0) {
throw new Exception(rb.getString("Unknown.keyUsage.type.") + s);
}
if (p == 9)
p = 1;
ok[p] = true;
}
KeyUsageExtension kue = new KeyUsageExtension(ok);
// The above KeyUsageExtension constructor does not
// allow isCritical value, so...
ext.set(KeyUsageExtension.NAME, Extension.newExtension(kue.getExtensionId(), isCritical, kue.getExtensionValue()));
} else {
throw new Exception(rb.getString("Illegal.value.") + extstr);
}
break;
case // EKU
2:
if (value != null) {
Vector<ObjectIdentifier> v = new Vector<>();
for (String s : value.split(",")) {
int p = oneOf(s, "anyExtendedKeyUsage", //1
"serverAuth", //2
"clientAuth", //3
"codeSigning", //4
"emailProtection", //5
"", //6
"", //7
"", //8
"timeStamping", //9
"OCSPSigning");
if (p < 0) {
try {
v.add(new ObjectIdentifier(s));
} catch (Exception e) {
throw new Exception(rb.getString("Unknown.extendedkeyUsage.type.") + s);
}
} else if (p == 0) {
v.add(new ObjectIdentifier("2.5.29.37.0"));
} else {
v.add(new ObjectIdentifier("1.3.6.1.5.5.7.3." + p));
}
}
ext.set(ExtendedKeyUsageExtension.NAME, new ExtendedKeyUsageExtension(isCritical, v));
} else {
throw new Exception(rb.getString("Illegal.value.") + extstr);
}
break;
// SAN
case 3:
case // IAN
4:
if (value != null) {
String[] ps = value.split(",");
GeneralNames gnames = new GeneralNames();
for (String item : ps) {
colonpos = item.indexOf(':');
if (colonpos < 0) {
throw new Exception("Illegal item " + item + " in " + extstr);
}
String t = item.substring(0, colonpos);
String v = item.substring(colonpos + 1);
gnames.add(createGeneralName(t, v));
}
if (exttype == 3) {
ext.set(SubjectAlternativeNameExtension.NAME, new SubjectAlternativeNameExtension(isCritical, gnames));
} else {
ext.set(IssuerAlternativeNameExtension.NAME, new IssuerAlternativeNameExtension(isCritical, gnames));
}
} else {
throw new Exception(rb.getString("Illegal.value.") + extstr);
}
break;
// SIA, always non-critical
case 5:
case // AIA, always non-critical
6:
if (isCritical) {
throw new Exception(rb.getString("This.extension.cannot.be.marked.as.critical.") + extstr);
}
if (value != null) {
List<AccessDescription> accessDescriptions = new ArrayList<>();
String[] ps = value.split(",");
for (String item : ps) {
colonpos = item.indexOf(':');
int colonpos2 = item.indexOf(':', colonpos + 1);
if (colonpos < 0 || colonpos2 < 0) {
throw new Exception(rb.getString("Illegal.value.") + extstr);
}
String m = item.substring(0, colonpos);
String t = item.substring(colonpos + 1, colonpos2);
String v = item.substring(colonpos2 + 1);
int p = oneOf(m, "", //1
"ocsp", //2
"caIssuers", //3
"timeStamping", "", //5
"caRepository");
ObjectIdentifier oid;
if (p < 0) {
try {
oid = new ObjectIdentifier(m);
} catch (Exception e) {
throw new Exception(rb.getString("Unknown.AccessDescription.type.") + m);
}
} else {
oid = new ObjectIdentifier("1.3.6.1.5.5.7.48." + p);
}
accessDescriptions.add(new AccessDescription(oid, createGeneralName(t, v)));
}
if (exttype == 5) {
ext.set(SubjectInfoAccessExtension.NAME, new SubjectInfoAccessExtension(accessDescriptions));
} else {
ext.set(AuthorityInfoAccessExtension.NAME, new AuthorityInfoAccessExtension(accessDescriptions));
}
} else {
throw new Exception(rb.getString("Illegal.value.") + extstr);
}
break;
case // CRL, experimental, only support 1 distributionpoint
8:
if (value != null) {
String[] ps = value.split(",");
GeneralNames gnames = new GeneralNames();
for (String item : ps) {
colonpos = item.indexOf(':');
if (colonpos < 0) {
throw new Exception("Illegal item " + item + " in " + extstr);
}
String t = item.substring(0, colonpos);
String v = item.substring(colonpos + 1);
gnames.add(createGeneralName(t, v));
}
ext.set(CRLDistributionPointsExtension.NAME, new CRLDistributionPointsExtension(isCritical, Collections.singletonList(new DistributionPoint(gnames, null, null))));
} else {
throw new Exception(rb.getString("Illegal.value.") + extstr);
}
break;
case -1:
ObjectIdentifier oid = new ObjectIdentifier(name);
byte[] data = null;
if (value != null) {
data = new byte[value.length() / 2 + 1];
int pos = 0;
for (char c : value.toCharArray()) {
int hex;
if (c >= '0' && c <= '9') {
hex = c - '0';
} else if (c >= 'A' && c <= 'F') {
hex = c - 'A' + 10;
} else if (c >= 'a' && c <= 'f') {
hex = c - 'a' + 10;
} else {
continue;
}
if (pos % 2 == 0) {
data[pos / 2] = (byte) (hex << 4);
} else {
data[pos / 2] += hex;
}
pos++;
}
if (pos % 2 != 0) {
throw new Exception(rb.getString("Odd.number.of.hex.digits.found.") + extstr);
}
data = Arrays.copyOf(data, pos / 2);
} else {
data = new byte[0];
}
ext.set(oid.toString(), new Extension(oid, isCritical, new DerValue(DerValue.tag_OctetString, data).toByteArray()));
break;
default:
throw new Exception(rb.getString("Unknown.extension.type.") + extstr);
}
}
// always non-critical
ext.set(SubjectKeyIdentifierExtension.NAME, new SubjectKeyIdentifierExtension(new KeyIdentifier(pkey).getIdentifier()));
if (akey != null && !pkey.equals(akey)) {
ext.set(AuthorityKeyIdentifierExtension.NAME, new AuthorityKeyIdentifierExtension(new KeyIdentifier(akey), null, null));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return ext;
}
use of sun.security.util.ObjectIdentifier in project jdk8u_jdk by JetBrains.
the class ExtendedKeyUsageExtension method toString.
/**
* Return the extension as user readable string.
*/
public String toString() {
if (keyUsages == null)
return "";
String usage = " ";
boolean first = true;
for (ObjectIdentifier oid : keyUsages) {
if (!first) {
usage += "\n ";
}
String result = map.get(oid);
if (result != null) {
usage += result;
} else {
usage += oid.toString();
}
first = false;
}
return super.toString() + "ExtendedKeyUsages [\n" + usage + "\n]\n";
}
Aggregations