diff options
Diffstat (limited to 'prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509')
9 files changed, 0 insertions, 2956 deletions
diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/CertificateFactory.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/CertificateFactory.java deleted file mode 100644 index 03a1fe83..00000000 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/CertificateFactory.java +++ /dev/null @@ -1,395 +0,0 @@ -package org.bouncycastle.jcajce.provider.asymmetric.x509; - -import java.io.IOException; -import java.io.InputStream; -import java.io.PushbackInputStream; -import java.security.cert.CRL; -import java.security.cert.CRLException; -import java.security.cert.CertPath; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactorySpi; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.ASN1Set; -import org.bouncycastle.asn1.ASN1TaggedObject; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.SignedData; -import org.bouncycastle.asn1.x509.Certificate; -import org.bouncycastle.asn1.x509.CertificateList; - -/** - * class for dealing with X509 certificates. - * <p> - * At the moment this will deal with "-----BEGIN CERTIFICATE-----" to "-----END CERTIFICATE-----" - * base 64 encoded certs, as well as the BER binaries of certificates and some classes of PKCS#7 - * objects. - */ -public class CertificateFactory - extends CertificateFactorySpi -{ - private static final PEMUtil PEM_CERT_PARSER = new PEMUtil("CERTIFICATE"); - private static final PEMUtil PEM_CRL_PARSER = new PEMUtil("CRL"); - - private ASN1Set sData = null; - private int sDataObjectCount = 0; - private InputStream currentStream = null; - - private ASN1Set sCrlData = null; - private int sCrlDataObjectCount = 0; - private InputStream currentCrlStream = null; - - private java.security.cert.Certificate readDERCertificate( - ASN1InputStream dIn) - throws IOException, CertificateParsingException - { - ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); - - if (seq.size() > 1 - && seq.getObjectAt(0) instanceof ASN1ObjectIdentifier) - { - if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) - { - sData = SignedData.getInstance(ASN1Sequence.getInstance( - (ASN1TaggedObject)seq.getObjectAt(1), true)).getCertificates(); - - return getCertificate(); - } - } - - return new X509CertificateObject( - Certificate.getInstance(seq)); - } - - private java.security.cert.Certificate getCertificate() - throws CertificateParsingException - { - if (sData != null) - { - while (sDataObjectCount < sData.size()) - { - Object obj = sData.getObjectAt(sDataObjectCount++); - - if (obj instanceof ASN1Sequence) - { - return new X509CertificateObject( - Certificate.getInstance(obj)); - } - } - } - - return null; - } - - private java.security.cert.Certificate readPEMCertificate( - InputStream in) - throws IOException, CertificateParsingException - { - ASN1Sequence seq = PEM_CERT_PARSER.readPEMObject(in); - - if (seq != null) - { - return new X509CertificateObject( - Certificate.getInstance(seq)); - } - - return null; - } - - protected CRL createCRL(CertificateList c) - throws CRLException - { - return new X509CRLObject(c); - } - - private CRL readPEMCRL( - InputStream in) - throws IOException, CRLException - { - ASN1Sequence seq = PEM_CRL_PARSER.readPEMObject(in); - - if (seq != null) - { - return createCRL( - CertificateList.getInstance(seq)); - } - - return null; - } - - private CRL readDERCRL( - ASN1InputStream aIn) - throws IOException, CRLException - { - ASN1Sequence seq = (ASN1Sequence)aIn.readObject(); - - if (seq.size() > 1 - && seq.getObjectAt(0) instanceof ASN1ObjectIdentifier) - { - if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) - { - sCrlData = SignedData.getInstance(ASN1Sequence.getInstance( - (ASN1TaggedObject)seq.getObjectAt(1), true)).getCRLs(); - - return getCRL(); - } - } - - return createCRL( - CertificateList.getInstance(seq)); - } - - private CRL getCRL() - throws CRLException - { - if (sCrlData == null || sCrlDataObjectCount >= sCrlData.size()) - { - return null; - } - - return createCRL( - CertificateList.getInstance( - sCrlData.getObjectAt(sCrlDataObjectCount++))); - } - - /** - * Generates a certificate object and initializes it with the data - * read from the input stream inStream. - */ - public java.security.cert.Certificate engineGenerateCertificate( - InputStream in) - throws CertificateException - { - if (currentStream == null) - { - currentStream = in; - sData = null; - sDataObjectCount = 0; - } - else if (currentStream != in) // reset if input stream has changed - { - currentStream = in; - sData = null; - sDataObjectCount = 0; - } - - try - { - if (sData != null) - { - if (sDataObjectCount != sData.size()) - { - return getCertificate(); - } - else - { - sData = null; - sDataObjectCount = 0; - return null; - } - } - - PushbackInputStream pis = new PushbackInputStream(in); - int tag = pis.read(); - - if (tag == -1) - { - return null; - } - - pis.unread(tag); - - if (tag != 0x30) // assume ascii PEM encoded. - { - return readPEMCertificate(pis); - } - else - { - return readDERCertificate(new ASN1InputStream(pis)); - } - } - catch (Exception e) - { - throw new ExCertificateException(e); - } - } - - /** - * Returns a (possibly empty) collection view of the certificates - * read from the given input stream inStream. - */ - public Collection engineGenerateCertificates( - InputStream inStream) - throws CertificateException - { - java.security.cert.Certificate cert; - List certs = new ArrayList(); - - while ((cert = engineGenerateCertificate(inStream)) != null) - { - certs.add(cert); - } - - return certs; - } - - /** - * Generates a certificate revocation list (CRL) object and initializes - * it with the data read from the input stream inStream. - */ - public CRL engineGenerateCRL( - InputStream inStream) - throws CRLException - { - if (currentCrlStream == null) - { - currentCrlStream = inStream; - sCrlData = null; - sCrlDataObjectCount = 0; - } - else if (currentCrlStream != inStream) // reset if input stream has changed - { - currentCrlStream = inStream; - sCrlData = null; - sCrlDataObjectCount = 0; - } - - try - { - if (sCrlData != null) - { - if (sCrlDataObjectCount != sCrlData.size()) - { - return getCRL(); - } - else - { - sCrlData = null; - sCrlDataObjectCount = 0; - return null; - } - } - - PushbackInputStream pis = new PushbackInputStream(inStream); - int tag = pis.read(); - - if (tag == -1) - { - return null; - } - - pis.unread(tag); - - if (tag != 0x30) // assume ascii PEM encoded. - { - return readPEMCRL(pis); - } - else - { // lazy evaluate to help processing of large CRLs - return readDERCRL(new ASN1InputStream(pis, true)); - } - } - catch (CRLException e) - { - throw e; - } - catch (Exception e) - { - throw new CRLException(e.toString()); - } - } - - /** - * Returns a (possibly empty) collection view of the CRLs read from - * the given input stream inStream. - * - * The inStream may contain a sequence of DER-encoded CRLs, or - * a PKCS#7 CRL set. This is a PKCS#7 SignedData object, with the - * only signficant field being crls. In particular the signature - * and the contents are ignored. - */ - public Collection engineGenerateCRLs( - InputStream inStream) - throws CRLException - { - CRL crl; - List crls = new ArrayList(); - - while ((crl = engineGenerateCRL(inStream)) != null) - { - crls.add(crl); - } - - return crls; - } - - public Iterator engineGetCertPathEncodings() - { - return PKIXCertPath.certPathEncodings.iterator(); - } - - public CertPath engineGenerateCertPath( - InputStream inStream) - throws CertificateException - { - return engineGenerateCertPath(inStream, "PkiPath"); - } - - public CertPath engineGenerateCertPath( - InputStream inStream, - String encoding) - throws CertificateException - { - return new PKIXCertPath(inStream, encoding); - } - - public CertPath engineGenerateCertPath( - List certificates) - throws CertificateException - { - Iterator iter = certificates.iterator(); - Object obj; - while (iter.hasNext()) - { - obj = iter.next(); - if (obj != null) - { - if (!(obj instanceof X509Certificate)) - { - throw new CertificateException("list contains non X509Certificate object while creating CertPath\n" + obj.toString()); - } - } - } - return new PKIXCertPath(certificates); - } - - private class ExCertificateException - extends CertificateException - { - private Throwable cause; - - public ExCertificateException(Throwable cause) - { - this.cause = cause; - } - - public ExCertificateException(String msg, Throwable cause) - { - super(msg); - - this.cause = cause; - } - - public Throwable getCause() - { - return cause; - } - } -} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/ExtCRLException.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/ExtCRLException.java deleted file mode 100644 index e27acfbb..00000000 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/ExtCRLException.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.bouncycastle.jcajce.provider.asymmetric.x509; - -import java.security.cert.CRLException; - -class ExtCRLException - extends CRLException -{ - Throwable cause; - - ExtCRLException(String message, Throwable cause) - { - super(message); - this.cause = cause; - } - - public Throwable getCause() - { - return cause; - } -} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/KeyFactory.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/KeyFactory.java deleted file mode 100644 index a4c701d6..00000000 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/KeyFactory.java +++ /dev/null @@ -1,95 +0,0 @@ -package org.bouncycastle.jcajce.provider.asymmetric.x509; - -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.KeyFactorySpi; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.KeySpec; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; - -import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.jce.provider.BouncyCastleProvider; - -public class KeyFactory - extends KeyFactorySpi -{ - - protected PrivateKey engineGeneratePrivate( - KeySpec keySpec) - throws InvalidKeySpecException - { - if (keySpec instanceof PKCS8EncodedKeySpec) - { - try - { - PrivateKeyInfo info = PrivateKeyInfo.getInstance(((PKCS8EncodedKeySpec)keySpec).getEncoded()); - PrivateKey key = BouncyCastleProvider.getPrivateKey(info); - - if (key != null) - { - return key; - } - - throw new InvalidKeySpecException("no factory found for OID: " + info.getPrivateKeyAlgorithm().getAlgorithm()); - } - catch (Exception e) - { - throw new InvalidKeySpecException(e.toString()); - } - } - - throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName()); - } - - protected PublicKey engineGeneratePublic( - KeySpec keySpec) - throws InvalidKeySpecException - { - if (keySpec instanceof X509EncodedKeySpec) - { - try - { - SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(((X509EncodedKeySpec)keySpec).getEncoded()); - PublicKey key = BouncyCastleProvider.getPublicKey(info); - - if (key != null) - { - return key; - } - - throw new InvalidKeySpecException("no factory found for OID: " + info.getAlgorithm().getAlgorithm()); - } - catch (Exception e) - { - throw new InvalidKeySpecException(e.toString()); - } - } - - throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName()); - } - - protected KeySpec engineGetKeySpec(Key key, Class keySpec) - throws InvalidKeySpecException - { - if (keySpec.isAssignableFrom(PKCS8EncodedKeySpec.class) && key.getFormat().equals("PKCS#8")) - { - return new PKCS8EncodedKeySpec(key.getEncoded()); - } - else if (keySpec.isAssignableFrom(X509EncodedKeySpec.class) && key.getFormat().equals("X.509")) - { - return new X509EncodedKeySpec(key.getEncoded()); - } - - throw new InvalidKeySpecException("not implemented yet " + key + " " + keySpec); - } - - protected Key engineTranslateKey(Key key) - throws InvalidKeyException - { - throw new InvalidKeyException("not implemented yet " + key); - } -}
\ No newline at end of file diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/PEMUtil.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/PEMUtil.java deleted file mode 100644 index e4aaf307..00000000 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/PEMUtil.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.bouncycastle.jcajce.provider.asymmetric.x509; - -import java.io.IOException; -import java.io.InputStream; - -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.util.encoders.Base64; - -public class PEMUtil -{ - private final String _header1; - private final String _header2; - private final String _footer1; - private final String _footer2; - - PEMUtil( - String type) - { - _header1 = "-----BEGIN " + type + "-----"; - _header2 = "-----BEGIN X509 " + type + "-----"; - _footer1 = "-----END " + type + "-----"; - _footer2 = "-----END X509 " + type + "-----"; - } - - private String readLine( - InputStream in) - throws IOException - { - int c; - StringBuffer l = new StringBuffer(); - - do - { - while (((c = in.read()) != '\r') && c != '\n' && (c >= 0)) - { - l.append((char)c); - } - } - while (c >= 0 && l.length() == 0); - - if (c < 0) - { - return null; - } - - return l.toString(); - } - - ASN1Sequence readPEMObject( - InputStream in) - throws IOException - { - String line; - StringBuffer pemBuf = new StringBuffer(); - - while ((line = readLine(in)) != null) - { - if (line.startsWith(_header1) || line.startsWith(_header2)) - { - break; - } - } - - while ((line = readLine(in)) != null) - { - if (line.startsWith(_footer1) || line.startsWith(_footer2)) - { - break; - } - - pemBuf.append(line); - } - - if (pemBuf.length() != 0) - { - try - { - return ASN1Sequence.getInstance(Base64.decode(pemBuf.toString())); - } - catch (Exception e) - { - throw new IOException("malformed PEM data encountered"); - } - } - - return null; - } -} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/PKIXCertPath.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/PKIXCertPath.java deleted file mode 100644 index 91d48294..00000000 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/PKIXCertPath.java +++ /dev/null @@ -1,372 +0,0 @@ -package org.bouncycastle.jcajce.provider.asymmetric.x509; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStreamWriter; -import java.security.NoSuchProviderException; -import java.security.cert.CertPath; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -import javax.security.auth.x500.X500Principal; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.asn1.DERSet; -import org.bouncycastle.asn1.pkcs.ContentInfo; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.SignedData; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.util.io.pem.PemObject; -import org.bouncycastle.util.io.pem.PemWriter; - -/** - * CertPath implementation for X.509 certificates. - * <br /> - **/ -public class PKIXCertPath - extends CertPath -{ - static final List certPathEncodings; - - static - { - List encodings = new ArrayList(); - encodings.add("PkiPath"); - encodings.add("PEM"); - encodings.add("PKCS7"); - certPathEncodings = Collections.unmodifiableList(encodings); - } - - private List certificates; - - /** - * @param certs - */ - private List sortCerts( - List certs) - { - if (certs.size() < 2) - { - return certs; - } - - X500Principal issuer = ((X509Certificate)certs.get(0)).getIssuerX500Principal(); - boolean okay = true; - - for (int i = 1; i != certs.size(); i++) - { - X509Certificate cert = (X509Certificate)certs.get(i); - - if (issuer.equals(cert.getSubjectX500Principal())) - { - issuer = ((X509Certificate)certs.get(i)).getIssuerX500Principal(); - } - else - { - okay = false; - break; - } - } - - if (okay) - { - return certs; - } - - // find end-entity cert - List retList = new ArrayList(certs.size()); - List orig = new ArrayList(certs); - - for (int i = 0; i < certs.size(); i++) - { - X509Certificate cert = (X509Certificate)certs.get(i); - boolean found = false; - - X500Principal subject = cert.getSubjectX500Principal(); - - for (int j = 0; j != certs.size(); j++) - { - X509Certificate c = (X509Certificate)certs.get(j); - if (c.getIssuerX500Principal().equals(subject)) - { - found = true; - break; - } - } - - if (!found) - { - retList.add(cert); - certs.remove(i); - } - } - - // can only have one end entity cert - something's wrong, give up. - if (retList.size() > 1) - { - return orig; - } - - for (int i = 0; i != retList.size(); i++) - { - issuer = ((X509Certificate)retList.get(i)).getIssuerX500Principal(); - - for (int j = 0; j < certs.size(); j++) - { - X509Certificate c = (X509Certificate)certs.get(j); - if (issuer.equals(c.getSubjectX500Principal())) - { - retList.add(c); - certs.remove(j); - break; - } - } - } - - // make sure all certificates are accounted for. - if (certs.size() > 0) - { - return orig; - } - - return retList; - } - - PKIXCertPath(List certificates) - { - super("X.509"); - this.certificates = sortCerts(new ArrayList(certificates)); - } - - /** - * Creates a CertPath of the specified type. - * This constructor is protected because most users should use - * a CertificateFactory to create CertPaths. - **/ - PKIXCertPath( - InputStream inStream, - String encoding) - throws CertificateException - { - super("X.509"); - try - { - if (encoding.equalsIgnoreCase("PkiPath")) - { - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Primitive derObject = derInStream.readObject(); - if (!(derObject instanceof ASN1Sequence)) - { - throw new CertificateException("input stream does not contain a ASN1 SEQUENCE while reading PkiPath encoded data to load CertPath"); - } - Enumeration e = ((ASN1Sequence)derObject).getObjects(); - certificates = new ArrayList(); - CertificateFactory certFactory = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME); - while (e.hasMoreElements()) - { - ASN1Encodable element = (ASN1Encodable)e.nextElement(); - byte[] encoded = element.toASN1Primitive().getEncoded(ASN1Encoding.DER); - certificates.add(0, certFactory.generateCertificate( - new ByteArrayInputStream(encoded))); - } - } - else if (encoding.equalsIgnoreCase("PKCS7") || encoding.equalsIgnoreCase("PEM")) - { - inStream = new BufferedInputStream(inStream); - certificates = new ArrayList(); - CertificateFactory certFactory= CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME); - Certificate cert; - while ((cert = certFactory.generateCertificate(inStream)) != null) - { - certificates.add(cert); - } - } - else - { - throw new CertificateException("unsupported encoding: " + encoding); - } - } - catch (IOException ex) - { - throw new CertificateException("IOException throw while decoding CertPath:\n" + ex.toString()); - } - catch (NoSuchProviderException ex) - { - throw new CertificateException("BouncyCastle provider not found while trying to get a CertificateFactory:\n" + ex.toString()); - } - - this.certificates = sortCerts(certificates); - } - - /** - * Returns an iteration of the encodings supported by this - * certification path, with the default encoding - * first. Attempts to modify the returned Iterator via its - * remove method result in an UnsupportedOperationException. - * - * @return an Iterator over the names of the supported encodings (as Strings) - **/ - public Iterator getEncodings() - { - return certPathEncodings.iterator(); - } - - /** - * Returns the encoded form of this certification path, using - * the default encoding. - * - * @return the encoded bytes - * @exception java.security.cert.CertificateEncodingException if an encoding error occurs - **/ - public byte[] getEncoded() - throws CertificateEncodingException - { - Iterator iter = getEncodings(); - if (iter.hasNext()) - { - Object enc = iter.next(); - if (enc instanceof String) - { - return getEncoded((String)enc); - } - } - return null; - } - - /** - * Returns the encoded form of this certification path, using - * the specified encoding. - * - * @param encoding the name of the encoding to use - * @return the encoded bytes - * @exception java.security.cert.CertificateEncodingException if an encoding error - * occurs or the encoding requested is not supported - * - **/ - public byte[] getEncoded(String encoding) - throws CertificateEncodingException - { - if (encoding.equalsIgnoreCase("PkiPath")) - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - ListIterator iter = certificates.listIterator(certificates.size()); - while (iter.hasPrevious()) - { - v.add(toASN1Object((X509Certificate)iter.previous())); - } - - return toDEREncoded(new DERSequence(v)); - } - else if (encoding.equalsIgnoreCase("PKCS7")) - { - ContentInfo encInfo = new ContentInfo(PKCSObjectIdentifiers.data, null); - - ASN1EncodableVector v = new ASN1EncodableVector(); - for (int i = 0; i != certificates.size(); i++) - { - v.add(toASN1Object((X509Certificate)certificates.get(i))); - } - - SignedData sd = new SignedData( - new ASN1Integer(1), - new DERSet(), - encInfo, - new DERSet(v), - null, - new DERSet()); - - return toDEREncoded(new ContentInfo( - PKCSObjectIdentifiers.signedData, sd)); - } - else if (encoding.equalsIgnoreCase("PEM")) - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - PemWriter pWrt = new PemWriter(new OutputStreamWriter(bOut)); - - try - { - for (int i = 0; i != certificates.size(); i++) - { - pWrt.writeObject(new PemObject("CERTIFICATE", ((X509Certificate)certificates.get(i)).getEncoded())); - } - - pWrt.close(); - } - catch (Exception e) - { - throw new CertificateEncodingException("can't encode certificate for PEM encoded path"); - } - - return bOut.toByteArray(); - } - else - { - throw new CertificateEncodingException("unsupported encoding: " + encoding); - } - } - - /** - * Returns the list of certificates in this certification - * path. The List returned must be immutable and thread-safe. - * - * @return an immutable List of Certificates (may be empty, but not null) - **/ - public List getCertificates() - { - return Collections.unmodifiableList(new ArrayList(certificates)); - } - - /** - * Return a DERObject containing the encoded certificate. - * - * @param cert the X509Certificate object to be encoded - * - * @return the DERObject - **/ - private ASN1Primitive toASN1Object( - X509Certificate cert) - throws CertificateEncodingException - { - try - { - return new ASN1InputStream(cert.getEncoded()).readObject(); - } - catch (Exception e) - { - throw new CertificateEncodingException("Exception while encoding certificate: " + e.toString()); - } - } - - private byte[] toDEREncoded(ASN1Encodable obj) - throws CertificateEncodingException - { - try - { - return obj.toASN1Primitive().getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CertificateEncodingException("Exception thrown: " + e); - } - } -} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLEntryObject.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLEntryObject.java deleted file mode 100644 index 32e595c2..00000000 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLEntryObject.java +++ /dev/null @@ -1,318 +0,0 @@ -package org.bouncycastle.jcajce.provider.asymmetric.x509; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.cert.CRLException; -import java.security.cert.X509CRLEntry; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Set; - -import javax.security.auth.x500.X500Principal; - -import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1Enumerated; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.util.ASN1Dump; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x509.CRLReason; -import org.bouncycastle.asn1.x509.Extension; -import org.bouncycastle.asn1.x509.Extensions; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.asn1.x509.GeneralNames; -import org.bouncycastle.asn1.x509.TBSCertList; -import org.bouncycastle.asn1.x509.X509Extension; - -/** - * The following extensions are listed in RFC 2459 as relevant to CRL Entries - * - * ReasonCode Hode Instruction Code Invalidity Date Certificate Issuer - * (critical) - */ -public class X509CRLEntryObject extends X509CRLEntry -{ - private TBSCertList.CRLEntry c; - - private X500Name certificateIssuer; - private int hashValue; - private boolean isHashValueSet; - - protected X509CRLEntryObject(TBSCertList.CRLEntry c) - { - this.c = c; - this.certificateIssuer = null; - } - - /** - * Constructor for CRLEntries of indirect CRLs. If <code>isIndirect</code> - * is <code>false</code> {@link #getCertificateIssuer()} will always - * return <code>null</code>, <code>previousCertificateIssuer</code> is - * ignored. If this <code>isIndirect</code> is specified and this CRLEntry - * has no certificate issuer CRL entry extension - * <code>previousCertificateIssuer</code> is returned by - * {@link #getCertificateIssuer()}. - * - * @param c - * TBSCertList.CRLEntry object. - * @param isIndirect - * <code>true</code> if the corresponding CRL is a indirect - * CRL. - * @param previousCertificateIssuer - * Certificate issuer of the previous CRLEntry. - */ - protected X509CRLEntryObject( - TBSCertList.CRLEntry c, - boolean isIndirect, - X500Name previousCertificateIssuer) - { - this.c = c; - this.certificateIssuer = loadCertificateIssuer(isIndirect, previousCertificateIssuer); - } - - /** - * Will return true if any extensions are present and marked as critical as - * we currently don't handle any extensions! - */ - public boolean hasUnsupportedCriticalExtension() - { - Set extns = getCriticalExtensionOIDs(); - - return extns != null && !extns.isEmpty(); - } - - private X500Name loadCertificateIssuer(boolean isIndirect, X500Name previousCertificateIssuer) - { - if (!isIndirect) - { - return null; - } - - Extension ext = getExtension(Extension.certificateIssuer); - if (ext == null) - { - return previousCertificateIssuer; - } - - try - { - GeneralName[] names = GeneralNames.getInstance(ext.getParsedValue()).getNames(); - for (int i = 0; i < names.length; i++) - { - if (names[i].getTagNo() == GeneralName.directoryName) - { - return X500Name.getInstance(names[i].getName()); - } - } - return null; - } - catch (Exception e) - { - return null; - } - } - - public X500Principal getCertificateIssuer() - { - if (certificateIssuer == null) - { - return null; - } - try - { - return new X500Principal(certificateIssuer.getEncoded()); - } - catch (IOException e) - { - return null; - } - } - - private Set getExtensionOIDs(boolean critical) - { - Extensions extensions = c.getExtensions(); - - if (extensions != null) - { - Set set = new HashSet(); - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (critical == ext.isCritical()) - { - set.add(oid.getId()); - } - } - - return set; - } - - return null; - } - - public Set getCriticalExtensionOIDs() - { - return getExtensionOIDs(true); - } - - public Set getNonCriticalExtensionOIDs() - { - return getExtensionOIDs(false); - } - - private Extension getExtension(ASN1ObjectIdentifier oid) - { - Extensions exts = c.getExtensions(); - - if (exts != null) - { - return exts.getExtension(oid); - } - - return null; - } - - public byte[] getExtensionValue(String oid) - { - Extension ext = getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new RuntimeException("error encoding " + e.toString()); - } - } - - return null; - } - - /** - * Cache the hashCode value - calculating it with the standard method. - * @return calculated hashCode. - */ - public int hashCode() - { - if (!isHashValueSet) - { - hashValue = super.hashCode(); - isHashValueSet = true; - } - - return hashValue; - } - - public boolean equals(Object o) - { - if (o == this) - { - return true; - } - - if (o instanceof X509CRLEntryObject) - { - X509CRLEntryObject other = (X509CRLEntryObject)o; - - return this.c.equals(other.c); - } - - return super.equals(this); - } - - public byte[] getEncoded() - throws CRLException - { - try - { - return c.getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CRLException(e.toString()); - } - } - - public BigInteger getSerialNumber() - { - return c.getUserCertificate().getValue(); - } - - public Date getRevocationDate() - { - return c.getRevocationDate().getDate(); - } - - public boolean hasExtensions() - { - return c.getExtensions() != null; - } - - public String toString() - { - StringBuffer buf = new StringBuffer(); - String nl = System.getProperty("line.separator"); - - buf.append(" userCertificate: ").append(this.getSerialNumber()).append(nl); - buf.append(" revocationDate: ").append(this.getRevocationDate()).append(nl); - buf.append(" certificateIssuer: ").append(this.getCertificateIssuer()).append(nl); - - Extensions extensions = c.getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - if (e.hasMoreElements()) - { - buf.append(" crlEntryExtensions:").append(nl); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - if (ext.getExtnValue() != null) - { - byte[] octs = ext.getExtnValue().getOctets(); - ASN1InputStream dIn = new ASN1InputStream(octs); - buf.append(" critical(").append(ext.isCritical()).append(") "); - try - { - if (oid.equals(X509Extension.reasonCode)) - { - buf.append(CRLReason.getInstance(ASN1Enumerated.getInstance(dIn.readObject()))).append(nl); - } - else if (oid.equals(X509Extension.certificateIssuer)) - { - buf.append("Certificate issuer: ").append(GeneralNames.getInstance(dIn.readObject())).append(nl); - } - else - { - buf.append(oid.getId()); - buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl); - } - } - catch (Exception ex) - { - buf.append(oid.getId()); - buf.append(" value = ").append("*****").append(nl); - } - } - else - { - buf.append(nl); - } - } - } - } - - return buf.toString(); - } -} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLObject.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLObject.java deleted file mode 100644 index c7d04020..00000000 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CRLObject.java +++ /dev/null @@ -1,627 +0,0 @@ -package org.bouncycastle.jcajce.provider.asymmetric.x509; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Principal; -import java.security.PublicKey; -import java.security.Signature; -import java.security.SignatureException; -import java.security.cert.CRLException; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509CRL; -import java.security.cert.X509CRLEntry; -import java.security.cert.X509Certificate; -import java.util.Collections; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import javax.security.auth.x500.X500Principal; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1OctetString; -import org.bouncycastle.asn1.util.ASN1Dump; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x509.CRLDistPoint; -import org.bouncycastle.asn1.x509.CRLNumber; -import org.bouncycastle.asn1.x509.CertificateList; -import org.bouncycastle.asn1.x509.Extension; -import org.bouncycastle.asn1.x509.Extensions; -import org.bouncycastle.asn1.x509.GeneralNames; -import org.bouncycastle.asn1.x509.IssuingDistributionPoint; -import org.bouncycastle.asn1.x509.TBSCertList; -import org.bouncycastle.jce.X509Principal; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.jce.provider.RFC3280CertPathUtilities; -import org.bouncycastle.util.encoders.Hex; - -/** - * The following extensions are listed in RFC 2459 as relevant to CRLs - * - * Authority Key Identifier - * Issuer Alternative Name - * CRL Number - * Delta CRL Indicator (critical) - * Issuing Distribution Point (critical) - */ -public class X509CRLObject - extends X509CRL -{ - private CertificateList c; - private String sigAlgName; - private byte[] sigAlgParams; - private boolean isIndirect; - private boolean isHashCodeSet = false; - private int hashCodeValue; - - static boolean isIndirectCRL(X509CRL crl) - throws CRLException - { - try - { - byte[] idp = crl.getExtensionValue(Extension.issuingDistributionPoint.getId()); - return idp != null - && IssuingDistributionPoint.getInstance(ASN1OctetString.getInstance(idp).getOctets()).isIndirectCRL(); - } - catch (Exception e) - { - throw new ExtCRLException( - "Exception reading IssuingDistributionPoint", e); - } - } - - protected X509CRLObject( - CertificateList c) - throws CRLException - { - this.c = c; - - try - { - this.sigAlgName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm()); - - if (c.getSignatureAlgorithm().getParameters() != null) - { - this.sigAlgParams = ((ASN1Encodable)c.getSignatureAlgorithm().getParameters()).toASN1Primitive().getEncoded(ASN1Encoding.DER); - } - else - { - this.sigAlgParams = null; - } - - this.isIndirect = isIndirectCRL(this); - } - catch (Exception e) - { - throw new CRLException("CRL contents invalid: " + e); - } - } - - /** - * Will return true if any extensions are present and marked - * as critical as we currently dont handle any extensions! - */ - public boolean hasUnsupportedCriticalExtension() - { - Set extns = getCriticalExtensionOIDs(); - - if (extns == null) - { - return false; - } - - extns.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT); - extns.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR); - - return !extns.isEmpty(); - } - - private Set getExtensionOIDs(boolean critical) - { - if (this.getVersion() == 2) - { - Extensions extensions = c.getTBSCertList().getExtensions(); - - if (extensions != null) - { - Set set = new HashSet(); - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (critical == ext.isCritical()) - { - set.add(oid.getId()); - } - } - - return set; - } - } - - return null; - } - - public Set getCriticalExtensionOIDs() - { - return getExtensionOIDs(true); - } - - public Set getNonCriticalExtensionOIDs() - { - return getExtensionOIDs(false); - } - - public byte[] getExtensionValue(String oid) - { - Extensions exts = c.getTBSCertList().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("error parsing " + e.toString()); - } - } - } - - return null; - } - - public byte[] getEncoded() - throws CRLException - { - try - { - return c.getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CRLException(e.toString()); - } - } - - public void verify(PublicKey key) - throws CRLException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - verify(key, BouncyCastleProvider.PROVIDER_NAME); - } - - public void verify(PublicKey key, String sigProvider) - throws CRLException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - if (!c.getSignatureAlgorithm().equals(c.getTBSCertList().getSignature())) - { - throw new CRLException("Signature algorithm on CertificateList does not match TBSCertList."); - } - - Signature sig; - - if (sigProvider != null) - { - sig = Signature.getInstance(getSigAlgName(), sigProvider); - } - else - { - sig = Signature.getInstance(getSigAlgName()); - } - - sig.initVerify(key); - sig.update(this.getTBSCertList()); - - if (!sig.verify(this.getSignature())) - { - throw new SignatureException("CRL does not verify with supplied public key."); - } - } - - public int getVersion() - { - return c.getVersionNumber(); - } - - public Principal getIssuerDN() - { - return new X509Principal(X500Name.getInstance(c.getIssuer().toASN1Primitive())); - } - - public X500Principal getIssuerX500Principal() - { - try - { - return new X500Principal(c.getIssuer().getEncoded()); - } - catch (IOException e) - { - throw new IllegalStateException("can't encode issuer DN"); - } - } - - public Date getThisUpdate() - { - return c.getThisUpdate().getDate(); - } - - public Date getNextUpdate() - { - if (c.getNextUpdate() != null) - { - return c.getNextUpdate().getDate(); - } - - return null; - } - - private Set loadCRLEntries() - { - Set entrySet = new HashSet(); - Enumeration certs = c.getRevokedCertificateEnumeration(); - - X500Name previousCertificateIssuer = null; // the issuer - while (certs.hasMoreElements()) - { - TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)certs.nextElement(); - X509CRLEntryObject crlEntry = new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer); - entrySet.add(crlEntry); - if (isIndirect && entry.hasExtensions()) - { - Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer); - - if (currentCaName != null) - { - previousCertificateIssuer = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); - } - } - } - - return entrySet; - } - - public X509CRLEntry getRevokedCertificate(BigInteger serialNumber) - { - Enumeration certs = c.getRevokedCertificateEnumeration(); - - X500Name previousCertificateIssuer = null; // the issuer - while (certs.hasMoreElements()) - { - TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)certs.nextElement(); - - if (serialNumber.equals(entry.getUserCertificate().getValue())) - { - return new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer); - } - - if (isIndirect && entry.hasExtensions()) - { - Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer); - - if (currentCaName != null) - { - previousCertificateIssuer = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); - } - } - } - - return null; - } - - public Set getRevokedCertificates() - { - Set entrySet = loadCRLEntries(); - - if (!entrySet.isEmpty()) - { - return Collections.unmodifiableSet(entrySet); - } - - return null; - } - - public byte[] getTBSCertList() - throws CRLException - { - try - { - return c.getTBSCertList().getEncoded("DER"); - } - catch (IOException e) - { - throw new CRLException(e.toString()); - } - } - - public byte[] getSignature() - { - return c.getSignature().getBytes(); - } - - public String getSigAlgName() - { - return sigAlgName; - } - - public String getSigAlgOID() - { - return c.getSignatureAlgorithm().getAlgorithm().getId(); - } - - public byte[] getSigAlgParams() - { - if (sigAlgParams != null) - { - byte[] tmp = new byte[sigAlgParams.length]; - - System.arraycopy(sigAlgParams, 0, tmp, 0, tmp.length); - - return tmp; - } - - return null; - } - - /** - * Returns a string representation of this CRL. - * - * @return a string representation of this CRL. - */ - public String toString() - { - StringBuffer buf = new StringBuffer(); - String nl = System.getProperty("line.separator"); - - buf.append(" Version: ").append(this.getVersion()).append( - nl); - buf.append(" IssuerDN: ").append(this.getIssuerDN()) - .append(nl); - buf.append(" This update: ").append(this.getThisUpdate()) - .append(nl); - buf.append(" Next update: ").append(this.getNextUpdate()) - .append(nl); - buf.append(" Signature Algorithm: ").append(this.getSigAlgName()) - .append(nl); - - byte[] sig = this.getSignature(); - - buf.append(" Signature: ").append( - new String(Hex.encode(sig, 0, 20))).append(nl); - for (int i = 20; i < sig.length; i += 20) - { - if (i < sig.length - 20) - { - buf.append(" ").append( - new String(Hex.encode(sig, i, 20))).append(nl); - } - else - { - buf.append(" ").append( - new String(Hex.encode(sig, i, sig.length - i))).append(nl); - } - } - - Extensions extensions = c.getTBSCertList().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - if (e.hasMoreElements()) - { - buf.append(" Extensions: ").append(nl); - } - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (ext.getExtnValue() != null) - { - byte[] octs = ext.getExtnValue().getOctets(); - ASN1InputStream dIn = new ASN1InputStream(octs); - buf.append(" critical(").append( - ext.isCritical()).append(") "); - try - { - if (oid.equals(Extension.cRLNumber)) - { - buf.append( - new CRLNumber(ASN1Integer.getInstance( - dIn.readObject()).getPositiveValue())) - .append(nl); - } - else if (oid.equals(Extension.deltaCRLIndicator)) - { - buf.append( - "Base CRL: " - + new CRLNumber(ASN1Integer.getInstance( - dIn.readObject()).getPositiveValue())) - .append(nl); - } - else if (oid - .equals(Extension.issuingDistributionPoint)) - { - buf.append( - IssuingDistributionPoint.getInstance(dIn.readObject())).append(nl); - } - else if (oid - .equals(Extension.cRLDistributionPoints)) - { - buf.append( - CRLDistPoint.getInstance(dIn.readObject())).append(nl); - } - else if (oid.equals(Extension.freshestCRL)) - { - buf.append( - CRLDistPoint.getInstance(dIn.readObject())).append(nl); - } - else - { - buf.append(oid.getId()); - buf.append(" value = ").append( - ASN1Dump.dumpAsString(dIn.readObject())) - .append(nl); - } - } - catch (Exception ex) - { - buf.append(oid.getId()); - buf.append(" value = ").append("*****").append(nl); - } - } - else - { - buf.append(nl); - } - } - } - Set set = getRevokedCertificates(); - if (set != null) - { - Iterator it = set.iterator(); - while (it.hasNext()) - { - buf.append(it.next()); - buf.append(nl); - } - } - return buf.toString(); - } - - /** - * Checks whether the given certificate is on this CRL. - * - * @param cert the certificate to check for. - * @return true if the given certificate is on this CRL, - * false otherwise. - */ - public boolean isRevoked(Certificate cert) - { - if (!cert.getType().equals("X.509")) - { - throw new RuntimeException("X.509 CRL used with non X.509 Cert"); - } - - Enumeration certs = c.getRevokedCertificateEnumeration(); - - X500Name caName = c.getIssuer(); - - if (certs.hasMoreElements()) - { - BigInteger serial = ((X509Certificate)cert).getSerialNumber(); - - while (certs.hasMoreElements()) - { - TBSCertList.CRLEntry entry = TBSCertList.CRLEntry.getInstance(certs.nextElement()); - - if (isIndirect && entry.hasExtensions()) - { - Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer); - - if (currentCaName != null) - { - caName = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); - } - } - - if (entry.getUserCertificate().getValue().equals(serial)) - { - X500Name issuer; - - if (cert instanceof X509Certificate) - { - issuer = X500Name.getInstance(((X509Certificate)cert).getIssuerX500Principal().getEncoded()); - } - else - { - try - { - issuer = org.bouncycastle.asn1.x509.Certificate.getInstance(cert.getEncoded()).getIssuer(); - } - catch (CertificateEncodingException e) - { - throw new RuntimeException("Cannot process certificate"); - } - } - - if (!caName.equals(issuer)) - { - return false; - } - - return true; - } - } - } - - return false; - } - - public boolean equals(Object other) - { - if (this == other) - { - return true; - } - - if (!(other instanceof X509CRL)) - { - return false; - } - - if (other instanceof X509CRLObject) - { - X509CRLObject crlObject = (X509CRLObject)other; - - if (isHashCodeSet) - { - boolean otherIsHashCodeSet = crlObject.isHashCodeSet; - if (otherIsHashCodeSet) - { - if (crlObject.hashCodeValue != hashCodeValue) - { - return false; - } - } - } - - return this.c.equals(crlObject.c); - } - - return super.equals(other); - } - - public int hashCode() - { - if (!isHashCodeSet) - { - isHashCodeSet = true; - hashCodeValue = super.hashCode(); - } - - return hashCodeValue; - } -} - diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CertificateObject.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CertificateObject.java deleted file mode 100644 index 44220622..00000000 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509CertificateObject.java +++ /dev/null @@ -1,903 +0,0 @@ -package org.bouncycastle.jcajce.provider.asymmetric.x509; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Principal; -import java.security.Provider; -import java.security.PublicKey; -import java.security.Security; -import java.security.Signature; -import java.security.SignatureException; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.security.auth.x500.X500Principal; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1OutputStream; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.ASN1String; -import org.bouncycastle.asn1.DERBitString; -import org.bouncycastle.asn1.DERIA5String; -import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.misc.MiscObjectIdentifiers; -import org.bouncycastle.asn1.misc.NetscapeCertType; -import org.bouncycastle.asn1.misc.NetscapeRevocationURL; -import org.bouncycastle.asn1.misc.VerisignCzagExtension; -import org.bouncycastle.asn1.util.ASN1Dump; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x500.style.RFC4519Style; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.BasicConstraints; -import org.bouncycastle.asn1.x509.Extension; -import org.bouncycastle.asn1.x509.Extensions; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.asn1.x509.KeyUsage; -import org.bouncycastle.jcajce.provider.asymmetric.util.PKCS12BagAttributeCarrierImpl; -import org.bouncycastle.jce.X509Principal; -import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.jce.provider.RFC3280CertPathUtilities; -import org.bouncycastle.util.Arrays; -import org.bouncycastle.util.Integers; -import org.bouncycastle.util.encoders.Hex; - -class X509CertificateObject - extends X509Certificate - implements PKCS12BagAttributeCarrier -{ - private org.bouncycastle.asn1.x509.Certificate c; - private BasicConstraints basicConstraints; - private boolean[] keyUsage; - private boolean hashValueSet; - private int hashValue; - - private PKCS12BagAttributeCarrier attrCarrier = new PKCS12BagAttributeCarrierImpl(); - - public X509CertificateObject( - org.bouncycastle.asn1.x509.Certificate c) - throws CertificateParsingException - { - this.c = c; - - try - { - byte[] bytes = this.getExtensionBytes("2.5.29.19"); - - if (bytes != null) - { - basicConstraints = BasicConstraints.getInstance(ASN1Primitive.fromByteArray(bytes)); - } - } - catch (Exception e) - { - throw new CertificateParsingException("cannot construct BasicConstraints: " + e); - } - - try - { - byte[] bytes = this.getExtensionBytes("2.5.29.15"); - if (bytes != null) - { - DERBitString bits = DERBitString.getInstance(ASN1Primitive.fromByteArray(bytes)); - - bytes = bits.getBytes(); - int length = (bytes.length * 8) - bits.getPadBits(); - - keyUsage = new boolean[(length < 9) ? 9 : length]; - - for (int i = 0; i != length; i++) - { - keyUsage[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0; - } - } - else - { - keyUsage = null; - } - } - catch (Exception e) - { - throw new CertificateParsingException("cannot construct KeyUsage: " + e); - } - } - - public void checkValidity() - throws CertificateExpiredException, CertificateNotYetValidException - { - this.checkValidity(new Date()); - } - - public void checkValidity( - Date date) - throws CertificateExpiredException, CertificateNotYetValidException - { - if (date.getTime() > this.getNotAfter().getTime()) // for other VM compatibility - { - throw new CertificateExpiredException("certificate expired on " + c.getEndDate().getTime()); - } - - if (date.getTime() < this.getNotBefore().getTime()) - { - throw new CertificateNotYetValidException("certificate not valid till " + c.getStartDate().getTime()); - } - } - - public int getVersion() - { - return c.getVersionNumber(); - } - - public BigInteger getSerialNumber() - { - return c.getSerialNumber().getValue(); - } - - public Principal getIssuerDN() - { - try - { - return new X509Principal(X500Name.getInstance(c.getIssuer().getEncoded())); - } - catch (IOException e) - { - return null; - } - } - - public X500Principal getIssuerX500Principal() - { - try - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ASN1OutputStream aOut = new ASN1OutputStream(bOut); - - aOut.writeObject(c.getIssuer()); - - return new X500Principal(bOut.toByteArray()); - } - catch (IOException e) - { - throw new IllegalStateException("can't encode issuer DN"); - } - } - - public Principal getSubjectDN() - { - return new X509Principal(X500Name.getInstance(c.getSubject().toASN1Primitive())); - } - - public X500Principal getSubjectX500Principal() - { - try - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ASN1OutputStream aOut = new ASN1OutputStream(bOut); - - aOut.writeObject(c.getSubject()); - - return new X500Principal(bOut.toByteArray()); - } - catch (IOException e) - { - throw new IllegalStateException("can't encode issuer DN"); - } - } - - public Date getNotBefore() - { - return c.getStartDate().getDate(); - } - - public Date getNotAfter() - { - return c.getEndDate().getDate(); - } - - public byte[] getTBSCertificate() - throws CertificateEncodingException - { - try - { - return c.getTBSCertificate().getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CertificateEncodingException(e.toString()); - } - } - - public byte[] getSignature() - { - return c.getSignature().getBytes(); - } - - /** - * return a more "meaningful" representation for the signature algorithm used in - * the certficate. - */ - public String getSigAlgName() - { - Provider prov = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME); - - if (prov != null) - { - String algName = prov.getProperty("Alg.Alias.Signature." + this.getSigAlgOID()); - - if (algName != null) - { - return algName; - } - } - - Provider[] provs = Security.getProviders(); - - // - // search every provider looking for a real algorithm - // - for (int i = 0; i != provs.length; i++) - { - String algName = provs[i].getProperty("Alg.Alias.Signature." + this.getSigAlgOID()); - if (algName != null) - { - return algName; - } - } - - return this.getSigAlgOID(); - } - - /** - * return the object identifier for the signature. - */ - public String getSigAlgOID() - { - return c.getSignatureAlgorithm().getAlgorithm().getId(); - } - - /** - * return the signature parameters, or null if there aren't any. - */ - public byte[] getSigAlgParams() - { - if (c.getSignatureAlgorithm().getParameters() != null) - { - try - { - return c.getSignatureAlgorithm().getParameters().toASN1Primitive().getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - return null; - } - } - else - { - return null; - } - } - - public boolean[] getIssuerUniqueID() - { - DERBitString id = c.getTBSCertificate().getIssuerUniqueId(); - - if (id != null) - { - byte[] bytes = id.getBytes(); - boolean[] boolId = new boolean[bytes.length * 8 - id.getPadBits()]; - - for (int i = 0; i != boolId.length; i++) - { - boolId[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0; - } - - return boolId; - } - - return null; - } - - public boolean[] getSubjectUniqueID() - { - DERBitString id = c.getTBSCertificate().getSubjectUniqueId(); - - if (id != null) - { - byte[] bytes = id.getBytes(); - boolean[] boolId = new boolean[bytes.length * 8 - id.getPadBits()]; - - for (int i = 0; i != boolId.length; i++) - { - boolId[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0; - } - - return boolId; - } - - return null; - } - - public boolean[] getKeyUsage() - { - return keyUsage; - } - - public List getExtendedKeyUsage() - throws CertificateParsingException - { - byte[] bytes = this.getExtensionBytes("2.5.29.37"); - - if (bytes != null) - { - try - { - ASN1InputStream dIn = new ASN1InputStream(bytes); - ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); - List list = new ArrayList(); - - for (int i = 0; i != seq.size(); i++) - { - list.add(((ASN1ObjectIdentifier)seq.getObjectAt(i)).getId()); - } - - return Collections.unmodifiableList(list); - } - catch (Exception e) - { - throw new CertificateParsingException("error processing extended key usage extension"); - } - } - - return null; - } - - public int getBasicConstraints() - { - if (basicConstraints != null) - { - if (basicConstraints.isCA()) - { - if (basicConstraints.getPathLenConstraint() == null) - { - return Integer.MAX_VALUE; - } - else - { - return basicConstraints.getPathLenConstraint().intValue(); - } - } - else - { - return -1; - } - } - - return -1; - } - - public Collection getSubjectAlternativeNames() - throws CertificateParsingException - { - return getAlternativeNames(getExtensionBytes(Extension.subjectAlternativeName.getId())); - } - - public Collection getIssuerAlternativeNames() - throws CertificateParsingException - { - return getAlternativeNames(getExtensionBytes(Extension.issuerAlternativeName.getId())); - } - - public Set getCriticalExtensionOIDs() - { - if (this.getVersion() == 3) - { - Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (ext.isCritical()) - { - set.add(oid.getId()); - } - } - - return set; - } - } - - return null; - } - - private byte[] getExtensionBytes(String oid) - { - Extensions exts = c.getTBSCertificate().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - if (ext != null) - { - return ext.getExtnValue().getOctets(); - } - } - - return null; - } - - public byte[] getExtensionValue(String oid) - { - Extensions exts = c.getTBSCertificate().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("error parsing " + e.toString()); - } - } - } - - return null; - } - - public Set getNonCriticalExtensionOIDs() - { - if (this.getVersion() == 3) - { - Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (!ext.isCritical()) - { - set.add(oid.getId()); - } - } - - return set; - } - } - - return null; - } - - public boolean hasUnsupportedCriticalExtension() - { - if (this.getVersion() == 3) - { - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - String oidId = oid.getId(); - - if (oidId.equals(RFC3280CertPathUtilities.KEY_USAGE) - || oidId.equals(RFC3280CertPathUtilities.CERTIFICATE_POLICIES) - || oidId.equals(RFC3280CertPathUtilities.POLICY_MAPPINGS) - || oidId.equals(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY) - || oidId.equals(RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS) - || oidId.equals(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT) - || oidId.equals(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR) - || oidId.equals(RFC3280CertPathUtilities.POLICY_CONSTRAINTS) - || oidId.equals(RFC3280CertPathUtilities.BASIC_CONSTRAINTS) - || oidId.equals(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME) - || oidId.equals(RFC3280CertPathUtilities.NAME_CONSTRAINTS)) - { - continue; - } - - Extension ext = extensions.getExtension(oid); - - if (ext.isCritical()) - { - return true; - } - } - } - } - - return false; - } - - public PublicKey getPublicKey() - { - try - { - return BouncyCastleProvider.getPublicKey(c.getSubjectPublicKeyInfo()); - } - catch (IOException e) - { - return null; // should never happen... - } - } - - public byte[] getEncoded() - throws CertificateEncodingException - { - try - { - return c.getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CertificateEncodingException(e.toString()); - } - } - - public boolean equals( - Object o) - { - if (o == this) - { - return true; - } - - if (!(o instanceof Certificate)) - { - return false; - } - - Certificate other = (Certificate)o; - - try - { - byte[] b1 = this.getEncoded(); - byte[] b2 = other.getEncoded(); - - return Arrays.areEqual(b1, b2); - } - catch (CertificateEncodingException e) - { - return false; - } - } - - public synchronized int hashCode() - { - if (!hashValueSet) - { - hashValue = calculateHashCode(); - hashValueSet = true; - } - - return hashValue; - } - - private int calculateHashCode() - { - try - { - int hashCode = 0; - byte[] certData = this.getEncoded(); - for (int i = 1; i < certData.length; i++) - { - hashCode += certData[i] * i; - } - return hashCode; - } - catch (CertificateEncodingException e) - { - return 0; - } - } - - public void setBagAttribute( - ASN1ObjectIdentifier oid, - ASN1Encodable attribute) - { - attrCarrier.setBagAttribute(oid, attribute); - } - - public ASN1Encodable getBagAttribute( - ASN1ObjectIdentifier oid) - { - return attrCarrier.getBagAttribute(oid); - } - - public Enumeration getBagAttributeKeys() - { - return attrCarrier.getBagAttributeKeys(); - } - - public String toString() - { - StringBuffer buf = new StringBuffer(); - String nl = System.getProperty("line.separator"); - - buf.append(" [0] Version: ").append(this.getVersion()).append(nl); - buf.append(" SerialNumber: ").append(this.getSerialNumber()).append(nl); - buf.append(" IssuerDN: ").append(this.getIssuerDN()).append(nl); - buf.append(" Start Date: ").append(this.getNotBefore()).append(nl); - buf.append(" Final Date: ").append(this.getNotAfter()).append(nl); - buf.append(" SubjectDN: ").append(this.getSubjectDN()).append(nl); - buf.append(" Public Key: ").append(this.getPublicKey()).append(nl); - buf.append(" Signature Algorithm: ").append(this.getSigAlgName()).append(nl); - - byte[] sig = this.getSignature(); - - buf.append(" Signature: ").append(new String(Hex.encode(sig, 0, 20))).append(nl); - for (int i = 20; i < sig.length; i += 20) - { - if (i < sig.length - 20) - { - buf.append(" ").append(new String(Hex.encode(sig, i, 20))).append(nl); - } - else - { - buf.append(" ").append(new String(Hex.encode(sig, i, sig.length - i))).append(nl); - } - } - - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - if (e.hasMoreElements()) - { - buf.append(" Extensions: \n"); - } - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (ext.getExtnValue() != null) - { - byte[] octs = ext.getExtnValue().getOctets(); - ASN1InputStream dIn = new ASN1InputStream(octs); - buf.append(" critical(").append(ext.isCritical()).append(") "); - try - { - if (oid.equals(Extension.basicConstraints)) - { - buf.append(BasicConstraints.getInstance(dIn.readObject())).append(nl); - } - else if (oid.equals(Extension.keyUsage)) - { - buf.append(KeyUsage.getInstance(dIn.readObject())).append(nl); - } - else if (oid.equals(MiscObjectIdentifiers.netscapeCertType)) - { - buf.append(new NetscapeCertType((DERBitString)dIn.readObject())).append(nl); - } - else if (oid.equals(MiscObjectIdentifiers.netscapeRevocationURL)) - { - buf.append(new NetscapeRevocationURL((DERIA5String)dIn.readObject())).append(nl); - } - else if (oid.equals(MiscObjectIdentifiers.verisignCzagExtension)) - { - buf.append(new VerisignCzagExtension((DERIA5String)dIn.readObject())).append(nl); - } - else - { - buf.append(oid.getId()); - buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl); - //buf.append(" value = ").append("*****").append(nl); - } - } - catch (Exception ex) - { - buf.append(oid.getId()); - // buf.append(" value = ").append(new String(Hex.encode(ext.getExtnValue().getOctets()))).append(nl); - buf.append(" value = ").append("*****").append(nl); - } - } - else - { - buf.append(nl); - } - } - } - - return buf.toString(); - } - - public final void verify( - PublicKey key) - throws CertificateException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - Signature signature; - String sigName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm()); - - try - { - signature = Signature.getInstance(sigName, BouncyCastleProvider.PROVIDER_NAME); - } - catch (Exception e) - { - signature = Signature.getInstance(sigName); - } - - checkSignature(key, signature); - } - - public final void verify( - PublicKey key, - String sigProvider) - throws CertificateException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - String sigName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm()); - Signature signature = Signature.getInstance(sigName, sigProvider); - - checkSignature(key, signature); - } - - private void checkSignature( - PublicKey key, - Signature signature) - throws CertificateException, NoSuchAlgorithmException, - SignatureException, InvalidKeyException - { - if (!isAlgIdEqual(c.getSignatureAlgorithm(), c.getTBSCertificate().getSignature())) - { - throw new CertificateException("signature algorithm in TBS cert not same as outer cert"); - } - - ASN1Encodable params = c.getSignatureAlgorithm().getParameters(); - - // TODO This should go after the initVerify? - X509SignatureUtil.setSignatureParameters(signature, params); - - signature.initVerify(key); - - signature.update(this.getTBSCertificate()); - - if (!signature.verify(this.getSignature())) - { - throw new SignatureException("certificate does not verify with supplied key"); - } - } - - private boolean isAlgIdEqual(AlgorithmIdentifier id1, AlgorithmIdentifier id2) - { - if (!id1.getAlgorithm().equals(id2.getAlgorithm())) - { - return false; - } - - if (id1.getParameters() == null) - { - if (id2.getParameters() != null && !id2.getParameters().equals(DERNull.INSTANCE)) - { - return false; - } - - return true; - } - - if (id2.getParameters() == null) - { - if (id1.getParameters() != null && !id1.getParameters().equals(DERNull.INSTANCE)) - { - return false; - } - - return true; - } - - return id1.getParameters().equals(id2.getParameters()); - } - - private static Collection getAlternativeNames(byte[] extVal) - throws CertificateParsingException - { - if (extVal == null) - { - return null; - } - try - { - Collection temp = new ArrayList(); - Enumeration it = ASN1Sequence.getInstance(extVal).getObjects(); - while (it.hasMoreElements()) - { - GeneralName genName = GeneralName.getInstance(it.nextElement()); - List list = new ArrayList(); - list.add(Integers.valueOf(genName.getTagNo())); - switch (genName.getTagNo()) - { - case GeneralName.ediPartyName: - case GeneralName.x400Address: - case GeneralName.otherName: - list.add(genName.getEncoded()); - break; - case GeneralName.directoryName: - list.add(X500Name.getInstance(RFC4519Style.INSTANCE, genName.getName()).toString()); - break; - case GeneralName.dNSName: - case GeneralName.rfc822Name: - case GeneralName.uniformResourceIdentifier: - list.add(((ASN1String)genName.getName()).getString()); - break; - case GeneralName.registeredID: - list.add(ASN1ObjectIdentifier.getInstance(genName.getName()).getId()); - break; - case GeneralName.iPAddress: - byte[] addrBytes = DEROctetString.getInstance(genName.getName()).getOctets(); - final String addr; - try - { - addr = InetAddress.getByAddress(addrBytes).getHostAddress(); - } - catch (UnknownHostException e) - { - continue; - } - list.add(addr); - break; - default: - throw new IOException("Bad tag number: " + genName.getTagNo()); - } - - temp.add(Collections.unmodifiableList(list)); - } - if (temp.size() == 0) - { - return null; - } - return Collections.unmodifiableCollection(temp); - } - catch (Exception e) - { - throw new CertificateParsingException(e.getMessage()); - } - } -} diff --git a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509SignatureUtil.java b/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509SignatureUtil.java deleted file mode 100644 index 06d30759..00000000 --- a/prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/x509/X509SignatureUtil.java +++ /dev/null @@ -1,138 +0,0 @@ -package org.bouncycastle.jcajce.provider.asymmetric.x509; - -import java.io.IOException; -import java.security.AlgorithmParameters; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.Signature; -import java.security.SignatureException; -import java.security.spec.PSSParameterSpec; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1Null; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; -import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.RSASSAPSSparams; -import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; - -class X509SignatureUtil -{ - private static final ASN1Null derNull = DERNull.INSTANCE; - - static void setSignatureParameters( - Signature signature, - ASN1Encodable params) - throws NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - if (params != null && !derNull.equals(params)) - { - AlgorithmParameters sigParams = AlgorithmParameters.getInstance(signature.getAlgorithm(), signature.getProvider()); - - try - { - sigParams.init(params.toASN1Primitive().getEncoded()); - } - catch (IOException e) - { - throw new SignatureException("IOException decoding parameters: " + e.getMessage()); - } - - if (signature.getAlgorithm().endsWith("MGF1")) - { - try - { - signature.setParameter(sigParams.getParameterSpec(PSSParameterSpec.class)); - } - catch (GeneralSecurityException e) - { - throw new SignatureException("Exception extracting parameters: " + e.getMessage()); - } - } - } - } - - static String getSignatureName( - AlgorithmIdentifier sigAlgId) - { - ASN1Encodable params = sigAlgId.getParameters(); - - if (params != null && !derNull.equals(params)) - { - if (sigAlgId.getAlgorithm().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) - { - RSASSAPSSparams rsaParams = RSASSAPSSparams.getInstance(params); - - return getDigestAlgName(rsaParams.getHashAlgorithm().getAlgorithm()) + "withRSAandMGF1"; - } - if (sigAlgId.getAlgorithm().equals(X9ObjectIdentifiers.ecdsa_with_SHA2)) - { - ASN1Sequence ecDsaParams = ASN1Sequence.getInstance(params); - - return getDigestAlgName((ASN1ObjectIdentifier)ecDsaParams.getObjectAt(0)) + "withECDSA"; - } - } - - return sigAlgId.getAlgorithm().getId(); - } - - /** - * Return the digest algorithm using one of the standard JCA string - * representations rather the the algorithm identifier (if possible). - */ - private static String getDigestAlgName( - ASN1ObjectIdentifier digestAlgOID) - { - if (PKCSObjectIdentifiers.md5.equals(digestAlgOID)) - { - return "MD5"; - } - else if (OIWObjectIdentifiers.idSHA1.equals(digestAlgOID)) - { - return "SHA1"; - } - else if (NISTObjectIdentifiers.id_sha224.equals(digestAlgOID)) - { - return "SHA224"; - } - else if (NISTObjectIdentifiers.id_sha256.equals(digestAlgOID)) - { - return "SHA256"; - } - else if (NISTObjectIdentifiers.id_sha384.equals(digestAlgOID)) - { - return "SHA384"; - } - else if (NISTObjectIdentifiers.id_sha512.equals(digestAlgOID)) - { - return "SHA512"; - } - else if (TeleTrusTObjectIdentifiers.ripemd128.equals(digestAlgOID)) - { - return "RIPEMD128"; - } - else if (TeleTrusTObjectIdentifiers.ripemd160.equals(digestAlgOID)) - { - return "RIPEMD160"; - } - else if (TeleTrusTObjectIdentifiers.ripemd256.equals(digestAlgOID)) - { - return "RIPEMD256"; - } - else if (CryptoProObjectIdentifiers.gostR3411.equals(digestAlgOID)) - { - return "GOST3411"; - } - else - { - return digestAlgOID.getId(); - } - } -} |