6876158: Remove dependencies on Signer, Certificate, Identity, IdentityScope classes from java.security pkg

Reviewed-by: alanb, mullan
This commit is contained in:
Vinnie Ryan 2009-12-07 17:06:59 +00:00
parent 45eee34489
commit 5c20a6292f
12 changed files with 28 additions and 2191 deletions

View File

@ -34,8 +34,6 @@ import java.util.*;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.Identity;
import java.security.IdentityScope;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Permission;
@ -267,7 +265,7 @@ public class PolicyFile extends javax.security.auth.Policy {
private boolean initialized = false;
private boolean expandProperties = true;
private boolean ignoreIdentityScope = false;
private boolean ignoreIdentityScope = true;
// for use with the reflection API
@ -459,9 +457,6 @@ public class PolicyFile extends javax.security.auth.Policy {
}
}
/** the scope to check */
private static IdentityScope scope = null;
/**
* Checks public key. If it is marked as trusted in
* the identity database, add it to the policy

View File

@ -44,7 +44,6 @@ import sun.security.util.*;
import sun.security.x509.AlgorithmId;
import sun.security.x509.X509Key;
import sun.security.x509.X500Name;
import sun.security.x509.X500Signer;
/**
* A PKCS #10 certificate request is created and sent to a Certificate
@ -183,13 +182,13 @@ public class PKCS10 {
* Create the signed certificate request. This will later be
* retrieved in either string or binary format.
*
* @param requester identifies the signer (by X.500 name)
* and provides the private key used to sign.
* @param subject identifies the signer (by X.500 name).
* @param signature private key and signing algorithm to use.
* @exception IOException on errors.
* @exception CertificateException on certificate handling errors.
* @exception SignatureException on signature handling errors.
*/
public void encodeAndSign(X500Signer requester)
public void encodeAndSign(X500Name subject, Signature signature)
throws CertificateException, IOException, SignatureException {
DerOutputStream out, scratch;
byte[] certificateRequestInfo;
@ -198,7 +197,7 @@ public class PKCS10 {
if (encoded != null)
throw new SignatureException("request is already signed");
subject = requester.getSigner();
this.subject = subject;
/*
* Encode cert request info, wrap in a sequence for signing
@ -217,14 +216,20 @@ public class PKCS10 {
/*
* Sign it ...
*/
requester.update(certificateRequestInfo, 0,
signature.update(certificateRequestInfo, 0,
certificateRequestInfo.length);
sig = requester.sign();
sig = signature.sign();
/*
* Build guts of SIGNED macro
*/
requester.getAlgorithmId().encode(scratch); // sig algorithm
AlgorithmId algId = null;
try {
algId = AlgorithmId.getAlgorithmId(signature.getAlgorithm());
} catch (NoSuchAlgorithmException nsae) {
throw new SignatureException(nsae);
}
algId.encode(scratch); // sig algorithm
scratch.putBitString(sig); // sig
/*

View File

@ -1,427 +0,0 @@
/*
* Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.security.provider;
import java.io.*;
import java.util.*;
import java.security.*;
/**
* An implementation of IdentityScope as a persistent identity
* database.
*
* @see Identity
* @see Key
*
* @author Benjamin Renaud
*/
public
class IdentityDatabase extends IdentityScope implements Serializable {
/** use serialVersionUID from JDK 1.1. for interoperability */
private static final long serialVersionUID = 4923799573357658384L;
/* Are we debugging? */
private static final boolean debug = false;
/* Are we printing out error messages? */
private static final boolean error = true;
/* The source file, if any, for this database.*/
File sourceFile;
/* The private representation of the database.*/
Hashtable<String, Identity> identities;
IdentityDatabase() throws InvalidParameterException {
this("restoring...");
}
/**
* Construct a new, empty database with a specified source file.
*
* @param file the source file.
*/
public IdentityDatabase(File file) throws InvalidParameterException {
this(file.getName());
sourceFile = file;
}
/**
* Construct a new, empty database.
*/
public IdentityDatabase(String name) throws InvalidParameterException {
super(name);
identities = new Hashtable<String, Identity>();
}
/**
* Initialize an identity database from a stream. The stream should
* contain data to initialized a serialized IdentityDatabase
* object.
*
* @param is the input stream from which to restore the database.
*
* @exception IOException if a stream IO exception occurs
*/
public static IdentityDatabase fromStream(InputStream is)
throws IOException {
IdentityDatabase db = null;
try {
ObjectInputStream ois = new ObjectInputStream(is);
db = (IdentityDatabase)ois.readObject();
} catch (ClassNotFoundException e) {
// this can't happen.
debug("This should not be happening.", e);
error(
"The version of the database is obsolete. Cannot initialize.");
} catch (InvalidClassException e) {
// this may happen in developers workspaces happen.
debug("This should not be happening.", e);
error("Unable to initialize system identity scope: " +
" InvalidClassException. \nThis is most likely due to " +
"a serialization versioning problem: a class used in " +
"key management was obsoleted");
} catch (StreamCorruptedException e) {
debug("The serialization stream is corrupted. Unable to load.", e);
error("Unable to initialize system identity scope." +
" StreamCorruptedException.");
}
if (db == null) {
db = new IdentityDatabase("uninitialized");
}
return db;
}
/**
* Initialize an IdentityDatabase from file.
*
* @param f the filename where the identity database is stored.
*
* @exception IOException a file-related exception occurs (e.g.
* the directory of the file passed does not exists, etc.
*
* @IOException if a file IO exception occurs.
*/
public static IdentityDatabase fromFile(File f) throws IOException {
FileInputStream fis = new FileInputStream(f);
IdentityDatabase edb = fromStream(fis);
edb.sourceFile = f;
return edb;
}
/**
* @return the number of identities in the database.
*/
public int size() {
return identities.size();
}
/**
* @param name the name of the identity to be retrieved.
*
* @return the identity named name, or null if there are
* no identities named name in the database.
*/
public Identity getIdentity(String name) {
Identity id = identities.get(name);
if (id instanceof Signer) {
localCheck("get.signer");
}
return id;
}
/**
* Get an identity by key.
*
* @param name the key of the identity to be retrieved.
*
* @return the identity with a given key, or null if there are no
* identities with that key in the database.
*/
public Identity getIdentity(PublicKey key) {
if (key == null) {
return null;
}
Enumeration<Identity> e = identities();
while (e.hasMoreElements()) {
Identity i = e.nextElement();
PublicKey k = i.getPublicKey();
if (k != null && keyEqual(k, key)) {
if (i instanceof Signer) {
localCheck("get.signer");
}
return i;
}
}
return null;
}
private boolean keyEqual(Key key1, Key key2) {
if (key1 == key2) {
return true;
} else {
return MessageDigest.isEqual(key1.getEncoded(), key2.getEncoded());
}
}
/**
* Adds an identity to the database.
*
* @param identity the identity to be added.
*
* @exception KeyManagementException if a name or key clash
* occurs, or if another exception occurs.
*/
public void addIdentity(Identity identity)
throws KeyManagementException {
localCheck("add.identity");
Identity byName = getIdentity(identity.getName());
Identity byKey = getIdentity(identity.getPublicKey());
String msg = null;
if (byName != null) {
msg = "name conflict";
}
if (byKey != null) {
msg = "key conflict";
}
if (msg != null) {
throw new KeyManagementException(msg);
}
identities.put(identity.getName(), identity);
}
/**
* Removes an identity to the database.
*/
public void removeIdentity(Identity identity)
throws KeyManagementException {
localCheck("remove.identity");
String name = identity.getName();
if (identities.get(name) == null) {
throw new KeyManagementException("there is no identity named " +
name + " in " + this);
}
identities.remove(name);
}
/**
* @return an enumeration of all identities in the database.
*/
public Enumeration<Identity> identities() {
return identities.elements();
}
/**
* Set the source file for this database.
*/
void setSourceFile(File f) {
sourceFile = f;
}
/**
* @return the source file for this database.
*/
File getSourceFile() {
return sourceFile;
}
/**
* Save the database in its current state to an output stream.
*
* @param os the output stream to which the database should be serialized.
*
* @exception IOException if an IO exception is raised by stream
* operations.
*/
public void save(OutputStream os) throws IOException {
try {
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(this);
oos.flush();
} catch (InvalidClassException e) {
debug("This should not be happening.", e);
return;
}
}
/**
* Save the database to a file.
*
* @exception IOException if an IO exception is raised by stream
* operations.
*/
void save(File f) throws IOException {
setSourceFile(f);
FileOutputStream fos = new FileOutputStream(f);
save(fos);
}
/**
* Saves the database to the default source file.
*
* @exception KeyManagementException when there is no default source
* file specified for this database.
*/
public void save() throws IOException {
if (sourceFile == null) {
throw new IOException("this database has no source file");
}
save(sourceFile);
}
/**
* This method returns the file from which to initialize the
* system database.
*/
private static File systemDatabaseFile() {
// First figure out where the identity database is hiding, if anywhere.
String dbPath = Security.getProperty("identity.database");
// if nowhere, it's the canonical place.
if (dbPath == null) {
dbPath = System.getProperty("user.home") + File.separatorChar +
"identitydb.obj";
}
return new File(dbPath);
}
/* This block initializes the system database, if there is one. */
static {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {
public Void run() {
initializeSystem();
return null;
}
});
}
/**
* This method initializes the system's identity database. The
* canonical location is
* <user.home>/identitydatabase.obj. This is settable through
* the identity.database property. */
private static void initializeSystem() {
IdentityDatabase systemDatabase;
File dbFile = systemDatabaseFile();
// Second figure out if it's there, and if it isn't, create one.
try {
if (dbFile.exists()) {
debug("loading system database from file: " + dbFile);
systemDatabase = fromFile(dbFile);
} else {
systemDatabase = new IdentityDatabase(dbFile);
}
IdentityScope.setSystemScope(systemDatabase);
debug("System database initialized: " + systemDatabase);
} catch (IOException e) {
debug("Error initializing identity database: " + dbFile, e);
return;
} catch (InvalidParameterException e) {
debug("Error trying to instantiate a system identities db in " +
dbFile, e);
return;
}
}
/*
private static File securityPropFile(String filename) {
// maybe check for a system property which will specify where to
// look.
String sep = File.separator;
return new File(System.getProperty("java.home") +
sep + "lib" + sep + "security" +
sep + filename);
}
*/
public String toString() {
return "sun.security.provider.IdentityDatabase, source file: " +
sourceFile;
}
private static void debug(String s) {
if (debug) {
System.err.println(s);
}
}
private static void debug(String s, Throwable t) {
if (debug) {
t.printStackTrace();
System.err.println(s);
}
}
private static void error(String s) {
if (error) {
System.err.println(s);
}
}
void localCheck(String directive) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
directive = this.getClass().getName() + "." +
directive + "." + localFullName();
security.checkSecurityAccess(directive);
}
}
/**
* Returns a parsable name for identity: identityName.scopeName
*/
String localFullName() {
String parsable = getName();
if (getScope() != null) {
parsable += "." +getScope().getName();
}
return parsable;
}
/**
* Serialization write.
*/
private synchronized void writeObject (java.io.ObjectOutputStream stream)
throws IOException {
localCheck("serialize.identity.database");
stream.writeObject(identities);
stream.writeObject(sourceFile);
}
}

View File

@ -295,16 +295,13 @@ public class PolicyFile extends java.security.Policy {
private static final int DEFAULT_CACHE_SIZE = 1;
/** the scope to check */
private static IdentityScope scope = null;
// contains the policy grant entries, PD cache, and alias mapping
private AtomicReference<PolicyInfo> policyInfo =
new AtomicReference<PolicyInfo>();
private boolean constructed = false;
private boolean expandProperties = true;
private boolean ignoreIdentityScope = false;
private boolean ignoreIdentityScope = true;
private boolean allowSystemProperties = true;
private boolean notUtf8 = false;
private URL url;
@ -2024,85 +2021,9 @@ public class PolicyFile extends java.security.Policy {
private boolean checkForTrustedIdentity(final Certificate cert,
PolicyInfo myInfo)
{
if (cert == null)
return false;
// see if we are ignoring the identity scope or not
if (ignoreIdentityScope)
return false;
// try to initialize scope
synchronized(PolicyFile.class) {
if (scope == null) {
IdentityScope is = IdentityScope.getSystemScope();
if (is instanceof sun.security.provider.IdentityDatabase) {
scope = is;
} else {
// leave scope null
}
}
}
if (scope == null) {
ignoreIdentityScope = true;
return false;
}
// need privileged block for getIdentity in case we are trying
// to get a signer
final Identity id = AccessController.doPrivileged(
new java.security.PrivilegedAction<Identity>() {
public Identity run() {
return scope.getIdentity(cert.getPublicKey());
}
});
if (isTrusted(id)) {
if (debug != null) {
debug.println("Adding policy entry for trusted Identity: ");
//needed for identity toString!
AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {
public Void run() {
debug.println(" identity = " + id);
return null;
}
});
debug.println("");
}
// add it to the policy for future reference
Certificate certs[] = new Certificate[] {cert};
PolicyEntry pe = new PolicyEntry(new CodeSource(null, certs));
pe.add(SecurityConstants.ALL_PERMISSION);
myInfo.identityPolicyEntries.add(pe);
// add it to the mapping as well so
// we don't have to go through this again
myInfo.aliasMapping.put(cert, id.getName());
return true;
}
return false;
}
private static boolean isTrusted(Identity id) {
if (id instanceof SystemIdentity) {
SystemIdentity sysid = (SystemIdentity)id;
if (sysid.isTrusted()) {
return true;
}
} else if (id instanceof SystemSigner) {
SystemSigner sysid = (SystemSigner)id;
if (sysid.isTrusted()) {
return true;
}
}
return false;
}
/**
* Each entry in the policy configuration file is represented by a
* PolicyEntry object. <p>

View File

@ -1,107 +0,0 @@
/*
* Copyright 1996-2000 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.security.provider;
import java.io.Serializable;
import java.util.Enumeration;
import java.security.*;
/**
* An identity with a very simple trust mechanism.
*
* @author Benjamin Renaud
*/
public class SystemIdentity extends Identity implements Serializable {
/** use serialVersionUID from JDK 1.1. for interoperability */
private static final long serialVersionUID = 9060648952088498478L;
/* This should be changed to ACL */
boolean trusted = false;
/* Free form additional information about this identity. */
private String info;
public SystemIdentity(String name, IdentityScope scope)
throws InvalidParameterException, KeyManagementException {
super(name, scope);
}
/**
* Is this identity trusted by sun.* facilities?
*/
public boolean isTrusted() {
return trusted;
}
/**
* Set the trust status of this identity.
*/
protected void setTrusted(boolean trusted) {
this.trusted = trusted;
}
void setIdentityInfo(String info) {
super.setInfo(info);
}
String getIndentityInfo() {
return super.getInfo();
}
/**
* Call back method into a protected method for package friends.
*/
void setIdentityPublicKey(PublicKey key) throws KeyManagementException {
setPublicKey(key);
}
/**
* Call back method into a protected method for package friends.
*/
void addIdentityCertificate(Certificate cert)
throws KeyManagementException {
addCertificate(cert);
}
void clearCertificates() throws KeyManagementException {
Certificate[] certs = certificates();
for (int i = 0; i < certs.length; i++) {
removeCertificate(certs[i]);
}
}
public String toString() {
String trustedString = "not trusted";
if (trusted) {
trustedString = "trusted";
}
return super.toString() + "[" + trustedString + "]";
}
}

View File

@ -1,115 +0,0 @@
/*
* Copyright 1996-2000 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.security.provider;
import java.util.*;
import java.security.*;
/**
* SunSecurity signer. Like SystemIdentity, it has a trust bit, which
* can be set by SunSecurity classes, and a set of accessors for other
* classes in sun.security.*.
*
* @author Benjamin Renaud
*/
public class SystemSigner extends Signer {
/** use serialVersionUID from JDK 1.1. for interoperability */
private static final long serialVersionUID = -2127743304301557711L;
/* Is this signer trusted */
private boolean trusted = false;
/**
* Construct a signer with a given name.
*/
public SystemSigner(String name) {
super(name);
}
/**
* Construct a signer with a name and a scope.
*
* @param name the signer's name.
*
* @param scope the scope for this signer.
*/
public SystemSigner(String name, IdentityScope scope)
throws KeyManagementException {
super(name, scope);
}
/* Set the trust status of this signer */
void setTrusted(boolean trusted) {
this.trusted = trusted;
}
/**
* Returns true if this signer is trusted.
*/
public boolean isTrusted() {
return trusted;
}
/* friendly callback for set keys */
void setSignerKeyPair(KeyPair pair)
throws InvalidParameterException, KeyException {
setKeyPair(pair);
}
/* friendly callback for getting private keys */
PrivateKey getSignerPrivateKey() {
return getPrivateKey();
}
void setSignerInfo(String s) {
setInfo(s);
}
/**
* Call back method into a protected method for package friends.
*/
void addSignerCertificate(Certificate cert) throws KeyManagementException {
addCertificate(cert);
}
void clearCertificates() throws KeyManagementException {
Certificate[] certs = certificates();
for (int i = 0; i < certs.length; i++) {
removeCertificate(certs[i]);
}
}
public String toString() {
String trustedString = "not trusted";
if (trusted) {
trustedString = "trusted";
}
return super.toString() + "[" + trustedString + "]";
}
}

View File

@ -118,8 +118,6 @@ public class JarSigner {
KeyStore store; // the keystore specified by -keystore
// or the default keystore, never null
IdentityScope scope;
String keystore; // key store file
boolean nullStream = false; // null keystore input stream (NONE)
boolean token = false; // token-based keystore
@ -212,7 +210,6 @@ public class JarSigner {
if (verify) {
try {
loadKeyStore(keystore, false);
scope = IdentityScope.getSystemScope();
} catch (Exception e) {
if ((keystore != null) || (storepass != null)) {
System.out.println(rb.getString("jarsigner error: ") +
@ -984,13 +981,6 @@ public class JarSigner {
result |= IN_KEYSTORE;
}
}
if (!found && (scope != null)) {
Identity id = scope.getIdentity(c.getPublicKey());
if (id != null) {
result |= IN_SCOPE;
storeHash.put(c, "[" + id.getName() + "]");
}
}
if (ckaliases.contains(alias)) {
result |= SIGNED_BY_ALIAS;
}

View File

@ -40,7 +40,6 @@ import java.security.UnrecoverableEntryException;
import java.security.UnrecoverableKeyException;
import java.security.Principal;
import java.security.Provider;
import java.security.Identity;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
@ -57,9 +56,6 @@ import java.net.URLClassLoader;
import sun.misc.BASE64Encoder;
import sun.security.util.ObjectIdentifier;
import sun.security.pkcs.PKCS10;
import sun.security.provider.IdentityDatabase;
import sun.security.provider.SystemSigner;
import sun.security.provider.SystemIdentity;
import sun.security.provider.X509Factory;
import sun.security.util.DerOutputStream;
import sun.security.util.Password;
@ -1163,18 +1159,16 @@ public final class KeyTool {
Signature signature = Signature.getInstance(sigAlgName);
signature.initSign(privateKey);
X500Signer signer = new X500Signer(signature, issuer);
X509CertInfo info = new X509CertInfo();
info.set(X509CertInfo.VALIDITY, interval);
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(
new java.util.Random().nextInt() & 0x7fffffff));
info.set(X509CertInfo.VERSION,
new CertificateVersion(CertificateVersion.V3));
new CertificateVersion(CertificateVersion.V3));
info.set(X509CertInfo.ALGORITHM_ID,
new CertificateAlgorithmId(signer.getAlgorithmId()));
info.set(X509CertInfo.ISSUER,
new CertificateIssuerName(signer.getSigner()));
new CertificateAlgorithmId(
AlgorithmId.getAlgorithmId(sigAlgName)));
info.set(X509CertInfo.ISSUER, new CertificateIssuerName(issuer));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
boolean canRead = false;
@ -1249,7 +1243,7 @@ public final class KeyTool {
request.getAttributes().setAttribute(X509CertInfo.EXTENSIONS,
new PKCS10Attribute(PKCS9Attribute.EXTENSION_REQUEST_OID, ext));
// Construct an X500Signer object, so that we can sign the request
// Construct a Signature object, so that we can sign the request
if (sigAlgName == null) {
sigAlgName = getCompatibleSigAlgName(privKey.getAlgorithm());
}
@ -1259,10 +1253,9 @@ public final class KeyTool {
X500Name subject = dname == null?
new X500Name(((X509Certificate)cert).getSubjectDN().toString()):
new X500Name(dname);
X500Signer signer = new X500Signer(signature, subject);
// Sign the request and base-64 encode it
request.encodeAndSign(signer);
request.encodeAndSign(subject, signature);
request.print(out);
}
@ -1564,75 +1557,8 @@ public final class KeyTool {
private void doImportIdentityDatabase(InputStream in)
throws Exception
{
byte[] encoded;
ByteArrayInputStream bais;
java.security.cert.X509Certificate newCert;
java.security.cert.Certificate[] chain = null;
PrivateKey privKey;
boolean modified = false;
IdentityDatabase idb = IdentityDatabase.fromStream(in);
for (Enumeration<Identity> enum_ = idb.identities();
enum_.hasMoreElements();) {
Identity id = enum_.nextElement();
newCert = null;
// only store trusted identities in keystore
if ((id instanceof SystemSigner && ((SystemSigner)id).isTrusted())
|| (id instanceof SystemIdentity
&& ((SystemIdentity)id).isTrusted())) {
// ignore if keystore entry with same alias name already exists
if (keyStore.containsAlias(id.getName())) {
MessageFormat form = new MessageFormat
(rb.getString("Keystore entry for <id.getName()> already exists"));
Object[] source = {id.getName()};
System.err.println(form.format(source));
continue;
}
java.security.Certificate[] certs = id.certificates();
if (certs!=null && certs.length>0) {
// we can only store one user cert per identity.
// convert old-style to new-style cert via the encoding
DerOutputStream dos = new DerOutputStream();
certs[0].encode(dos);
encoded = dos.toByteArray();
bais = new ByteArrayInputStream(encoded);
newCert = (X509Certificate)cf.generateCertificate(bais);
bais.close();
// if certificate is self-signed, make sure it verifies
if (isSelfSigned(newCert)) {
PublicKey pubKey = newCert.getPublicKey();
try {
newCert.verify(pubKey);
} catch (Exception e) {
// ignore this cert
continue;
}
}
if (id instanceof SystemSigner) {
MessageFormat form = new MessageFormat(rb.getString
("Creating keystore entry for <id.getName()> ..."));
Object[] source = {id.getName()};
System.err.println(form.format(source));
if (chain==null) {
chain = new java.security.cert.Certificate[1];
}
chain[0] = newCert;
privKey = ((SystemSigner)id).getPrivateKey();
keyStore.setKeyEntry(id.getName(), privKey, storePass,
chain);
} else {
keyStore.setCertificateEntry(id.getName(), newCert);
}
kssave = true;
}
}
}
if (!kssave) {
System.err.println(rb.getString
("No entries from identity database added"));
}
System.err.println(rb.getString
("No entries from identity database added"));
}
/**

View File

@ -189,41 +189,6 @@ public final class CertAndKeyGen {
}
/**
* Returns a self-signed X.509v1 certificate for the public key.
* The certificate is immediately valid.
*
* <P>Such certificates normally are used to identify a "Certificate
* Authority" (CA). Accordingly, they will not always be accepted by
* other parties. However, such certificates are also useful when
* you are bootstrapping your security infrastructure, or deploying
* system prototypes.
*
* @deprecated Use the new <a href =
* "#getSelfCertificate(sun.security.x509.X500Name, long)">
*
* @param myname X.500 name of the subject (who is also the issuer)
* @param validity how long the certificate should be valid, in seconds
*/
@Deprecated
public X509Cert getSelfCert (X500Name myname, long validity)
throws InvalidKeyException, SignatureException, NoSuchAlgorithmException
{
X509Certificate cert;
try {
cert = getSelfCertificate(myname, validity);
return new X509Cert(cert.getEncoded());
} catch (CertificateException e) {
throw new SignatureException(e.getMessage());
} catch (NoSuchProviderException e) {
throw new NoSuchAlgorithmException(e.getMessage());
} catch (IOException e) {
throw new SignatureException(e.getMessage());
}
}
/**
* Returns a self-signed X.509v3 certificate for the public key.
* The certificate is immediately valid. No extensions.
@ -248,13 +213,10 @@ public final class CertAndKeyGen {
throws CertificateException, InvalidKeyException, SignatureException,
NoSuchAlgorithmException, NoSuchProviderException
{
X500Signer issuer;
X509CertImpl cert;
Date lastDate;
try {
issuer = getSigner (myname);
lastDate = new Date ();
lastDate.setTime (firstDate.getTime () + validity * 1000);
@ -267,14 +229,13 @@ public final class CertAndKeyGen {
new CertificateVersion(CertificateVersion.V3));
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(
new java.util.Random().nextInt() & 0x7fffffff));
AlgorithmId algID = issuer.getAlgorithmId();
AlgorithmId algID = AlgorithmId.getAlgorithmId(sigAlg);
info.set(X509CertInfo.ALGORITHM_ID,
new CertificateAlgorithmId(algID));
info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(myname));
info.set(X509CertInfo.KEY, new CertificateX509Key(publicKey));
info.set(X509CertInfo.VALIDITY, interval);
info.set(X509CertInfo.ISSUER,
new CertificateIssuerName(issuer.getSigner()));
info.set(X509CertInfo.ISSUER, new CertificateIssuerName(myname));
cert = new X509CertImpl(info);
cert.sign(privateKey, this.sigAlg);
@ -315,7 +276,9 @@ public final class CertAndKeyGen {
PKCS10 req = new PKCS10 (publicKey);
try {
req.encodeAndSign (getSigner (myname));
Signature signature = Signature.getInstance(sigAlg);
signature.initSign (privateKey);
req.encodeAndSign(myname, signature);
} catch (CertificateException e) {
throw new SignatureException (sigAlg + " CertificateException");
@ -330,18 +293,6 @@ public final class CertAndKeyGen {
return req;
}
private X500Signer getSigner (X500Name me)
throws InvalidKeyException, NoSuchAlgorithmException
{
Signature signature = Signature.getInstance(sigAlg);
// XXX should have a way to pass prng to the signature
// algorithm ... appropriate for DSS/DSA, not RSA
signature.initSign (privateKey);
return new X500Signer (signature, me);
}
private SecureRandom prng;
private String sigAlg;
private KeyPairGenerator keyGen;

View File

@ -1,115 +0,0 @@
/*
* Copyright 1996-2003 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.security.x509;
import java.security.Signature;
import java.security.SignatureException;
import java.security.Signer;
import java.security.NoSuchAlgorithmException;
/**
* This class provides a binding between a Signature object and an
* authenticated X.500 name (from an X.509 certificate chain), which
* is needed in many public key signing applications.
*
* <P>The name of the signer is important, both because knowing it is the
* whole point of the signature, and because the associated X.509 certificate
* is always used to verify the signature.
*
* <P><em>The X.509 certificate chain is temporarily not associated with
* the signer, but this omission will be resolved.</em>
*
*
* @author David Brownell
* @author Amit Kapoor
* @author Hemma Prafullchandra
*/
public final class X500Signer extends Signer
{
private static final long serialVersionUID = -8609982645394364834L;
/**
* Called for each chunk of the data being signed. That
* is, you can present the data in many chunks, so that
* it doesn't need to be in a single sequential buffer.
*
* @param buf buffer holding the next chunk of the data to be signed
* @param offset starting point of to-be-signed data
* @param len how many bytes of data are to be signed
* @exception SignatureException on errors.
*/
public void update(byte buf[], int offset, int len)
throws SignatureException {
sig.update (buf, offset, len);
}
/**
* Produces the signature for the data processed by update().
*
* @exception SignatureException on errors.
*/
public byte[] sign() throws SignatureException {
return sig.sign();
}
/**
* Returns the algorithm used to sign.
*/
public AlgorithmId getAlgorithmId() {
return algid;
}
/**
* Returns the name of the signing agent.
*/
public X500Name getSigner() {
return agent;
}
/*
* Constructs a binding between a signature and an X500 name
* from an X.509 certificate.
*/
// package private ----hmmmmm ?????
public X500Signer(Signature sig, X500Name agent) {
if (sig == null || agent == null)
throw new IllegalArgumentException ("null parameter");
this.sig = sig;
this.agent = agent;
try {
this.algid = AlgorithmId.getAlgorithmId(sig.getAlgorithm());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("internal error! " + e.getMessage());
}
}
private Signature sig;
private X500Name agent; // XXX should be X509CertChain
private AlgorithmId algid;
}

View File

@ -1,892 +0,0 @@
/*
* Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.security.x509;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.*;
import java.util.Date;
import java.util.Enumeration;
import sun.security.util.*; // DER
/**
* @author David Brownell
*
* @see CertAndKeyGen
* @deprecated Use the new X509Certificate class.
* This class is only restored for backwards compatibility.
*/
@Deprecated
public class X509Cert implements Certificate, Serializable {
static final long serialVersionUID = -52595524744692374L;
/*
* NOTE: All fields are marked transient, because we do not want them to
* be included in the class description when we serialize an object of
* this class. We override "writeObject" and "readObject" to use the
* ASN.1 encoding of a certificate as the serialized form, instead of
* calling the default routines which would operate on the field values.
*
* MAKE SURE TO MARK ANY FIELDS THAT ARE ADDED IN THE FUTURE AS TRANSIENT.
*/
/* The algorithm id */
transient protected AlgorithmId algid;
/*
* Certificate data, and its envelope
*/
transient private byte rawCert [];
transient private byte signature [];
transient private byte signedCert [];
/*
* X509.v1 data (parsed)
*/
transient private X500Name subject; // from subject
transient private PublicKey pubkey;
transient private Date notafter; // from CA (constructor)
transient private Date notbefore;
transient private int version; // from CA (signAndEncode)
transient private BigInteger serialnum;
transient private X500Name issuer;
transient private AlgorithmId issuerSigAlg;
/*
* flag to indicate whether or not this certificate has already been parsed
* (through a call to one of the constructors or the "decode" or
* "readObject" methods). This is to ensure that certificates are
* immutable.
*/
transient private boolean parsed=false;
/*
* X509.v2 extensions
*/
/*
* X509.v3 extensions
*/
/*
* Other extensions ... Netscape, Verisign, SET, etc
*/
/**
* Construct a uninitialized X509 Cert on which <a href="#decode">
* decode</a> must later be called (or which may be deserialized).
*/
// XXX deprecated, delete this
public X509Cert() { }
/**
* Unmarshals a certificate from its encoded form, parsing the
* encoded bytes. This form of constructor is used by agents which
* need to examine and use certificate contents. That is, this is
* one of the more commonly used constructors. Note that the buffer
* must include only a certificate, and no "garbage" may be left at
* the end. If you need to ignore data at the end of a certificate,
* use another constructor.
*
* @param cert the encoded bytes, with no terminatu (CONSUMED)
* @exception IOException when the certificate is improperly encoded.
*/
public X509Cert(byte cert []) throws IOException
{
DerValue in = new DerValue (cert);
parse (in);
if (in.data.available () != 0)
throw new CertParseError ("garbage at end");
signedCert = cert;
}
/**
* Unmarshals a certificate from its encoded form, parsing the
* encoded bytes. This form of constructor is used by agents which
* need to examine and use certificate contents. That is, this is
* one of the most commonly used constructors.
*
* @param buf the buffer holding the encoded bytes
* @param offset the offset in the buffer where the bytes begin
* @param len how many bytes of certificate exist
*
* @exception IOException when the certificate is improperly encoded.
*/
public X509Cert(byte buf [], int offset, int len) throws IOException
{
DerValue in = new DerValue (buf, offset, len);
parse (in);
if (in.data.available () != 0)
throw new CertParseError ("garbage at end");
signedCert = new byte [len];
System.arraycopy (buf, offset, signedCert, 0, len);
}
/**
* Unmarshal a certificate from its encoded form, parsing a DER value.
* This form of constructor is used by agents which need to examine
* and use certificate contents.
*
* @param derVal the der value containing the encoded cert.
* @exception IOException when the certificate is improperly encoded.
*/
public X509Cert(DerValue derVal) throws IOException
{
parse (derVal);
if (derVal.data.available () != 0)
throw new CertParseError ("garbage at end");
signedCert = derVal.toByteArray ();
}
/**
* Partially constructs a certificate from descriptive parameters.
* This constructor may be used by Certificate Authority (CA) code,
* which later <a href="#signAndEncode">signs and encodes</a> the
* certificate. Also, self-signed certificates serve as CA certificates,
* and are sometimes used as certificate requests.
*
* <P>Until the certificate has been signed and encoded, some of
* the mandatory fields in the certificate will not be available
* via accessor functions: the serial number, issuer name and signing
* algorithm, and of course the signed certificate. The fields passed
* to this constructor are available, and must be non-null.
*
* <P>Note that the public key being signed is generally independent of
* the signature algorithm being used. So for example Diffie-Hellman
* keys (which do not support signatures) can be placed in X.509
* certificates when some other signature algorithm (e.g. DSS/DSA,
* or one of the RSA based algorithms) is used.
*
* @see CertAndKeyGen
*
* @param subjectName the X.500 distinguished name being certified
* @param subjectPublicKey the public key being certified. This
* must be an "X509Key" implementing the "PublicKey" interface.
* @param notBefore the first time the certificate is valid
* @param notAfter the last time the certificate is valid
*
* @exception CertException if the public key is inappropriate
*/
public X509Cert(X500Name subjectName, X509Key subjectPublicKey,
Date notBefore, Date notAfter) throws CertException
{
subject = subjectName;
if (!(subjectPublicKey instanceof PublicKey))
throw new CertException (CertException.err_INVALID_PUBLIC_KEY,
"Doesn't implement PublicKey interface");
// The X509 cert API requires X509 keys, else things break.
pubkey = subjectPublicKey;
notbefore = notBefore;
notafter = notAfter;
version = 0;
}
/**
* Decode an X.509 certificate from an input stream.
*
* @param in an input stream holding at least one certificate
* @exception IOException when the certificate is improperly encoded, or
* if it has already been parsed.
*/
public void decode(InputStream in) throws IOException
{
DerValue val = new DerValue(in);
parse(val);
signedCert = val.toByteArray();
}
/**
* Appends the certificate to an output stream.
*
* @param out an input stream to which the certificate is appended.
* @exception IOException when appending fails.
*/
public void encode (OutputStream out) throws IOException
{ out.write (getSignedCert ()); }
/**
* Compares two certificates. This is false if the
* certificates are not both X.509 certs, otherwise it
* compares them as binary data.
*
* @param other the object being compared with this one
* @return true iff the certificates are equivalent
*/
public boolean equals (Object other)
{
if (other instanceof X509Cert)
return equals ((X509Cert) other);
else
return false;
}
/**
* Compares two certificates, returning false if any data
* differs between the two.
*
* @param other the object being compared with this one
* @return true iff the certificates are equivalent
*/
public boolean equals (X509Cert src)
{
if (this == src)
return true;
if (signedCert == null || src.signedCert == null)
return false;
if (signedCert.length != src.signedCert.length)
return false;
for (int i = 0; i < signedCert.length; i++)
if (signedCert [i] != src.signedCert [i])
return false;
return true;
}
/** Returns the "X.509" format identifier. */
public String getFormat () // for Certificate
{ return "X.509"; }
/** Returns <a href="#getIssuerName">getIssuerName</a> */
public Principal getGuarantor () // for Certificate
{ return getIssuerName (); }
/** Returns <a href="#getSubjectName">getSubjectName</a> */
public Principal getPrincipal ()
{ return getSubjectName (); }
/**
* Throws an exception if the certificate is invalid because it is
* now outside of the certificate's validity period, or because it
* was not signed using the verification key provided. Successfully
* verifying a certificate does <em>not</em> indicate that one should
* trust the entity which it represents.
*
* <P><em>Note that since this class represents only a single X.509
* certificate, it cannot know anything about the certificate chain
* which is used to provide the verification key and to establish trust.
* Other code must manage and use those cert chains.
*
* <P>For now, you must walk the cert chain being used to verify any
* given cert. Start at the root, which is a self-signed certificate;
* verify it using the key inside the certificate. Then use that to
* verify the next certificate in the chain, issued by that CA. In
* this manner, verify each certificate until you reach the particular
* certificate you wish to verify. You should not use a certificate
* if any of the verification operations for its certificate chain
* were unsuccessful.
* </em>
*
* @param issuerPublicKey the public key of the issuing CA
* @exception CertException when the certificate is not valid.
*/
public void verify (PublicKey issuerPublicKey)
throws CertException
{
Date now = new Date ();
if (now.before (notbefore))
throw new CertException (CertException.verf_INVALID_NOTBEFORE);
if (now.after (notafter))
throw new CertException (CertException.verf_INVALID_EXPIRED);
if (signedCert == null)
throw new CertException (CertException.verf_INVALID_SIG,
"?? certificate is not signed yet ??");
//
// Verify the signature ...
//
String algName = null;
try {
Signature sigVerf = null;
algName = issuerSigAlg.getName();
sigVerf = Signature.getInstance(algName);
sigVerf.initVerify (issuerPublicKey);
sigVerf.update (rawCert, 0, rawCert.length);
if (!sigVerf.verify (signature)) {
throw new CertException (CertException.verf_INVALID_SIG,
"Signature ... by <" + issuer + "> for <" + subject + ">");
}
// Gag -- too many catch clauses, let most through.
} catch (NoSuchAlgorithmException e) {
throw new CertException (CertException.verf_INVALID_SIG,
"Unsupported signature algorithm (" + algName + ")");
} catch (InvalidKeyException e) {
// e.printStackTrace();
throw new CertException (CertException.err_INVALID_PUBLIC_KEY,
"Algorithm (" + algName + ") rejected public key");
} catch (SignatureException e) {
throw new CertException (CertException.verf_INVALID_SIG,
"Signature by <" + issuer + "> for <" + subject + ">");
}
}
/**
* Creates an X.509 certificate, and signs it using the issuer
* passed (associating a signature algorithm and an X.500 name).
* This operation is used to implement the certificate generation
* functionality of a certificate authority.
*
* @see #getSignedCert
* @see #getSigner
* @see CertAndKeyGen
*
* @param serial the serial number of the certificate (non-null)
* @param issuer the certificate issuer (CA) (non-null)
* @return the signed certificate, as returned by getSignedCert
*
* @exception IOException if any of the data could not be encoded,
* or when any mandatory data was omitted
* @exception SignatureException on signing failures
*/
public byte []
encodeAndSign (
BigInteger serial,
X500Signer issuer
) throws IOException, SignatureException
{
rawCert = null;
/*
* Get the remaining cert parameters, and make sure we have enough.
*
* We deduce version based on what attribute data are available
* For now, we have no attributes, so we always deduce X.509v1 !
*/
version = 0;
serialnum = serial;
this.issuer = issuer.getSigner ();
issuerSigAlg = issuer.getAlgorithmId ();
if (subject == null || pubkey == null
|| notbefore == null || notafter == null)
throw new IOException ("not enough cert parameters");
/*
* Encode the raw cert, create its signature and put it
* into the envelope.
*/
rawCert = DERencode ();
signedCert = sign (issuer, rawCert);
return signedCert;
}
/**
* Returns an X500Signer that may be used to create signatures. Those
* signature may in turn be verified using this certificate (or a
* copy of it).
*
* <P><em><b>NOTE:</b> If the private key is by itself capable of
* creating signatures, this fact may not be recognized at this time.
* Specifically, the case of DSS/DSA keys which get their algorithm
* parameters from higher in the certificate chain is not supportable
* without using an X509CertChain API, and there is no current support
* for other sources of algorithm parameters.</em>
*
* @param algorithm the signature algorithm to be used. Note that a
* given public/private key pair may support several such algorithms.
* @param privateKey the private key used to create the signature,
* which must correspond to the public key in this certificate
* @return the Signer object
*
* @exception NoSuchAlgorithmException if the signature
* algorithm is not supported
* @exception InvalidKeyException if either the key in the certificate,
* or the private key parameter, does not support the requested
* signature algorithm
*/
public X500Signer getSigner (AlgorithmId algorithmId,
PrivateKey privateKey)
throws NoSuchAlgorithmException, InvalidKeyException
{
String algorithm;
Signature sig;
if (privateKey instanceof Key) {
Key key = (Key)privateKey;
algorithm = key.getAlgorithm();
} else {
throw new InvalidKeyException("private key not a key!");
}
sig = Signature.getInstance(algorithmId.getName());
if (!pubkey.getAlgorithm ().equals (algorithm)) {
throw new InvalidKeyException( "Private key algorithm " +
algorithm +
" incompatible with certificate " +
pubkey.getAlgorithm());
}
sig.initSign (privateKey);
return new X500Signer (sig, subject);
}
/**
* Returns a signature object that may be used to verify signatures
* created using a specified signature algorithm and the public key
* contained in this certificate.
*
* <P><em><b>NOTE:</b> If the public key in this certificate is not by
* itself capable of verifying signatures, this may not be recognized
* at this time. Specifically, the case of DSS/DSA keys which get
* their algorithm parameters from higher in the certificate chain
* is not supportable without using an X509CertChain API, and there
* is no current support for other sources of algorithm parameters.</em>
*
* @param algorithm the algorithm of the signature to be verified
* @return the Signature object
* @exception NoSuchAlgorithmException if the signature
* algorithm is not supported
* @exception InvalidKeyException if the key in the certificate
* does not support the requested signature algorithm
*/
public Signature getVerifier(String algorithm)
throws NoSuchAlgorithmException, InvalidKeyException
{
String algName;
Signature sig;
sig = Signature.getInstance(algorithm);
sig.initVerify (pubkey);
return sig;
}
/**
* Return the signed X.509 certificate as a byte array.
* The bytes are in standard DER marshaled form.
* Null is returned in the case of a partially constructed cert.
*/
public byte [] getSignedCert ()
{ return signedCert.clone(); }
/**
* Returns the certificate's serial number.
* Null is returned in the case of a partially constructed cert.
*/
public BigInteger getSerialNumber ()
{ return serialnum; }
/**
* Returns the subject's X.500 distinguished name.
*/
public X500Name getSubjectName ()
{ return subject; }
/**
* Returns the certificate issuer's X.500 distinguished name.
* Null is returned in the case of a partially constructed cert.
*/
public X500Name getIssuerName ()
{ return issuer; }
/**
* Returns the algorithm used by the issuer to sign the certificate.
* Null is returned in the case of a partially constructed cert.
*/
public AlgorithmId getIssuerAlgorithmId ()
{ return issuerSigAlg; }
/**
* Returns the first time the certificate is valid.
*/
public Date getNotBefore ()
{ return new Date(notbefore.getTime()); }
/**
* Returns the last time the certificate is valid.
*/
public Date getNotAfter ()
{ return new Date(notafter.getTime()); }
/**
* Returns the subject's public key. Note that some public key
* algorithms support an optional certificate generation policy
* where the keys in the certificates are not in themselves sufficient
* to perform a public key operation. Those keys need to be augmented
* by algorithm parameters, which the certificate generation policy
* chose not to place in the certificate.
*
* <P>Two such public key algorithms are: DSS/DSA, where algorithm
* parameters could be acquired from a CA certificate in the chain
* of issuers; and Diffie-Hellman, with a similar solution although
* the CA then needs both a Diffie-Hellman certificate and a signature
* capable certificate.
*/
public PublicKey getPublicKey ()
{ return pubkey; }
/**
* Returns the X.509 version number of this certificate, zero based.
* That is, "2" indicates an X.509 version 3 (1993) certificate,
* and "0" indicates X.509v1 (1988).
* Zero is returned in the case of a partially constructed cert.
*/
public int getVersion ()
{ return version; }
/**
* Calculates a hash code value for the object. Objects
* which are equal will also have the same hashcode.
*/
public int hashCode ()
{
int retval = 0;
for (int i = 0; i < signedCert.length; i++)
retval += signedCert [i] * i;
return retval;
}
/**
* Returns a printable representation of the certificate. This does not
* contain all the information available to distinguish this from any
* other certificate. The certificate must be fully constructed
* before this function may be called; in particular, if you are
* creating certificates you must call encodeAndSign() before calling
* this function.
*/
public String toString ()
{
String s;
if (subject == null || pubkey == null
|| notbefore == null || notafter == null
|| issuer == null || issuerSigAlg == null
|| serialnum == null)
throw new NullPointerException ("X.509 cert is incomplete");
s = " X.509v" + (version + 1) + " certificate,\n";
s += " Subject is " + subject + "\n";
s += " Key: " + pubkey;
s += " Validity <" + notbefore + "> until <" + notafter + ">\n";
s += " Issuer is " + issuer + "\n";
s += " Issuer signature used " + issuerSigAlg.toString () + "\n";
s += " Serial number = " + Debug.toHexString(serialnum) + "\n";
// optional v2, v3 extras
return "[\n" + s + "]";
}
/**
* Returns a printable representation of the certificate.
*
* @param detailed true iff lots of detail is requested
*/
public String toString (boolean detailed)
{ return toString (); }
/************************************************************/
/*
* Cert is a SIGNED ASN.1 macro, a three elment sequence:
*
* - Data to be signed (ToBeSigned) -- the "raw" cert
* - Signature algorithm (SigAlgId)
* - The signature bits
*
* This routine unmarshals the certificate, saving the signature
* parts away for later verification.
*/
private void parse (DerValue val) throws IOException
{
if (parsed == true) {
throw new IOException("Certificate already parsed");
}
DerValue seq [] = new DerValue [3];
seq [0] = val.data.getDerValue ();
seq [1] = val.data.getDerValue ();
seq [2] = val.data.getDerValue ();
if (val.data.available () != 0)
throw new CertParseError ("signed overrun, bytes = "
+ val.data.available ());
if (seq [0].tag != DerValue.tag_Sequence)
throw new CertParseError ("signed fields invalid");
rawCert = seq [0].toByteArray (); // XXX slow; fixme!
issuerSigAlg = AlgorithmId.parse (seq [1]);
signature = seq [2].getBitString ();
if (seq [1].data.available () != 0) {
// XXX why was this error check commented out?
// It was originally part of the next check.
throw new CertParseError ("algid field overrun");
}
if (seq [2].data.available () != 0)
throw new CertParseError ("signed fields overrun");
/*
* Let's have fun parsing the cert itself.
*/
DerInputStream in;
DerValue tmp;
in = seq [0].data;
/*
* Version -- this is optional (default zero). If it's there it's
* the first field and is specially tagged.
*
* Both branches leave "tmp" holding a value for the serial
* number that comes next.
*/
version = 0;
tmp = in.getDerValue ();
if (tmp.isConstructed () && tmp.isContextSpecific ()) {
version = tmp.data.getInteger();
if (tmp.data.available () != 0)
throw new IOException ("X.509 version, bad format");
tmp = in.getDerValue ();
}
/*
* serial number ... an integer
*/
serialnum = tmp.getBigInteger ();
/*
* algorithm type for CA's signature ... needs to match the
* one on the envelope, and that's about it! different IDs
* may represent a signature attack. In general we want to
* inherit parameters.
*/
tmp = in.getDerValue ();
{
AlgorithmId algid;
algid = AlgorithmId.parse(tmp);
if (!algid.equals (issuerSigAlg))
throw new CertParseError ("CA Algorithm mismatch!");
this.algid = algid;
}
/*
* issuer name
*/
issuer = new X500Name (in);
/*
* validity: SEQUENCE { start date, end date }
*/
tmp = in.getDerValue ();
if (tmp.tag != DerValue.tag_Sequence)
throw new CertParseError ("corrupt validity field");
notbefore = tmp.data.getUTCTime ();
notafter = tmp.data.getUTCTime ();
if (tmp.data.available () != 0)
throw new CertParseError ("excess validity data");
/*
* subject name and public key
*/
subject = new X500Name (in);
tmp = in.getDerValue ();
pubkey = X509Key.parse (tmp);
/*
* XXX for v2 and later, a bunch of tagged options follow
*/
if (in.available () != 0) {
/*
* Until we parse V2/V3 data ... ignore it.
*
// throw new CertParseError ("excess cert data");
System.out.println (
"@end'o'cert, optional V2/V3 data unparsed: "
+ in.available ()
+ " bytes"
);
*/
}
parsed = true;
}
/*
* Encode only the parts that will later be signed.
*/
private byte [] DERencode () throws IOException
{
DerOutputStream raw = new DerOutputStream ();
encode (raw);
return raw.toByteArray ();
}
/*
* Marshal the contents of a "raw" certificate into a DER sequence.
*/
private void encode (DerOutputStream out) throws IOException
{
DerOutputStream tmp = new DerOutputStream ();
/*
* encode serial number, issuer signing algorithm,
* and issuer name into the data we'll return
*/
tmp.putInteger (serialnum);
issuerSigAlg.encode (tmp);
issuer.encode (tmp);
/*
* Validity is a two element sequence ... encode the
* elements, then wrap them into the data we'll return
*/
{
DerOutputStream seq = new DerOutputStream ();
seq.putUTCTime (notbefore);
seq.putUTCTime (notafter);
tmp.write (DerValue.tag_Sequence, seq);
}
/*
* Encode subject (principal) and associated key
*/
subject.encode (tmp);
tmp.write(pubkey.getEncoded());
/*
* Wrap the data; encoding of the "raw" cert is now complete.
*/
out.write (DerValue.tag_Sequence, tmp);
}
/*
* Calculate the signature of the "raw" certificate,
* and marshal the cert with the signature and a
* description of the signing algorithm.
*/
private byte [] sign (X500Signer issuer, byte data [])
throws IOException, SignatureException
{
/*
* Encode the to-be-signed data, then the algorithm used
* to create the signature.
*/
DerOutputStream out = new DerOutputStream ();
DerOutputStream tmp = new DerOutputStream ();
tmp.write (data);
issuer.getAlgorithmId ().encode(tmp);
/*
* Create and encode the signature itself.
*/
issuer.update (data, 0, data.length);
signature = issuer.sign ();
tmp.putBitString (signature);
/*
* Wrap the signed data in a SEQUENCE { data, algorithm, sig }
*/
out.write (DerValue.tag_Sequence, tmp);
return out.toByteArray ();
}
/**
* Serialization write ... X.509 certificates serialize as
* themselves, and they're parsed when they get read back.
* (Actually they serialize as some type data from the
* serialization subsystem, then the cert data.)
*/
private void writeObject (java.io.ObjectOutputStream stream)
throws IOException
{ encode(stream); }
/**
* Serialization read ... X.509 certificates serialize as
* themselves, and they're parsed when they get read back.
*/
private void readObject (ObjectInputStream stream)
throws IOException
{ decode(stream); }
}

View File

@ -1,295 +0,0 @@
/*
* Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.tools.jar;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import java.util.jar.*;
import java.security.cert.Certificate;
import java.security.AccessController;
import java.security.cert.X509Certificate;
import java.security.PublicKey;
import java.security.Principal;
import sun.security.provider.SystemIdentity;
/**
* This is OBSOLETE. DO NOT USE THIS. Use
* java.util.jar.JarEntry.getCertificates instead. It has to stay here
* because some apps (namely HJ and HJV) call directly into it.
*
* This class is stripped down greatly from JDK 1.1.x.
*
* @author Roland Schemers
*/
public class JarVerifierStream extends ZipInputStream {
private JarEntry current;
private Hashtable<String, Vector<SystemIdentity>> verified
= new Hashtable<String, Vector<SystemIdentity>>();
private JarInputStream jis;
private sun.tools.jar.Manifest man = null;
/**
* construct a JarVerfierStream from an input stream.
*/
public JarVerifierStream(InputStream is)
throws IOException
{
super(is);
jis = new JarInputStream(is);
}
public void close()
throws IOException
{
jis.close();
}
public void closeEntry() throws IOException {
jis.closeEntry();
}
/**
* This method scans to see which entry we're parsing and
* keeps various state information depending on what type of
* file is being parsed. Files it treats specially are: <ul>
*
* <li>Manifest files. At any point, this stream can be queried
* for a manifest. If it is present, a Manifest object will be
* returned.
*
* <li>Block Signature file. Like with the manifest, the stream
* can be queried at any time for all blocks parsed thus far.
*
* </ul>
*/
public synchronized ZipEntry getNextEntry() throws IOException {
current = (JarEntry) jis.getNextEntry();
return current;
}
/**
* read a single byte.
*/
public int read() throws IOException {
int n = jis.read();
if (n == -1) {
addIds();
}
return n;
}
/**
* read an array of bytes.
*/
public int read(byte[] b, int off, int len) throws IOException {
int n = jis.read(b, off, len);
if (n == -1) {
addIds();
}
return n;
}
private void addIds()
{
if (current != null) {
Certificate[] certs = current.getCertificates();
if (certs != null) {
Vector<SystemIdentity> ids = getIds(certs);
if (ids != null) {
verified.put(current.getName(), ids);
}
}
}
}
/**
* Returns a Hashtable mapping filenames to vectors of identities.
*/
public Hashtable getVerifiedSignatures() {
/* we may want to return a copy of this at some point.
For now we simply trust the caller */
if (verified.isEmpty())
return null;
else
return verified;
}
/**
* Returns an enumeration of PKCS7 blocks. This looks bogus,
* but Hotjava just checks to see if enumeration is not null
* to see if anything was signed!
*/
public Enumeration getBlocks() {
if (verified.isEmpty()) {
return null;
} else {
return new Enumeration() {
public boolean hasMoreElements() { return false; }
public Object nextElement() { return null; }
};
}
}
/**
* This method used to be called by various versions of
* AppletResourceLoader, even though they didn't do anything with
* the result. We leave them and return null for backwards compatability.
*/
public Hashtable getNameToHash() {
return null;
}
/**
* Convert java.util.jar.Manifest object to a sun.tools.jar.Manifest
* object.
*/
public sun.tools.jar.Manifest getManifest() {
if (man == null) {
try {
java.util.jar.Manifest jman = jis.getManifest();
if (jman == null)
return null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
jman.write(baos);
byte[] data = baos.toByteArray();
man = new sun.tools.jar.Manifest(data);
} catch (IOException ioe) {
// return null
}
}
return man;
}
static class CertCache {
Certificate [] certs;
Vector<SystemIdentity> ids;
boolean equals(Certificate[] certs) {
if (this.certs == null) {
if (certs!= null)
return false;
else
return true;
}
if (certs == null)
return false;
boolean match;
for (int i = 0; i < certs.length; i++) {
match = false;
for (int j = 0; j < this.certs.length; j++) {
if (certs[i].equals(this.certs[j])) {
match = true;
break;
}
}
if (!match) return false;
}
for (int i = 0; i < this.certs.length; i++) {
match = false;
for (int j = 0; j < certs.length; j++) {
if (this.certs[i].equals(certs[j])) {
match = true;
break;
}
}
if (!match) return false;
}
return true;
}
}
private ArrayList<CertCache> certCache = null;
/**
* Returns the Identity vector for the given array of Certificates
*/
protected Vector<SystemIdentity> getIds(Certificate[] certs) {
if (certs == null)
return null;
if (certCache == null)
certCache = new ArrayList<CertCache>();
CertCache cc;
for (int i = 0; i < certCache.size(); i++) {
cc = certCache.get(i);
if (cc.equals(certs)) {
return cc.ids;
}
}
cc = new CertCache();
cc.certs = certs;
if (certs.length > 0) {
for (int i=0; i<certs.length; i++) {
try {
X509Certificate cert = (X509Certificate) certs[i];
Principal tmpName = cert.getSubjectDN();
final SystemIdentity id = new SystemIdentity(
tmpName.getName(),
null);
byte[] encoded = cert.getEncoded();
final java.security.Certificate oldC =
new sun.security.x509.X509Cert(encoded);
try {
AccessController.doPrivileged(
new java.security.PrivilegedExceptionAction<Void>() {
public Void run()
throws java.security.KeyManagementException
{
id.addCertificate(oldC);
return null;
}
});
} catch (java.security.PrivilegedActionException pae) {
throw (java.security.KeyManagementException)
pae.getException();
}
if (cc.ids == null)
cc.ids = new Vector<SystemIdentity>();
cc.ids.addElement(id);
} catch (java.security.KeyManagementException kme) {
// ignore if we can't create Identity
} catch (IOException ioe) {
// ignore if we can't parse
} catch (java.security.cert.CertificateEncodingException cee) {
// ignore if we can't encode
}
}
}
certCache.add(cc);
return cc.ids;
}
}