use of sun.security.util.ObjectIdentifier in project jdk8u_jdk by JetBrains.
the class PKCS9Attributes method toString.
/**
* Returns the PKCS9 block in a printable string form.
*/
public String toString() {
StringBuffer buf = new StringBuffer(200);
buf.append("PKCS9 Attributes: [\n\t");
ObjectIdentifier oid;
PKCS9Attribute value;
boolean first = true;
for (int i = 1; i < PKCS9Attribute.PKCS9_OIDS.length; i++) {
value = getAttribute(PKCS9Attribute.PKCS9_OIDS[i]);
if (value == null)
continue;
// we have a value; print it
if (first)
first = false;
else
buf.append(";\n\t");
buf.append(value.toString());
}
buf.append("\n\t] (end PKCS9 Attributes)");
return buf.toString();
}
use of sun.security.util.ObjectIdentifier in project jdk8u_jdk by JetBrains.
the class SignerInfo method verify.
/* Returns null if verify fails, this signerInfo if
verify succeeds. */
SignerInfo verify(PKCS7 block, byte[] data) throws NoSuchAlgorithmException, SignatureException {
try {
ContentInfo content = block.getContentInfo();
if (data == null) {
data = content.getContentBytes();
}
ConstraintsParameters cparams = new ConstraintsParameters(timestamp);
String digestAlgname = getDigestAlgorithmId().getName();
byte[] dataSigned;
// digest and compare it with the digest of data
if (authenticatedAttributes == null) {
dataSigned = data;
} else {
// first, check content type
ObjectIdentifier contentType = (ObjectIdentifier) authenticatedAttributes.getAttributeValue(PKCS9Attribute.CONTENT_TYPE_OID);
if (contentType == null || !contentType.equals((Object) content.contentType))
// contentType does not match, bad SignerInfo
return null;
// now, check message digest
byte[] messageDigest = (byte[]) authenticatedAttributes.getAttributeValue(PKCS9Attribute.MESSAGE_DIGEST_OID);
if (// fail if there is no message digest
messageDigest == null)
return null;
// check that digest algorithm is not restricted
try {
JAR_DISABLED_CHECK.permits(digestAlgname, cparams);
} catch (CertPathValidatorException e) {
throw new SignatureException(e.getMessage(), e);
}
MessageDigest md = MessageDigest.getInstance(digestAlgname);
byte[] computedMessageDigest = md.digest(data);
if (messageDigest.length != computedMessageDigest.length)
return null;
for (int i = 0; i < messageDigest.length; i++) {
if (messageDigest[i] != computedMessageDigest[i])
return null;
}
// message digest attribute matched
// digest of original data
// the data actually signed is the DER encoding of
// the authenticated attributes (tagged with
// the "SET OF" tag, not 0xA0).
dataSigned = authenticatedAttributes.getDerEncoding();
}
// put together digest algorithm and encryption algorithm
// to form signing algorithm
String encryptionAlgname = getDigestEncryptionAlgorithmId().getName();
// Workaround: sometimes the encryptionAlgname is actually
// a signature name
String tmp = AlgorithmId.getEncAlgFromSigAlg(encryptionAlgname);
if (tmp != null)
encryptionAlgname = tmp;
String algname = AlgorithmId.makeSigAlg(digestAlgname, encryptionAlgname);
// check that jar signature algorithm is not restricted
try {
JAR_DISABLED_CHECK.permits(algname, cparams);
} catch (CertPathValidatorException e) {
throw new SignatureException(e.getMessage(), e);
}
X509Certificate cert = getCertificate(block);
if (cert == null) {
return null;
}
PublicKey key = cert.getPublicKey();
// check if the public key is restricted
if (!JAR_DISABLED_CHECK.permits(SIG_PRIMITIVE_SET, key)) {
throw new SignatureException("Public key check failed. " + "Disabled key used: " + KeyUtil.getKeySize(key) + " bit " + key.getAlgorithm());
}
if (cert.hasUnsupportedCriticalExtension()) {
throw new SignatureException("Certificate has unsupported " + "critical extension(s)");
}
// Make sure that if the usage of the key in the certificate is
// restricted, it can be used for digital signatures.
// XXX We may want to check for additional extensions in the
// future.
boolean[] keyUsageBits = cert.getKeyUsage();
if (keyUsageBits != null) {
KeyUsageExtension keyUsage;
try {
// We don't care whether or not this extension was marked
// critical in the certificate.
// We're interested only in its value (i.e., the bits set)
// and treat the extension as critical.
keyUsage = new KeyUsageExtension(keyUsageBits);
} catch (IOException ioe) {
throw new SignatureException("Failed to parse keyUsage " + "extension");
}
boolean digSigAllowed = keyUsage.get(KeyUsageExtension.DIGITAL_SIGNATURE).booleanValue();
boolean nonRepuAllowed = keyUsage.get(KeyUsageExtension.NON_REPUDIATION).booleanValue();
if (!digSigAllowed && !nonRepuAllowed) {
throw new SignatureException("Key usage restricted: " + "cannot be used for " + "digital signatures");
}
}
Signature sig = Signature.getInstance(algname);
sig.initVerify(key);
sig.update(dataSigned);
if (sig.verify(encryptedDigest)) {
return this;
}
} catch (IOException e) {
throw new SignatureException("IO error verifying signature:\n" + e.getMessage());
} catch (InvalidKeyException e) {
throw new SignatureException("InvalidKey: " + e.getMessage());
}
return null;
}
use of sun.security.util.ObjectIdentifier in project jdk8u_jdk by JetBrains.
the class PKCS9Attribute method derEncode.
/**
* Write the DER encoding of this attribute to an output stream.
*
* <P> N.B.: This method always encodes values of
* ChallengePassword and UnstructuredAddress attributes as ASN.1
* <code>PrintableString</code>s, without checking whether they
* should be encoded as <code>T61String</code>s.
*/
public void derEncode(OutputStream out) throws IOException {
DerOutputStream temp = new DerOutputStream();
temp.putOID(oid);
switch(index) {
case // Unknown
-1:
temp.write((byte[]) value);
break;
// email address
case 1:
case // unstructured name
2:
{
// open scope
String[] values = (String[]) value;
DerOutputStream[] temps = new DerOutputStream[values.length];
for (int i = 0; i < values.length; i++) {
temps[i] = new DerOutputStream();
temps[i].putIA5String(values[i]);
}
temp.putOrderedSetOf(DerValue.tag_Set, temps);
}
// close scope
break;
case // content type
3:
{
DerOutputStream temp2 = new DerOutputStream();
temp2.putOID((ObjectIdentifier) value);
temp.write(DerValue.tag_Set, temp2.toByteArray());
}
break;
case // message digest
4:
{
DerOutputStream temp2 = new DerOutputStream();
temp2.putOctetString((byte[]) value);
temp.write(DerValue.tag_Set, temp2.toByteArray());
}
break;
case // signing time
5:
{
DerOutputStream temp2 = new DerOutputStream();
temp2.putUTCTime((Date) value);
temp.write(DerValue.tag_Set, temp2.toByteArray());
}
break;
case // countersignature
6:
temp.putOrderedSetOf(DerValue.tag_Set, (DerEncoder[]) value);
break;
case // challenge password
7:
{
DerOutputStream temp2 = new DerOutputStream();
temp2.putPrintableString((String) value);
temp.write(DerValue.tag_Set, temp2.toByteArray());
}
break;
case // unstructured address
8:
{
// open scope
String[] values = (String[]) value;
DerOutputStream[] temps = new DerOutputStream[values.length];
for (int i = 0; i < values.length; i++) {
temps[i] = new DerOutputStream();
temps[i].putPrintableString(values[i]);
}
temp.putOrderedSetOf(DerValue.tag_Set, temps);
}
// close scope
break;
case // extended-certificate attribute -- not supported
9:
throw new IOException("PKCS9 extended-certificate " + "attribute not supported.");
// break unnecessary
case // issuerAndserialNumber attribute -- not supported
10:
throw new IOException("PKCS9 IssuerAndSerialNumber" + "attribute not supported.");
// RSA DSI proprietary
case 11:
case // RSA DSI proprietary
12:
throw new IOException("PKCS9 RSA DSI attributes" + "11 and 12, not supported.");
// break unnecessary
case // S/MIME unused attribute
13:
throw new IOException("PKCS9 attribute #13 not supported.");
case // ExtensionRequest
14:
{
DerOutputStream temp2 = new DerOutputStream();
CertificateExtensions exts = (CertificateExtensions) value;
try {
exts.encode(temp2, true);
} catch (CertificateException ex) {
throw new IOException(ex.toString());
}
temp.write(DerValue.tag_Set, temp2.toByteArray());
}
break;
case // SMIMECapability
15:
throw new IOException("PKCS9 attribute #15 not supported.");
case // SigningCertificate
16:
throw new IOException("PKCS9 SigningCertificate attribute not supported.");
case // SignatureTimestampToken
17:
temp.write(DerValue.tag_Set, (byte[]) value);
break;
// can't happen
default:
}
DerOutputStream derOut = new DerOutputStream();
derOut.write(DerValue.tag_Sequence, temp.toByteArray());
out.write(derOut.toByteArray());
}
use of sun.security.util.ObjectIdentifier in project jdk8u_jdk by JetBrains.
the class PKCS12KeyStore method getBagAttributes.
private byte[] getBagAttributes(String alias, byte[] keyId, ObjectIdentifier[] trustedUsage, Set<KeyStore.Entry.Attribute> attributes) throws IOException {
byte[] localKeyID = null;
byte[] friendlyName = null;
byte[] trustedKeyUsage = null;
// return null if all three attributes are null
if ((alias == null) && (keyId == null) && (trustedKeyUsage == null)) {
return null;
}
// SafeBag Attributes
DerOutputStream bagAttrs = new DerOutputStream();
// Encode the friendlyname oid.
if (alias != null) {
DerOutputStream bagAttr1 = new DerOutputStream();
bagAttr1.putOID(PKCS9FriendlyName_OID);
DerOutputStream bagAttrContent1 = new DerOutputStream();
DerOutputStream bagAttrValue1 = new DerOutputStream();
bagAttrContent1.putBMPString(alias);
bagAttr1.write(DerValue.tag_Set, bagAttrContent1);
bagAttrValue1.write(DerValue.tag_Sequence, bagAttr1);
friendlyName = bagAttrValue1.toByteArray();
}
// Encode the localkeyId oid.
if (keyId != null) {
DerOutputStream bagAttr2 = new DerOutputStream();
bagAttr2.putOID(PKCS9LocalKeyId_OID);
DerOutputStream bagAttrContent2 = new DerOutputStream();
DerOutputStream bagAttrValue2 = new DerOutputStream();
bagAttrContent2.putOctetString(keyId);
bagAttr2.write(DerValue.tag_Set, bagAttrContent2);
bagAttrValue2.write(DerValue.tag_Sequence, bagAttr2);
localKeyID = bagAttrValue2.toByteArray();
}
// Encode the trustedKeyUsage oid.
if (trustedUsage != null) {
DerOutputStream bagAttr3 = new DerOutputStream();
bagAttr3.putOID(TrustedKeyUsage_OID);
DerOutputStream bagAttrContent3 = new DerOutputStream();
DerOutputStream bagAttrValue3 = new DerOutputStream();
for (ObjectIdentifier usage : trustedUsage) {
bagAttrContent3.putOID(usage);
}
bagAttr3.write(DerValue.tag_Set, bagAttrContent3);
bagAttrValue3.write(DerValue.tag_Sequence, bagAttr3);
trustedKeyUsage = bagAttrValue3.toByteArray();
}
DerOutputStream attrs = new DerOutputStream();
if (friendlyName != null) {
attrs.write(friendlyName);
}
if (localKeyID != null) {
attrs.write(localKeyID);
}
if (trustedKeyUsage != null) {
attrs.write(trustedKeyUsage);
}
if (attributes != null) {
for (KeyStore.Entry.Attribute attribute : attributes) {
String attributeName = attribute.getName();
// skip friendlyName, localKeyId and trustedKeyUsage
if (CORE_ATTRIBUTES[0].equals(attributeName) || CORE_ATTRIBUTES[1].equals(attributeName) || CORE_ATTRIBUTES[2].equals(attributeName)) {
continue;
}
attrs.write(((PKCS12Attribute) attribute).getEncoded());
}
}
bagAttrs.write(DerValue.tag_Set, attrs);
return bagAttrs.toByteArray();
}
use of sun.security.util.ObjectIdentifier 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