Java Code Examples for org.bouncycastle.asn1.x509.X509CertificateStructure

The following are top voted examples for showing how to use org.bouncycastle.asn1.x509.X509CertificateStructure. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Direct-File-Downloader   File: JDKX509CertificateFactory.java   View source code 6 votes vote down vote up
/**
   * read in a BER encoded PKCS7 certificate.
   */
  private Certificate readPKCS7Certificate(
      InputStream  in)
      throws IOException
  {
      BERInputStream  dIn = new BERInputStream(in);
      ASN1Sequence seq = (ASN1Sequence)dIn.readObject();

if (seq.size() > 1
		&& seq.getObjectAt(0) instanceof DERObjectIdentifier)
{
       if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData))
       {
		sData = new SignedData(ASN1Sequence.getInstance(
						(ASN1TaggedObject)seq.getObjectAt(1), true));
	
		return new X509CertificateObject(
					X509CertificateStructure.getInstance(
							sData.getCertificates().getObjectAt(sDataObjectCount++)));
       }
}

return new X509CertificateObject(
			 X509CertificateStructure.getInstance(seq));
  }
 
Example 2
Project: In-the-Box-Fork   File: PKIXCertPathValidatorSpiTest.java   View source code 6 votes vote down vote up
public void testTrustAndRemoteCertificatesWithDifferentEncodings()
        throws IOException, CertificateException, KeyStoreException,
        InvalidAlgorithmParameterException, CertPathValidatorException {

    X509CertPathImpl certPath = new X509CertPathImpl(Arrays.asList(
            new X509CertImpl(serviceSprintComCertChain[0]),
            new X509CertImpl(serviceSprintComCertChain[1]),
            new X509CertImpl(serviceSprintComCertChain[2])));

    Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
    trustAnchors.add(new TrustAnchor(new X509CertificateObject(
            new X509CertificateStructure(
                    (ASN1Sequence) new ASN1InputStream(trustedCert).readObject())), null));

    IndexedPKIXParameters indexedPKIXParameters = new IndexedPKIXParameters(trustAnchors);
    indexedPKIXParameters.setRevocationEnabled(false);

    new PKIXCertPathValidatorSpi().engineValidate(certPath, indexedPKIXParameters);
    // completing normally indicates that the certificate was valid
}
 
Example 3
Project: AcademicTorrents-Downloader   File: JDKX509CertificateFactory.java   View source code 6 votes vote down vote up
private Certificate readDERCertificate(
    InputStream in)
    throws IOException
{
    DERInputStream  dIn = new DERInputStream(in);
    ASN1Sequence    seq = (ASN1Sequence)dIn.readObject();

    if (seq.size() > 1
            && seq.getObjectAt(0) instanceof DERObjectIdentifier)
    {
        if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData))
        {
            sData = new SignedData(ASN1Sequence.getInstance(
                            (ASN1TaggedObject)seq.getObjectAt(1), true));

            return new X509CertificateObject(
                        X509CertificateStructure.getInstance(
                                sData.getCertificates().getObjectAt(sDataObjectCount++)));
        }
    }

    return new X509CertificateObject(
                        X509CertificateStructure.getInstance(seq));
}
 
Example 4
Project: AcademicTorrents-Downloader   File: JDKX509CertificateFactory.java   View source code 6 votes vote down vote up
/**
   * read in a BER encoded PKCS7 certificate.
   */
  private Certificate readPKCS7Certificate(
      InputStream  in)
      throws IOException
  {
      BERInputStream  dIn = new BERInputStream(in);
      ASN1Sequence seq = (ASN1Sequence)dIn.readObject();

if (seq.size() > 1
		&& seq.getObjectAt(0) instanceof DERObjectIdentifier)
{
       if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData))
       {
		sData = new SignedData(ASN1Sequence.getInstance(
						(ASN1TaggedObject)seq.getObjectAt(1), true));
	
		return new X509CertificateObject(
					X509CertificateStructure.getInstance(
							sData.getCertificates().getObjectAt(sDataObjectCount++)));
       }
}

return new X509CertificateObject(
			 X509CertificateStructure.getInstance(seq));
  }
 
Example 5
Project: jradius   File: TlsRSAKeyExchange.java   View source code 6 votes vote down vote up
private void validateKeyUsage(X509CertificateStructure c, int keyUsageBits) throws IOException
{
    X509Extensions exts = c.getTBSCertificate().getExtensions();
    if (exts != null)
    {
        X509Extension ext = exts.getExtension(X509Extensions.KeyUsage);
        if (ext != null)
        {
            KeyUsage ku = KeyUsage.getInstance(ext);
            int bits = ku.getBytes()[0] & 0xff;
            if ((bits & keyUsageBits) != keyUsageBits)
            {
                handler.failWithError(TlsProtocolHandler.AL_fatal,
                    TlsProtocolHandler.AP_certificate_unknown);
            }
        }
    }
}
 
Example 6
Project: jradius   File: TlsDHKeyExchange.java   View source code 6 votes vote down vote up
private void validateKeyUsage(X509CertificateStructure c, int keyUsageBits) throws IOException
{
    X509Extensions exts = c.getTBSCertificate().getExtensions();
    if (exts != null)
    {
        X509Extension ext = exts.getExtension(X509Extensions.KeyUsage);
        if (ext != null)
        {
            KeyUsage ku = KeyUsage.getInstance(ext);
            int bits = ku.getBytes()[0] & 0xff;
            if ((bits & keyUsageBits) != keyUsageBits)
            {
                handler.failWithError(TlsProtocolHandler.AL_fatal,
                    TlsProtocolHandler.AP_certificate_unknown);
            }
        }
    }
}
 
Example 7
Project: jradius   File: TlsSRPKeyExchange.java   View source code 6 votes vote down vote up
private void validateKeyUsage(X509CertificateStructure c, int keyUsageBits) throws IOException
{
    X509Extensions exts = c.getTBSCertificate().getExtensions();
    if (exts != null)
    {
        X509Extension ext = exts.getExtension(X509Extensions.KeyUsage);
        if (ext != null)
        {
            KeyUsage ku = KeyUsage.getInstance(ext);
            int bits = ku.getBytes()[0] & 0xff;
            if ((bits & keyUsageBits) != keyUsageBits)
            {
                handler.failWithError(TlsProtocolHandler.AL_fatal,
                    TlsProtocolHandler.AP_certificate_unknown);
            }
        }
    }
}
 
Example 8
Project: Direct-File-Downloader   File: JDKX509CertificateFactory.java   View source code 5 votes vote down vote up
private Certificate readDERCertificate(
    InputStream in)
    throws IOException
{
    DERInputStream  dIn = new DERInputStream(in);
    ASN1Sequence    seq = (ASN1Sequence)dIn.readObject();

    if (seq.size() > 1
            && seq.getObjectAt(0) instanceof DERObjectIdentifier)
    {
        if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData))
        {
            sData = new SignedData(ASN1Sequence.getInstance(
                            (ASN1TaggedObject)seq.getObjectAt(1), true));

            return new X509CertificateObject(
                        X509CertificateStructure.getInstance(
                                sData.getCertificates().getObjectAt(sDataObjectCount++)));
        }
    }

    return new X509CertificateObject(
                        X509CertificateStructure.getInstance(seq));
}
 
Example 9
Project: helium   File: SignaturaPluginTest.java   View source code 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "resource" })
private DadesCertificat getDadesCertificat(X509Certificate cert) throws Exception {
	ASN1InputStream asn1is = new ASN1InputStream(cert.getEncoded());
	org.bouncycastle.asn1.DERObject obj = asn1is.readObject();
	/*byte[] value = cert.getExtensionValue(X509Extensions.BasicConstraints.toString());
	BasicConstraints basicConstraints = new BasicConstraints(cert.getBasicConstraints());
	if (basicConstraints.isCA())
		return null;*/
	DadesCertificat resposta = new DadesCertificat();
	X509CertificateStructure certificate = new X509CertificateStructure((ASN1Sequence)obj);
	X509Name name = certificate.getSubject();
	Vector oids = name.getOIDs();
	Vector values = name.getValues();
	for (int i = 0; i < oids.size(); i++) {
		if (oids.get(i).equals(X509Name.CN)) {
			processName(values.get(i).toString(), resposta);
		} else if (oids.get(i).equals(X509Name.SURNAME)) {
			resposta.setApellidosResponsable(values.get(i).toString());
		} else if (oids.get(i).equals(X509Name.GIVENNAME)) {
			resposta.setNombreResponsable(values.get(i).toString());
		} else if (oids.get(i).equals(X509Name.SN)) {
			resposta.setNifCif(values.get(i).toString());
			resposta.setNifResponsable(values.get(i).toString());
		} else if (oids.get(i).equals(OID_NIF_RESPONSABLE)) {
			resposta.setNifResponsable(values.get(i).toString());
		} else if (oids.get(i).equals(X509Name.EmailAddress)) {
			resposta.setEmail(values.get(i).toString());
		} else if (oids.get(i).equals(X509Name.C)) {
			//resposta.setPais(values.get(i).toString());
		} else if (oids.get(i).equals(X509Name.O)) {
			resposta.setRazonSocial(values.get(i).toString());
		} else if (oids.get(i).equals(X509Name.OU)) {
			//resposta.setDepartament(values.get(i).toString());
		} else if (oids.get(i).equals(X509Name.T)) {
			//resposta.setCarrec(values.get(i).toString());
	    }
	}
	return resposta;
}
 
Example 10
Project: sistra   File: DatosCertificado.java   View source code 5 votes vote down vote up
public DatosCertificado(X509Certificate cert) throws Exception{
      byte b[] = cert.getEncoded();
      ASN1InputStream asn1is = new ASN1InputStream(b);
      org.bouncycastle.asn1.DERObject obj = asn1is.readObject();
      X509CertificateStructure certificate = new X509CertificateStructure((ASN1Sequence)obj);
      X509Name name = certificate.getSubject();
      personaFisica = false;
      personaJuridica = false;
      Vector v = name.getOIDs();
      Vector value = name.getValues();
      for(int i = 0; i < v.size(); i++)
      {
          if(v.get(i).equals(X509Name.CN))
              processName(value.get(i).toString());
          if(v.get(i).equals(X509Name.SURNAME))
              surName = value.get(i).toString();
          if(v.get(i).equals(X509Name.GIVENNAME))
              givenName = value.get(i).toString();
          if(v.get(i).equals(X509Name.CN))
              processName(value.get(i).toString());
          if(v.get(i).equals(X509Name.SN))
          {
              nif = value.get(i).toString();
              if(!personaJuridica)
                  personaFisica = true;
          }
          if(v.get(i).equals(NIFOID))
          {
              nifResponsable = v.get(i).toString();
              personaFisica = false;
              personaJuridica = true;
          }
      }

}
 
Example 11
Project: sistra   File: DatosCertificado.java   View source code 5 votes vote down vote up
public DatosCertificado(X509Certificate cert) throws Exception{
      byte b[] = cert.getEncoded();
      ASN1InputStream asn1is = new ASN1InputStream(b);
      org.bouncycastle.asn1.DERObject obj = asn1is.readObject();
      X509CertificateStructure certificate = new X509CertificateStructure((ASN1Sequence)obj);
      X509Name name = certificate.getSubject();
      personaFisica = false;
      personaJuridica = false;
      Vector v = name.getOIDs();
      Vector value = name.getValues();
      for(int i = 0; i < v.size(); i++)
      {
          if(v.get(i).equals(X509Name.CN))
              processName(value.get(i).toString());
          if(v.get(i).equals(X509Name.SURNAME))
              surName = value.get(i).toString();
          if(v.get(i).equals(X509Name.GIVENNAME))
              givenName = value.get(i).toString();
          if(v.get(i).equals(X509Name.CN))
              processName(value.get(i).toString());
          if(v.get(i).equals(X509Name.SN))
          {
              nif = value.get(i).toString();
              if(!personaJuridica)
                  personaFisica = true;
          }
          if(v.get(i).equals(NIFOID))
          {
              nifResponsable = v.get(i).toString();
              personaFisica = false;
              personaJuridica = true;
          }
      }

}
 
Example 12
Project: gwt-crypto   File: IssuerAndSerialNumber.java   View source code 5 votes vote down vote up
/**
 * @deprecated use constructor taking Certificate
 */
public IssuerAndSerialNumber(
    X509CertificateStructure certificate)
{
    this.name = certificate.getIssuer();
    this.serialNumber = certificate.getSerialNumber();
}
 
Example 13
Project: Aki-SSL   File: IssuerAndSerialNumber.java   View source code 5 votes vote down vote up
/**
 * @deprecated use constructor taking Certificate
 */
public IssuerAndSerialNumber(
    X509CertificateStructure certificate)
{
    this.name = certificate.getIssuer();
    this.serialNumber = certificate.getSerialNumber();
}
 
Example 14
Project: TinyTravelTracker   File: IssuerAndSerialNumber.java   View source code 5 votes vote down vote up
/**
 * @deprecated use constructor taking Certificate
 */
public IssuerAndSerialNumber(
    X509CertificateStructure certificate)
{
    this.name = certificate.getIssuer();
    this.serialNumber = certificate.getSerialNumber();
}
 
Example 15
Project: CryptMeme   File: IssuerAndSerialNumber.java   View source code 5 votes vote down vote up
/**
 * @deprecated use constructor taking Certificate
 */
public IssuerAndSerialNumber(
    X509CertificateStructure certificate)
{
    this.name = certificate.getIssuer();
    this.serialNumber = certificate.getSerialNumber();
}
 
Example 16
Project: Mailster   File: CertificateUtilities.java   View source code 5 votes vote down vote up
public static X509Extensions getExtensions(X509Certificate cert) 
    throws Exception
{
    ByteArrayInputStream bis = new ByteArrayInputStream(cert.getEncoded());
    ASN1InputStream ais = new ASN1InputStream(bis);
    DERObject o = ais.readObject();
    X509CertificateStructure struct = X509CertificateStructure
            .getInstance(o);

    return struct.getTBSCertificate().getExtensions();
}
 
Example 17
Project: irma_future_id   File: IssuerAndSerialNumber.java   View source code 5 votes vote down vote up
/**
 * @deprecated use constructor taking Certificate
 */
public IssuerAndSerialNumber(
    X509CertificateStructure certificate)
{
    this.name = certificate.getIssuer();
    this.serialNumber = certificate.getSerialNumber();
}
 
Example 18
Project: bc-java   File: IssuerAndSerialNumber.java   View source code 5 votes vote down vote up
/**
 * @deprecated use constructor taking Certificate
 */
public IssuerAndSerialNumber(
    X509CertificateStructure certificate)
{
    this.name = certificate.getIssuer();
    this.serialNumber = certificate.getSerialNumber();
}
 
Example 19
Project: jradius   File: Certificate.java   View source code 5 votes vote down vote up
/**
 * Parse the ServerCertificate message.
 * 
 * @param is The stream where to parse from.
 * @return A Certificate object with the certs, the server has sended.
 * @throws IOException If something goes wrong during parsing.
 */
public static Certificate parse(InputStream is) throws IOException
{
    X509CertificateStructure[] certs;
    int left = TlsUtils.readUint24(is);
    Vector tmp = new Vector();
    while (left > 0)
    {
        int size = TlsUtils.readUint24(is);
        left -= 3 + size;
        byte[] buf = new byte[size];
        TlsUtils.readFully(buf, is);
        ByteArrayInputStream bis = new ByteArrayInputStream(buf);
        ASN1InputStream ais = new ASN1InputStream(bis);
        ASN1Primitive o = ais.readObject();
        tmp.addElement(X509CertificateStructure.getInstance(o));
        if (bis.available() > 0)
        {
            throw new IllegalArgumentException(
                "Sorry, there is garbage data left after the certificate");
        }
    }
    certs = new X509CertificateStructure[tmp.size()];
    for (int i = 0; i < tmp.size(); i++)
    {
        certs[i] = (X509CertificateStructure)tmp.elementAt(i);
    }
    return new Certificate(certs);
}
 
Example 20
Project: jradius   File: Certificate.java   View source code 5 votes vote down vote up
/**
 * @return An array which contains the certs, this chain contains.
 */
public X509CertificateStructure[] getCerts()
{
    X509CertificateStructure[] result = new X509CertificateStructure[certs.length];
    System.arraycopy(certs, 0, result, 0, certs.length);
    return result;
}
 
Example 21
Project: ipack   File: IssuerAndSerialNumber.java   View source code 4 votes vote down vote up
public IssuerAndSerialNumber(
    X509CertificateStructure certificate)
{
    this.name = certificate.getIssuer();
    this.serialNumber = certificate.getSerialNumber();
}
 
Example 22
Project: Direct-File-Downloader   File: JDKX509CertificateFactory.java   View source code 4 votes vote down vote up
/**
  * Generates a certificate object and initializes it with the data
  * read from the input stream inStream.
  */
 public Certificate engineGenerateCertificate(
     InputStream in) 
     throws CertificateException
 {
 	if (sData != null && sDataObjectCount != sData.getCertificates().size())
 	{
return new X509CertificateObject(
			X509CertificateStructure.getInstance(
					sData.getCertificates().getObjectAt(sDataObjectCount++)));
 	}
 	
     if (!in.markSupported())
     {
         in = new BufferedInputStream(in);
     }

     try
     {
         in.mark(10);
         int	tag = in.read();
         
         if (tag == -1)
         {
         	return null;
         }
         
         if (tag != 0x30)  // assume ascii PEM encoded.
         {
             in.reset();
             return readPEMCertificate(in);
         }
         else if (in.read() == 0x80)    // assume BER encoded.
         {
             in.reset();
             return readPKCS7Certificate(in);
         }
         else
         {
             in.reset();
             return readDERCertificate(in);
         }
     }
     catch (IOException e)
     {
         throw new CertificateException(e.toString());
     }
 }
 
Example 23
Project: AcademicTorrents-Downloader   File: X509CertificateObject.java   View source code 4 votes vote down vote up
public X509CertificateObject(
    X509CertificateStructure    c)
{
    this.c = c;
}
 
Example 24
Project: AcademicTorrents-Downloader   File: JDKX509CertificateFactory.java   View source code 4 votes vote down vote up
/**
  * Generates a certificate object and initializes it with the data
  * read from the input stream inStream.
  */
 public Certificate engineGenerateCertificate(
     InputStream in) 
     throws CertificateException
 {
 	if (sData != null && sDataObjectCount != sData.getCertificates().size())
 	{
return new X509CertificateObject(
			X509CertificateStructure.getInstance(
					sData.getCertificates().getObjectAt(sDataObjectCount++)));
 	}
 	
     if (!in.markSupported())
     {
         in = new BufferedInputStream(in);
     }

     try
     {
         in.mark(10);
         int	tag = in.read();
         
         if (tag == -1)
         {
         	return null;
         }
         
         if (tag != 0x30)  // assume ascii PEM encoded.
         {
             in.reset();
             return readPEMCertificate(in);
         }
         else if (in.read() == 0x80)    // assume BER encoded.
         {
             in.reset();
             return readPKCS7Certificate(in);
         }
         else
         {
             in.reset();
             return readDERCertificate(in);
         }
     }
     catch (IOException e)
     {
         throw new CertificateException(e.toString());
     }
 }
 
Example 25
Project: CryptMeme   File: CertTest.java   View source code 4 votes vote down vote up
private void testNullDerNullCert()
    throws Exception
{
    KeyPair pair = generateLongFixedKeys();
    PublicKey pubKey = pair.getPublic();
    PrivateKey privKey = pair.getPrivate();

    X509V3CertificateGenerator  certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(1));
    certGen.setIssuerDN(new X509Principal("CN=Test"));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(new X509Principal("CN=Test"));
    certGen.setPublicKey(pubKey);
    certGen.setSignatureAlgorithm("MD5WithRSAEncryption");
    X509Certificate cert = certGen.generate(privKey, "BC");

    X509CertificateStructure struct = X509CertificateStructure.getInstance(ASN1Primitive.fromByteArray(cert.getEncoded()));

    ASN1Encodable tbsCertificate = struct.getTBSCertificate();
    AlgorithmIdentifier sig = struct.getSignatureAlgorithm();

    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCertificate);
    v.add(new AlgorithmIdentifier(sig.getObjectId()));
    v.add(struct.getSignature());

    // verify
    ByteArrayInputStream    bIn;
    String                  dump = "";

    try
    {
        bIn = new ByteArrayInputStream(new DERSequence(v).getEncoded());

        CertificateFactory  fact = CertificateFactory.getInstance("X.509", "BC");

        cert = (X509Certificate)fact.generateCertificate(bIn);

        cert.verify(cert.getPublicKey());
    }
    catch (Exception e)
    {
        fail(dump + System.getProperty("line.separator") + getName() + ": testNullDerNull failed - exception " + e.toString(), e);
    }
}
 
Example 26
Project: irma_future_id   File: CertTest.java   View source code 4 votes vote down vote up
private void testNullDerNullCert()
    throws Exception
{
    KeyPair pair = generateLongFixedKeys();
    PublicKey pubKey = pair.getPublic();
    PrivateKey privKey = pair.getPrivate();

    ContentSigner sigGen = new JcaContentSignerBuilder("MD5WithRSAEncryption").setProvider(BC).build(privKey);
    JcaX509v3CertificateBuilder  certGen = new JcaX509v3CertificateBuilder(new X500Name("CN=Test"),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),new X500Name("CN=Test"),pubKey);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certGen.build(sigGen));

    X509CertificateStructure struct = X509CertificateStructure.getInstance(ASN1Primitive.fromByteArray(cert.getEncoded()));

    ASN1Encodable tbsCertificate = struct.getTBSCertificate();
    AlgorithmIdentifier sig = struct.getSignatureAlgorithm();

    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCertificate);
    v.add(new AlgorithmIdentifier(sig.getAlgorithm()));
    v.add(struct.getSignature());

    // verify
    ByteArrayInputStream    bIn;
    String                  dump = "";

    try
    {
        bIn = new ByteArrayInputStream(new DERSequence(v).getEncoded());

        CertificateFactory  fact = CertificateFactory.getInstance("X.509", BC);

        cert = (X509Certificate)fact.generateCertificate(bIn);

        cert.verify(cert.getPublicKey());
    }
    catch (Exception e)
    {
        fail(dump + System.getProperty("line.separator") + getName() + ": testNullDerNull failed - exception " + e.toString(), e);
    }
}
 
Example 27
Project: irma_future_id   File: CertTest.java   View source code 4 votes vote down vote up
private void testNullDerNullCert()
    throws Exception
{
    KeyPair pair = generateLongFixedKeys();
    PublicKey pubKey = pair.getPublic();
    PrivateKey privKey = pair.getPrivate();

    ContentSigner sigGen = new JcaContentSignerBuilder("MD5WithRSAEncryption").setProvider(BC).build(privKey);
    JcaX509v3CertificateBuilder  certGen = new JcaX509v3CertificateBuilder(new X500Name("CN=Test"),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),new X500Name("CN=Test"),pubKey);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certGen.build(sigGen));

    X509CertificateStructure struct = X509CertificateStructure.getInstance(ASN1Primitive.fromByteArray(cert.getEncoded()));

    ASN1Encodable tbsCertificate = struct.getTBSCertificate();
    AlgorithmIdentifier sig = struct.getSignatureAlgorithm();

    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCertificate);
    v.add(new AlgorithmIdentifier(sig.getAlgorithm()));
    v.add(struct.getSignature());

    // verify
    ByteArrayInputStream    bIn;
    String                  dump = "";

    try
    {
        bIn = new ByteArrayInputStream(new DERSequence(v).getEncoded());

        CertificateFactory  fact = CertificateFactory.getInstance("X.509", BC);

        cert = (X509Certificate)fact.generateCertificate(bIn);

        cert.verify(cert.getPublicKey());
    }
    catch (Exception e)
    {
        fail(dump + System.getProperty("line.separator") + getName() + ": testNullDerNull failed - exception " + e.toString(), e);
    }
}
 
Example 28
Project: irma_future_id   File: CertTest.java   View source code 4 votes vote down vote up
private void testNullDerNullCert()
    throws Exception
{
    KeyPair pair = generateLongFixedKeys();
    PublicKey pubKey = pair.getPublic();
    PrivateKey privKey = pair.getPrivate();

    ContentSigner sigGen = new JcaContentSignerBuilder("MD5WithRSAEncryption").setProvider(BC).build(privKey);
    JcaX509v3CertificateBuilder  certGen = new JcaX509v3CertificateBuilder(new X500Name("CN=Test"),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),new X500Name("CN=Test"),pubKey);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certGen.build(sigGen));

    X509CertificateStructure struct = X509CertificateStructure.getInstance(ASN1Primitive.fromByteArray(cert.getEncoded()));

    ASN1Encodable tbsCertificate = struct.getTBSCertificate();
    AlgorithmIdentifier sig = struct.getSignatureAlgorithm();

    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCertificate);
    v.add(new AlgorithmIdentifier(sig.getAlgorithm()));
    v.add(struct.getSignature());

    // verify
    ByteArrayInputStream    bIn;
    String                  dump = "";

    try
    {
        bIn = new ByteArrayInputStream(new DERSequence(v).getEncoded());

        CertificateFactory  fact = CertificateFactory.getInstance("X.509", BC);

        cert = (X509Certificate)fact.generateCertificate(bIn);

        cert.verify(cert.getPublicKey());
    }
    catch (Exception e)
    {
        fail(dump + System.getProperty("line.separator") + getName() + ": testNullDerNull failed - exception " + e.toString(), e);
    }
}
 
Example 29
Project: irma_future_id   File: CertTest.java   View source code 4 votes vote down vote up
private void testNullDerNullCert()
    throws Exception
{
    KeyPair pair = generateLongFixedKeys();
    PublicKey pubKey = pair.getPublic();
    PrivateKey privKey = pair.getPrivate();

    ContentSigner sigGen = new JcaContentSignerBuilder("MD5WithRSAEncryption").setProvider(BC).build(privKey);
    JcaX509v3CertificateBuilder  certGen = new JcaX509v3CertificateBuilder(new X500Name("CN=Test"),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),new X500Name("CN=Test"),pubKey);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certGen.build(sigGen));

    X509CertificateStructure struct = X509CertificateStructure.getInstance(ASN1Primitive.fromByteArray(cert.getEncoded()));

    ASN1Encodable tbsCertificate = struct.getTBSCertificate();
    AlgorithmIdentifier sig = struct.getSignatureAlgorithm();

    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCertificate);
    v.add(new AlgorithmIdentifier(sig.getAlgorithm()));
    v.add(struct.getSignature());

    // verify
    ByteArrayInputStream    bIn;
    String                  dump = "";

    try
    {
        bIn = new ByteArrayInputStream(new DERSequence(v).getEncoded());

        CertificateFactory  fact = CertificateFactory.getInstance("X.509", BC);

        cert = (X509Certificate)fact.generateCertificate(bIn);

        cert.verify(cert.getPublicKey());
    }
    catch (Exception e)
    {
        fail(dump + System.getProperty("line.separator") + getName() + ": testNullDerNull failed - exception " + e.toString(), e);
    }
}
 
Example 30
Project: irma_future_id   File: CertTest.java   View source code 4 votes vote down vote up
private void testNullDerNullCert()
    throws Exception
{
    KeyPair pair = generateLongFixedKeys();
    PublicKey pubKey = pair.getPublic();
    PrivateKey privKey = pair.getPrivate();

    X509V3CertificateGenerator  certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(1));
    certGen.setIssuerDN(new X509Principal("CN=Test"));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(new X509Principal("CN=Test"));
    certGen.setPublicKey(pubKey);
    certGen.setSignatureAlgorithm("MD5WithRSAEncryption");
    X509Certificate cert = certGen.generate(privKey, "BC");

    X509CertificateStructure struct = X509CertificateStructure.getInstance(ASN1Primitive.fromByteArray(cert.getEncoded()));

    ASN1Encodable tbsCertificate = struct.getTBSCertificate();
    AlgorithmIdentifier sig = struct.getSignatureAlgorithm();

    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCertificate);
    v.add(new AlgorithmIdentifier(sig.getObjectId()));
    v.add(struct.getSignature());

    // verify
    ByteArrayInputStream    bIn;
    String                  dump = "";

    try
    {
        bIn = new ByteArrayInputStream(new DERSequence(v).getEncoded());

        CertificateFactory  fact = CertificateFactory.getInstance("X.509", "BC");

        cert = (X509Certificate)fact.generateCertificate(bIn);

        cert.verify(cert.getPublicKey());
    }
    catch (Exception e)
    {
        fail(dump + System.getProperty("line.separator") + getName() + ": testNullDerNull failed - exception " + e.toString(), e);
    }
}
 
Example 31
Project: bc-java   File: CertTest.java   View source code 4 votes vote down vote up
private void testNullDerNullCert()
    throws Exception
{
    KeyPair pair = generateLongFixedKeys();
    PublicKey pubKey = pair.getPublic();
    PrivateKey privKey = pair.getPrivate();

    ContentSigner sigGen = new JcaContentSignerBuilder("MD5WithRSAEncryption").setProvider(BC).build(privKey);
    JcaX509v3CertificateBuilder  certGen = new JcaX509v3CertificateBuilder(new X500Name("CN=Test"),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),new X500Name("CN=Test"),pubKey);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certGen.build(sigGen));

    X509CertificateStructure struct = X509CertificateStructure.getInstance(ASN1Primitive.fromByteArray(cert.getEncoded()));

    ASN1Encodable tbsCertificate = struct.getTBSCertificate();
    AlgorithmIdentifier sig = struct.getSignatureAlgorithm();

    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCertificate);
    v.add(new AlgorithmIdentifier(sig.getAlgorithm()));
    v.add(struct.getSignature());

    // verify
    ByteArrayInputStream    bIn;
    String                  dump = "";

    try
    {
        bIn = new ByteArrayInputStream(new DERSequence(v).getEncoded());

        CertificateFactory  fact = CertificateFactory.getInstance("X.509", BC);

        cert = (X509Certificate)fact.generateCertificate(bIn);

        cert.verify(cert.getPublicKey());
    }
    catch (Exception e)
    {
        fail(dump + System.getProperty("line.separator") + getName() + ": testNullDerNull failed - exception " + e.toString(), e);
    }
}
 
Example 32
Project: bc-java   File: CertTest.java   View source code 4 votes vote down vote up
private void testNullDerNullCert()
    throws Exception
{
    KeyPair pair = generateLongFixedKeys();
    PublicKey pubKey = pair.getPublic();
    PrivateKey privKey = pair.getPrivate();

    ContentSigner sigGen = new JcaContentSignerBuilder("MD5WithRSAEncryption").setProvider(BC).build(privKey);
    JcaX509v3CertificateBuilder  certGen = new JcaX509v3CertificateBuilder(new X500Name("CN=Test"),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),new X500Name("CN=Test"),pubKey);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certGen.build(sigGen));

    X509CertificateStructure struct = X509CertificateStructure.getInstance(ASN1Primitive.fromByteArray(cert.getEncoded()));

    ASN1Encodable tbsCertificate = struct.getTBSCertificate();
    AlgorithmIdentifier sig = struct.getSignatureAlgorithm();

    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCertificate);
    v.add(new AlgorithmIdentifier(sig.getAlgorithm()));
    v.add(struct.getSignature());

    // verify
    ByteArrayInputStream    bIn;
    String                  dump = "";

    try
    {
        bIn = new ByteArrayInputStream(new DERSequence(v).getEncoded());

        CertificateFactory  fact = CertificateFactory.getInstance("X.509", BC);

        cert = (X509Certificate)fact.generateCertificate(bIn);

        cert.verify(cert.getPublicKey());
    }
    catch (Exception e)
    {
        fail(dump + System.getProperty("line.separator") + getName() + ": testNullDerNull failed - exception " + e.toString(), e);
    }
}
 
Example 33
Project: bc-java   File: CertTest.java   View source code 4 votes vote down vote up
private void testNullDerNullCert()
    throws Exception
{
    KeyPair pair = generateLongFixedKeys();
    PublicKey pubKey = pair.getPublic();
    PrivateKey privKey = pair.getPrivate();

    ContentSigner sigGen = new JcaContentSignerBuilder("MD5WithRSAEncryption").setProvider(BC).build(privKey);
    JcaX509v3CertificateBuilder  certGen = new JcaX509v3CertificateBuilder(new X500Name("CN=Test"),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),new X500Name("CN=Test"),pubKey);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certGen.build(sigGen));

    X509CertificateStructure struct = X509CertificateStructure.getInstance(ASN1Primitive.fromByteArray(cert.getEncoded()));

    ASN1Encodable tbsCertificate = struct.getTBSCertificate();
    AlgorithmIdentifier sig = struct.getSignatureAlgorithm();

    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCertificate);
    v.add(new AlgorithmIdentifier(sig.getAlgorithm()));
    v.add(struct.getSignature());

    // verify
    ByteArrayInputStream    bIn;
    String                  dump = "";

    try
    {
        bIn = new ByteArrayInputStream(new DERSequence(v).getEncoded());

        CertificateFactory  fact = CertificateFactory.getInstance("X.509", BC);

        cert = (X509Certificate)fact.generateCertificate(bIn);

        cert.verify(cert.getPublicKey());
    }
    catch (Exception e)
    {
        fail(dump + System.getProperty("line.separator") + getName() + ": testNullDerNull failed - exception " + e.toString(), e);
    }
}
 
Example 34
Project: bc-java   File: CertTest.java   View source code 4 votes vote down vote up
private void testNullDerNullCert()
    throws Exception
{
    KeyPair pair = generateLongFixedKeys();
    PublicKey pubKey = pair.getPublic();
    PrivateKey privKey = pair.getPrivate();

    ContentSigner sigGen = new JcaContentSignerBuilder("MD5WithRSAEncryption").setProvider(BC).build(privKey);
    JcaX509v3CertificateBuilder  certGen = new JcaX509v3CertificateBuilder(new X500Name("CN=Test"),BigInteger.valueOf(1),new Date(System.currentTimeMillis() - 50000),new Date(System.currentTimeMillis() + 50000),new X500Name("CN=Test"),pubKey);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certGen.build(sigGen));

    X509CertificateStructure struct = X509CertificateStructure.getInstance(ASN1Primitive.fromByteArray(cert.getEncoded()));

    ASN1Encodable tbsCertificate = struct.getTBSCertificate();
    AlgorithmIdentifier sig = struct.getSignatureAlgorithm();

    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCertificate);
    v.add(new AlgorithmIdentifier(sig.getAlgorithm()));
    v.add(struct.getSignature());

    // verify
    ByteArrayInputStream    bIn;
    String                  dump = "";

    try
    {
        bIn = new ByteArrayInputStream(new DERSequence(v).getEncoded());

        CertificateFactory  fact = CertificateFactory.getInstance("X.509", BC);

        cert = (X509Certificate)fact.generateCertificate(bIn);

        cert.verify(cert.getPublicKey());
    }
    catch (Exception e)
    {
        fail(dump + System.getProperty("line.separator") + getName() + ": testNullDerNull failed - exception " + e.toString(), e);
    }
}
 
Example 35
Project: bc-java   File: CertTest.java   View source code 4 votes vote down vote up
private void testNullDerNullCert()
    throws Exception
{
    KeyPair pair = generateLongFixedKeys();
    PublicKey pubKey = pair.getPublic();
    PrivateKey privKey = pair.getPrivate();

    X509V3CertificateGenerator  certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(1));
    certGen.setIssuerDN(new X509Principal("CN=Test"));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(new X509Principal("CN=Test"));
    certGen.setPublicKey(pubKey);
    certGen.setSignatureAlgorithm("MD5WithRSAEncryption");
    X509Certificate cert = certGen.generate(privKey, "BC");

    X509CertificateStructure struct = X509CertificateStructure.getInstance(ASN1Primitive.fromByteArray(cert.getEncoded()));

    ASN1Encodable tbsCertificate = struct.getTBSCertificate();
    AlgorithmIdentifier sig = struct.getSignatureAlgorithm();

    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCertificate);
    v.add(new AlgorithmIdentifier(sig.getObjectId()));
    v.add(struct.getSignature());

    // verify
    ByteArrayInputStream    bIn;
    String                  dump = "";

    try
    {
        bIn = new ByteArrayInputStream(new DERSequence(v).getEncoded());

        CertificateFactory  fact = CertificateFactory.getInstance("X.509", "BC");

        cert = (X509Certificate)fact.generateCertificate(bIn);

        cert.verify(cert.getPublicKey());
    }
    catch (Exception e)
    {
        fail(dump + System.getProperty("line.separator") + getName() + ": testNullDerNull failed - exception " + e.toString(), e);
    }
}
 
Example 36
Project: jradius   File: TlsRSAKeyExchange.java   View source code 4 votes vote down vote up
public void processServerCertificate(Certificate serverCertificate) throws IOException
{
    X509CertificateStructure x509Cert = serverCertificate.certs[0];
    SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo();

    try
    {
        this.serverPublicKey = PublicKeyFactory.createKey(keyInfo);
    }
    catch (RuntimeException e)
    {
        handler.failWithError(TlsProtocolHandler.AL_fatal,
            TlsProtocolHandler.AP_unsupported_certificate);
    }

    // Sanity check the PublicKeyFactory
    if (this.serverPublicKey.isPrivate())
    {
        handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_internal_error);
    }

    // TODO 
    /*
     * Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the
     * signing algorithm for the certificate must be the same as the algorithm for the
     * certificate key."
     */

    // TODO Should the 'instanceof' tests be replaces with stricter checks on keyInfo.getAlgorithmId()?

    if (!(this.serverPublicKey instanceof RSAKeyParameters))
    {
        handler.failWithError(TlsProtocolHandler.AL_fatal,
            TlsProtocolHandler.AP_certificate_unknown);
    }
    validateKeyUsage(x509Cert, KeyUsage.keyEncipherment);
    this.rsaServerPublicKey = validateRSAPublicKey((RSAKeyParameters)this.serverPublicKey);

    /*
     * Verify them.
     */
    if (!this.verifyer.isValid(serverCertificate.getCerts()))
    {
        handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_user_canceled);
    }
}
 
Example 37
Project: jradius   File: TlsDHKeyExchange.java   View source code 4 votes vote down vote up
public void processServerCertificate(Certificate serverCertificate) throws IOException
    {
        X509CertificateStructure x509Cert = serverCertificate.certs[0];
        SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo();

        try
        {
            this.serverPublicKey = PublicKeyFactory.createKey(keyInfo);
        }
        catch (RuntimeException e)
        {
            handler.failWithError(TlsProtocolHandler.AL_fatal,
                TlsProtocolHandler.AP_unsupported_certificate);
        }

        // Sanity check the PublicKeyFactory
        if (this.serverPublicKey.isPrivate())
        {
            handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_internal_error);
        }

        // TODO 
        /*
         * Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the
         * signing algorithm for the certificate must be the same as the algorithm for the
         * certificate key."
         */

        // TODO Should the 'instanceof' tests be replaces with stricter checks on keyInfo.getAlgorithmId()?

        switch (this.keyExchange)
        {
            case TlsKeyExchange.KE_DH_DSS:
                if (!(this.serverPublicKey instanceof DHPublicKeyParameters))
                {
                    handler.failWithError(TlsProtocolHandler.AL_fatal,
                        TlsProtocolHandler.AP_certificate_unknown);
                }
                // TODO The algorithm used to sign the certificate should be DSS.
//                x509Cert.getSignatureAlgorithm();
                this.dhAgreeServerPublicKey = validateDHPublicKey((DHPublicKeyParameters)this.serverPublicKey);
                break;
            case TlsKeyExchange.KE_DH_RSA:
                if (!(this.serverPublicKey instanceof DHPublicKeyParameters))
                {
                    handler.failWithError(TlsProtocolHandler.AL_fatal,
                        TlsProtocolHandler.AP_certificate_unknown);
                }
                // TODO The algorithm used to sign the certificate should be RSA.
//              x509Cert.getSignatureAlgorithm();
                this.dhAgreeServerPublicKey = validateDHPublicKey((DHPublicKeyParameters)this.serverPublicKey);
                break;
            case TlsKeyExchange.KE_DHE_RSA:
                if (!(this.serverPublicKey instanceof RSAKeyParameters))
                {
                    handler.failWithError(TlsProtocolHandler.AL_fatal,
                        TlsProtocolHandler.AP_certificate_unknown);
                }
                validateKeyUsage(x509Cert, KeyUsage.digitalSignature);
                break;
            case TlsKeyExchange.KE_DHE_DSS:
                if (!(this.serverPublicKey instanceof DSAPublicKeyParameters))
                {
                    handler.failWithError(TlsProtocolHandler.AL_fatal,
                        TlsProtocolHandler.AP_certificate_unknown);
                }
                break;
            default:
                handler.failWithError(TlsProtocolHandler.AL_fatal,
                    TlsProtocolHandler.AP_unsupported_certificate);
        }

        /*
         * Verify them.
         */
        if (!this.verifyer.isValid(serverCertificate.getCerts()))
        {
            handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_user_canceled);
        }
    }
 
Example 38
Project: jradius   File: TlsSRPKeyExchange.java   View source code 4 votes vote down vote up
public void processServerCertificate(Certificate serverCertificate) throws IOException
{
    if (tlsSigner == null)
    {
        handler.failWithError(TlsProtocolHandler.AL_fatal,
            TlsProtocolHandler.AP_unexpected_message);
    }

    X509CertificateStructure x509Cert = serverCertificate.certs[0];
    SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo();

    try
    {
        this.serverPublicKey = PublicKeyFactory.createKey(keyInfo);
    }
    catch (RuntimeException e)
    {
        handler.failWithError(TlsProtocolHandler.AL_fatal,
            TlsProtocolHandler.AP_unsupported_certificate);
    }

    // Sanity check the PublicKeyFactory
    if (this.serverPublicKey.isPrivate())
    {
        handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_internal_error);
    }

    // TODO 
    /*
     * Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the
     * signing algorithm for the certificate must be the same as the algorithm for the
     * certificate key."
     */
    switch (this.keyExchange)
    {
        case TlsKeyExchange.KE_SRP_RSA:
            if (!(this.serverPublicKey instanceof RSAKeyParameters))
            {
                handler.failWithError(TlsProtocolHandler.AL_fatal,
                    TlsProtocolHandler.AP_certificate_unknown);
            }
            validateKeyUsage(x509Cert, KeyUsage.digitalSignature);
            break;
        case TlsKeyExchange.KE_SRP_DSS:
            if (!(this.serverPublicKey instanceof DSAPublicKeyParameters))
            {
                handler.failWithError(TlsProtocolHandler.AL_fatal,
                    TlsProtocolHandler.AP_certificate_unknown);
            }
            break;
        default:
            handler.failWithError(TlsProtocolHandler.AL_fatal,
                TlsProtocolHandler.AP_unsupported_certificate);
    }

    /*
     * Verify them.
     */
    if (!this.verifyer.isValid(serverCertificate.getCerts()))
    {
        handler.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_user_canceled);
    }
}
 
Example 39
Project: cagrid-general   File: BouncyCastleCertProcessingFactory.java   View source code 3 votes vote down vote up
/**
    * Loads a X509 certificate from the specified input stream.
    * Input stream must contain DER-encoded certificate.
    *
    * @param in the input stream to read the certificate from.
    * @return <code>X509Certificate</code> the loaded certificate.
    * @exception GeneralSecurityException if certificate failed to load.
    */
   public X509Certificate loadCertificate(InputStream in)
throws IOException, GeneralSecurityException {
DERInputStream derin = new DERInputStream(in);
DERObject certInfo = derin.readObject();
ASN1Sequence seq = ASN1Sequence.getInstance(certInfo);
return new X509CertificateObject(new X509CertificateStructure(seq));
   }
 
Example 40
Project: cagrid-core   File: BouncyCastleCertProcessingFactory.java   View source code 3 votes vote down vote up
/**
 * Loads a X509 certificate from the specified input stream. Input stream
 * must contain DER-encoded certificate.
 * 
 * @param in
 *            the input stream to read the certificate from.
 * @return <code>X509Certificate</code> the loaded certificate.
 * @exception GeneralSecurityException
 *                if certificate failed to load.
 */
public X509Certificate loadCertificate(InputStream in) throws IOException, GeneralSecurityException {
	DERInputStream derin = new DERInputStream(in);
	DERObject certInfo = derin.readObject();
	ASN1Sequence seq = ASN1Sequence.getInstance(certInfo);
	return new X509CertificateObject(new X509CertificateStructure(seq));
}