Ejemplo n.º 1
0
  /**
   * Reads in a PKCS7 object. This returns a ContentInfo object suitable for use with the CMS API.
   *
   * @return the X509Certificate
   * @throws IOException if an I/O error occured
   */
  private static CMSSignedData readPKCS7(BufferedReader in, char[] p, String endMarker)
      throws IOException {
    String line;
    StringBuffer buf = new StringBuffer();
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    while ((line = in.readLine()) != null) {
      if (line.indexOf(endMarker) != -1) {
        break;
      }
      line = line.trim();
      buf.append(line.trim());
      Base64.decode(buf.substring(0, (buf.length() / 4) * 4), bOut);
      buf.delete(0, (buf.length() / 4) * 4);
    }
    if (buf.length() != 0) {
      throw new RuntimeException("base64 data appears to be truncated");
    }
    if (line == null) {
      throw new IOException(endMarker + " not found");
    }
    try {
      ASN1InputStream aIn = new ASN1InputStream(bOut.toByteArray());
      return new CMSSignedData(ContentInfo.getInstance(aIn.readObject()));
    } catch (Exception e) {
      throw new IOException("problem parsing PKCS7 object: " + e.toString());
    }
  }
Ejemplo n.º 2
0
  public void fromAsn1(byte[] data, int defaultCAKeyID) throws IOException, EIDException {

    try {
      ASN1InputStream ais = new ASN1InputStream(data);
      try {

        ASN1Sequence seq = (ASN1Sequence) ais.readObject();
        ContentInfo ci = ContentInfo.getInstance(seq);

        if (!ci.getContentType().equals(CMSObjectIdentifiers.signedData))
          throw new EIDException("wrong content type in CardSecurity");

        SignedData sd = SignedData.getInstance((ASN1Sequence) ci.getContent());
        ContentInfo eci = sd.getEncapContentInfo();

        if (!eci.getContentType().equals(EAC2ObjectIdentifiers.id_SecurityObject))
          throw new EIDException("CardSecurity does not encapsulate SecurityInfos");

        SecurityInfos si = new SecurityInfos();
        si.fromAsn1(((ASN1OctetString) eci.getContent()).getOctets(), defaultCAKeyID);
        securityInfos = si;
      } finally {
        ais.close();
      }

    } catch (Exception e) {
      throw new EIDException(e);
    }
  }
Ejemplo n.º 3
0
  /**
   * Sets the values of the certificate (body and signature).
   *
   * @param appSpe is a ASN1ApplicationSpecific object containing body and signature.
   * @throws IOException if tags or value are incorrect.
   */
  private void setPrivateData(ASN1ApplicationSpecific appSpe) throws IOException {
    valid = 0;
    if (appSpe.getApplicationTag() == EACTags.CARDHOLDER_CERTIFICATE) {
      ASN1InputStream content = new ASN1InputStream(appSpe.getContents());
      ASN1Primitive tmpObj;
      while ((tmpObj = content.readObject()) != null) {
        DERApplicationSpecific aSpe;
        if (tmpObj instanceof DERApplicationSpecific) {
          aSpe = (DERApplicationSpecific) tmpObj;
          switch (aSpe.getApplicationTag()) {
            case EACTags.CERTIFICATE_CONTENT_TEMPLATE:
              certificateBody = CertificateBody.getInstance(aSpe);
              valid |= bodyValid;
              break;
            case EACTags.STATIC_INTERNAL_AUTHENTIFICATION_ONE_STEP:
              signature = aSpe.getContents();
              valid |= signValid;
              break;
            default:
              throw new IOException(
                  "Invalid tag, not an Iso7816CertificateStructure :" + aSpe.getApplicationTag());
          }
        } else {
          throw new IOException("Invalid Object, not an Iso7816CertificateStructure");
        }
      }
      content.close();
    } else {
      throw new IOException("not a CARDHOLDER_CERTIFICATE :" + appSpe.getApplicationTag());
    }

    if (valid != (signValid | bodyValid)) {
      throw new IOException("invalid CARDHOLDER_CERTIFICATE :" + appSpe.getApplicationTag());
    }
  }
Ejemplo n.º 4
0
  /**
   * create from an issuer certificate and the serial number of the certificate it signed.
   *
   * @exception OCSPException if any problems occur creating the id fields.
   */
  public CertificateID(
      String hashAlgorithm, X509Certificate issuerCert, BigInteger number, String provider)
      throws OCSPException {
    try {
      MessageDigest digest = MessageDigest.getInstance(hashAlgorithm, provider);
      AlgorithmIdentifier hashAlg =
          new AlgorithmIdentifier(new DERObjectIdentifier(hashAlgorithm), new DERNull());

      X509Principal issuerName = PrincipalUtil.getSubjectX509Principal(issuerCert);

      digest.update(issuerName.getEncoded());

      ASN1OctetString issuerNameHash = new DEROctetString(digest.digest());
      PublicKey issuerKey = issuerCert.getPublicKey();

      ASN1InputStream aIn = new ASN1InputStream(issuerKey.getEncoded());
      SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject());

      digest.update(info.getPublicKeyData().getBytes());

      ASN1OctetString issuerKeyHash = new DEROctetString(digest.digest());

      DERInteger serialNumber = new DERInteger(number);

      this.id = new CertID(hashAlg, issuerNameHash, issuerKeyHash, serialNumber);
    } catch (Exception e) {
      throw new OCSPException("problem creating ID: " + e, e);
    }
  }
Ejemplo n.º 5
0
  public TestResult pkcs10Test(String testName, byte[] req) {
    try {
      ByteArrayInputStream bIn = new ByteArrayInputStream(req);
      ASN1InputStream aIn = new ASN1InputStream(bIn);

      CertificationRequest r = new CertificationRequest((ASN1Sequence) aIn.readObject());

      ByteArrayOutputStream bOut = new ByteArrayOutputStream();
      DEROutputStream dOut = new DEROutputStream(bOut);

      dOut.writeObject(r.getDERObject());

      byte[] bytes = bOut.toByteArray();

      if (bytes.length != req.length) {
        return new SimpleTestResult(false, getName() + ": " + testName + " failed length test");
      }

      for (int i = 0; i != req.length; i++) {
        if (bytes[i] != req[i]) {
          return new SimpleTestResult(
              false, getName() + ": " + testName + " failed comparison test");
        }
      }
    } catch (Exception e) {
      return new SimpleTestResult(
          false, getName() + ": Exception - " + testName + " " + e.toString());
    }

    return new SimpleTestResult(true, getName() + ": Okay");
  }
  private DERObject createDERForRecipient(byte[] in, X509Certificate cert)
      throws IOException, GeneralSecurityException {

    String s = "1.2.840.113549.3.2";

    AlgorithmParameterGenerator algorithmparametergenerator =
        AlgorithmParameterGenerator.getInstance(s);
    AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters();
    ByteArrayInputStream bytearrayinputstream =
        new ByteArrayInputStream(algorithmparameters.getEncoded("ASN.1"));
    ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream);
    DERObject derobject = asn1inputstream.readObject();
    KeyGenerator keygenerator = KeyGenerator.getInstance(s);
    keygenerator.init(128);
    SecretKey secretkey = keygenerator.generateKey();
    Cipher cipher = Cipher.getInstance(s);
    cipher.init(1, secretkey, algorithmparameters);
    byte[] abyte1 = cipher.doFinal(in);
    DEROctetString deroctetstring = new DEROctetString(abyte1);
    KeyTransRecipientInfo keytransrecipientinfo =
        computeRecipientInfo(cert, secretkey.getEncoded());
    DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
    AlgorithmIdentifier algorithmidentifier =
        new AlgorithmIdentifier(new DERObjectIdentifier(s), derobject);
    EncryptedContentInfo encryptedcontentinfo =
        new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring);
    EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, null);
    ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
    return contentinfo.getDERObject();
  }
Ejemplo n.º 7
0
 /** @return the first object found when treating the provided byte array as an ASN1InputStream */
 @SuppressWarnings("unchecked")
 private static <T> T getAsn1ObjectFromBytes(final byte[] bytes, final Class<T> clazz) {
   T ret = null;
   ASN1InputStream asn1InputStream = null;
   try {
     if (bytes != null) {
       asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(bytes));
       ret = (T) asn1InputStream.readObject();
     }
   } catch (ClassCastException e) {
     // Ignore
     log.info("Failed to extract expected ASN1 object from bytes array.", e);
   } catch (IOException e) {
     // Ignore
     log.info("Failed to extract ASN1 object from bytes array.", e);
   } finally {
     if (asn1InputStream != null) {
       try {
         asn1InputStream.close();
       } catch (IOException e) {
         log.info("Failed to extract expected ASN1 object from bytes array.", e);
       }
     }
   }
   return ret;
 }
Ejemplo n.º 8
0
  private String generateSubjectKeyIdentifier(Certificate certificate) throws IOException {
    String subjectKeyIdentifier;
    ASN1InputStream is;
    SubjectPublicKeyInfo spki;
    SubjectKeyIdentifier ski;

    subjectKeyIdentifier = null;
    is = null;
    spki = null;
    ski = null;

    try {
      is = new ASN1InputStream(certificate.getPublicKey().getEncoded());

      spki = new SubjectPublicKeyInfo((ASN1Sequence) is.readObject());
      ski = new SubjectKeyIdentifier(spki);
    } finally {
      if (is != null) {
        is.close();
      }
    }

    subjectKeyIdentifier = new String(Hex.encode(ski.getKeyIdentifier()));

    return subjectKeyIdentifier;
  }
  /** Tests the extension Freshest CRL DP. */
  @Test
  public void testCRLFreshestCRL() throws Exception {
    final String cdpURL = "http://www.ejbca.org/foo/bar.crl";
    final String freshestCdpURL = "http://www.ejbca.org/foo/delta.crl";
    X509CAInfo cainfo = (X509CAInfo) testx509ca.getCAInfo();
    X509CRL x509crl;
    byte[] cFreshestDpDER;

    cainfo.setUseCrlDistributionPointOnCrl(true);
    cainfo.setDefaultCRLDistPoint(cdpURL);
    cainfo.setCADefinedFreshestCRL(freshestCdpURL);
    caSession.editCA(roleMgmgToken, cainfo);
    publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId());
    x509crl =
        CertTools.getCRLfromByteArray(crlStoreSession.getLastCRL(cainfo.getSubjectDN(), false));
    cFreshestDpDER = x509crl.getExtensionValue(Extension.freshestCRL.getId());
    assertNotNull("CRL has no Freshest Distribution Point", cFreshestDpDER);

    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(cFreshestDpDER));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    CRLDistPoint cdp = CRLDistPoint.getInstance((ASN1Sequence) aIn.readObject());
    DistributionPoint[] distpoints = cdp.getDistributionPoints();

    assertEquals("More CRL Freshest distributions points than expected", 1, distpoints.length);
    assertEquals(
        "Freshest CRL distribution point is different",
        freshestCdpURL,
        ((DERIA5String)
                ((GeneralNames) distpoints[0].getDistributionPoint().getName())
                    .getNames()[0].getName())
            .getString());
  }
Ejemplo n.º 10
0
  public static OtherStatusInfo getInstance(Object obj) {
    if (obj instanceof OtherStatusInfo) {
      return (OtherStatusInfo) obj;
    }

    if (obj instanceof ASN1Encodable) {
      ASN1Encodable asn1Value = ((ASN1Encodable) obj).toASN1Primitive();

      if (asn1Value instanceof ASN1Integer) // CMCFail info is an asn1 integer.
      {
        return new OtherStatusInfo(CMCFailInfo.getInstance(asn1Value));
      } else if (asn1Value instanceof ASN1Sequence) // PendInfo is a sequence.
      {
        if (((ASN1Sequence) asn1Value).getObjectAt(0) instanceof ASN1ObjectIdentifier) {
          return new OtherStatusInfo(ExtendedFailInfo.getInstance(asn1Value));
        }
        return new OtherStatusInfo(PendInfo.getInstance(asn1Value));
      }
    } else if (obj instanceof byte[]) {
      ASN1InputStream ain = new ASN1InputStream(new ByteArrayInputStream((byte[]) obj));
      try {
        return getInstance(ain.readObject());
      } catch (Exception e) {
        throw new IllegalArgumentException(e.getMessage(), e);
      } finally {
        try {
          ain.close();
        } catch (IOException e) {
          throw new IllegalArgumentException(e.getMessage(), e);
        }
      }
    }
    throw new IllegalArgumentException(
        "unknown object in getInstance(): " + obj.getClass().getName());
  }
Ejemplo n.º 11
0
  public CryptEngineImpl(Context ctx) throws Exception {

    // Получаем действующее хранилище
    IKeyStorage storage = KeyStorageFactory.getKeyStorage(ctx);

    Log.v("TFORWARD.CryptEngineImpl", "Decoding public key...");
    byte[] publicKey = Base64.decode(storage.getKey(IKeyStorage.PUBLIC_KEY_TYPE), Base64.DEFAULT);

    Log.v("TFORWARD.CryptEngineImpl", "Decoding ASN1 Structure");
    ASN1InputStream asnStream = new ASN1InputStream(publicKey);

    ASN1Sequence sequence = null;
    try {
      Log.v("TFORWARD.CryptEngineImpl", "Reading ASN1 Sequence");
      sequence = (ASN1Sequence) asnStream.readObject();
    } finally {
      asnStream.close();
    }

    Log.v("TFORWARD.CryptEngineImpl", "Creating certificate. " + sequence.size());
    Certificate certificate = Certificate.getInstance(sequence);
    SubjectPublicKeyInfo publicKeyInfo = certificate.getSubjectPublicKeyInfo();

    RSAPublicKey publicKeyStructure = RSAPublicKey.getInstance(publicKeyInfo.parsePublicKey());
    BigInteger mod = publicKeyStructure.getModulus();
    BigInteger pubExp = publicKeyStructure.getPublicExponent();

    publicRsaKey = new RSAKeyParameters(false, mod, pubExp);

    // ------------------------ PRIVATE KEY --------------------------------
    byte[] privateKeyData =
        Base64.decode(storage.getKey(IKeyStorage.SECRET_KEY_TYPE), Base64.DEFAULT);
    asnStream = new ASN1InputStream(privateKeyData);

    ASN1Sequence asnSequence = null;
    try {
      asnSequence = (ASN1Sequence) asnStream.readObject();
    } finally {
      asnStream.close();
    }

    RSAPrivateKey privateKey = RSAPrivateKey.getInstance(asnSequence);
    privateRsaKey =
        new RSAPrivateCrtKeyParameters(
            privateKey.getModulus(),
            privateKey.getPublicExponent(),
            privateKey.getPrivateExponent(),
            privateKey.getPrime1(),
            privateKey.getPrime2(),
            privateKey.getExponent1(),
            privateKey.getExponent2(),
            privateKey.getCoefficient());

    RSAEngine engine = new RSAEngine();
    digest = new MD5Digest();
    cipher = new PKCS1Encoding(engine);
  }
  private static ASN1Primitive getObject(String oid, byte[] ext) throws AnnotatedException {
    try {
      ASN1InputStream aIn = new ASN1InputStream(ext);
      ASN1OctetString octs = (ASN1OctetString) aIn.readObject();

      aIn = new ASN1InputStream(octs.getOctets());
      return aIn.readObject();
    } catch (Exception e) {
      throw new AnnotatedException("exception processing extension " + oid, e);
    }
  }
  protected static AlgorithmIdentifier getAlgorithmIdentifier(PublicKey key)
      throws CertPathValidatorException {
    try {
      ASN1InputStream aIn = new ASN1InputStream(key.getEncoded());

      SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject());

      return info.getAlgorithmId();
    } catch (Exception e) {
      throw new ExtCertPathValidatorException("Subject public key cannot be decoded.", e);
    }
  }
Ejemplo n.º 14
0
  protected BigInteger[] derDecode(byte[] encoding) throws IOException {
    ByteArrayInputStream bIn = new ByteArrayInputStream(encoding);
    ASN1InputStream aIn = new ASN1InputStream(bIn);
    ASN1Sequence s = (ASN1Sequence) aIn.readObject();

    BigInteger[] sig = new BigInteger[2];

    sig[0] = ((DERInteger) s.getObjectAt(0)).getValue();
    sig[1] = ((DERInteger) s.getObjectAt(1)).getValue();

    return sig;
  }
Ejemplo n.º 15
0
 public void fromByteArray(byte[] encodedData) {
   ASN1InputStream asn1in = new ASN1InputStream(encodedData);
   try {
     to = (DERTaggedObject) asn1in.readObject();
     asn1in.close();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   DEROctetString ocs = (DEROctetString) to.getObject();
   data = ocs.getOctets();
 }
  protected static AlgorithmIdentifier getAlgorithmIdentifier(PublicKey key)
      throws CertPathValidatorException {
    try {
      ASN1InputStream aIn = new ASN1InputStream(key.getEncoded());

      SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject());

      return info.getAlgorithmId();
    } catch (IOException e) {
      throw new CertPathValidatorException("exception processing public key");
    }
  }
Ejemplo n.º 17
0
 /** Return an Extension ASN1Primitive from a CRL */
 protected static ASN1Primitive getExtensionValue(X509CRL crl, String oid) throws IOException {
   if (crl == null) {
     return null;
   }
   byte[] bytes = crl.getExtensionValue(oid);
   if (bytes == null) {
     return null;
   }
   ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bytes));
   ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
   aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
   return aIn.readObject();
 } // getExtensionValue
Ejemplo n.º 18
0
  @Test
  public void testMultipleSignatures() throws Exception {

    ASN1InputStream is = new ASN1InputStream(Base64.decode(podpis1));
    ASN1Primitive primitive = is.readObject();
    System.out.println(org.bouncycastle.asn1.util.ASN1Dump.dumpAsString(primitive));

    assertTrue(verify(podpis1) == 1);

    is = new ASN1InputStream(Base64.decode(podpis2));
    primitive = is.readObject();
    System.out.println(org.bouncycastle.asn1.util.ASN1Dump.dumpAsString(primitive));

    assertTrue(verify(podpis2) == 2);
  }
Ejemplo n.º 19
0
  private void checkConstruction(Restriction restriction, DirectoryString res) throws IOException {
    checkValues(restriction, res);

    restriction = Restriction.getInstance(restriction);

    checkValues(restriction, res);

    ASN1InputStream aIn = new ASN1InputStream(restriction.toASN1Object().getEncoded());

    ASN1String str = (ASN1String) aIn.readObject();

    restriction = Restriction.getInstance(str);

    checkValues(restriction, res);
  }
  /*
   * Constructs (i.e., parses) an <code>EncryptedPrivateKeyInfo</code> from
   * its ASN.1 encoding.
   *
   * @param encoded the ASN.1 encoding of this object.
   * @exception NullPointerException if the <code>encoded</code> is null.
   * @exception IOException if error occurs when parsing the ASN.1 encoding.
   */
  public EncryptedPrivateKeyInfo(byte[] encoded) throws NullPointerException, IOException {
    if (encoded == null) {
      throw new NullPointerException("parameters null");
    }

    ByteArrayInputStream bIn = new ByteArrayInputStream(encoded);
    ASN1InputStream dIn = new ASN1InputStream(bIn);

    infoObj =
        new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo((ASN1Sequence) dIn.readObject());

    try {
      algP = this.getParameters();
    } catch (NoSuchAlgorithmException e) {
      throw new IOException("can't create parameters: " + e.toString());
    }
  }
Ejemplo n.º 21
0
  private DigestInfo derDecode(byte[] encoding) throws IOException, CMSException {
    if (encoding[0] != (DERTags.CONSTRUCTED | DERTags.SEQUENCE)) {
      throw new IOException("not a digest info object");
    }

    ASN1InputStream aIn = new ASN1InputStream(encoding);

    DigestInfo digInfo = new DigestInfo((ASN1Sequence) aIn.readObject());

    // length check to avoid Bleichenbacher vulnerability

    if (digInfo.getEncoded().length != encoding.length) {
      throw new CMSException("malformed RSA signature");
    }

    return digInfo;
  }
Ejemplo n.º 22
0
  /**
   * This method returns the {@code ASN1Sequence} encapsulated in {@code DEROctetString}. The {@code
   * DEROctetString} is represented as {@code byte} array.
   *
   * @param bytes {@code byte} representation of {@code DEROctetString}
   * @return encapsulated {@code ASN1Sequence}
   * @throws DSSException in case of a decoding problem
   */
  public static ASN1Sequence getAsn1SequenceFromDerOctetString(byte[] bytes) throws DSSException {

    ASN1InputStream input = null;
    try {

      input = new ASN1InputStream(bytes);
      final DEROctetString s = (DEROctetString) input.readObject();
      final byte[] content = s.getOctets();
      input.close();
      input = new ASN1InputStream(content);
      final ASN1Sequence seq = (ASN1Sequence) input.readObject();
      return seq;
    } catch (IOException e) {
      throw new DSSException("Error when converting byte array to ASN1Sequence!", e);
    } finally {
      DSSUtils.closeQuietly(input);
    }
  }
 private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0)
     throws GeneralSecurityException, IOException {
   ASN1InputStream asn1inputstream =
       new ASN1InputStream(new ByteArrayInputStream(x509certificate.getTBSCertificate()));
   TBSCertificateStructure tbscertificatestructure =
       TBSCertificateStructure.getInstance(asn1inputstream.readObject());
   AlgorithmIdentifier algorithmidentifier =
       tbscertificatestructure.getSubjectPublicKeyInfo().getAlgorithmId();
   IssuerAndSerialNumber issuerandserialnumber =
       new IssuerAndSerialNumber(
           tbscertificatestructure.getIssuer(),
           tbscertificatestructure.getSerialNumber().getValue());
   Cipher cipher = Cipher.getInstance(algorithmidentifier.getObjectId().getId());
   cipher.init(1, x509certificate.getPublicKey());
   DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0));
   RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber);
   return new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring);
 }
Ejemplo n.º 24
0
 private void initFrom(ASN1InputStream aIS) throws IOException {
   ASN1Primitive obj;
   while ((obj = aIS.readObject()) != null) {
     if (obj instanceof DERApplicationSpecific) {
       setPrivateData((DERApplicationSpecific) obj);
     } else {
       throw new IOException("Invalid Input Stream for creating an Iso7816CertificateStructure");
     }
   }
 }
Ejemplo n.º 25
0
  /**
   * 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);
  }
  protected static DataBuffer convertToPlainBC(byte[] sign) {

    ASN1InputStream dIn = new ASN1InputStream(sign);
    ASN1Primitive obj;
    try {

      obj = dIn.readObject();

      if (obj instanceof ASN1Sequence) {
        ASN1Sequence seq = (ASN1Sequence) obj;
        if (seq.size() == 2) {
          ASN1Integer r = (ASN1Integer) seq.getObjectAt(0);
          ASN1Integer s = (ASN1Integer) seq.getObjectAt(1);
          byte[] res;
          byte[] byteR = makeUnsigned(r.getValue());
          byte[] byteS = makeUnsigned(s.getValue());

          if (byteR.length > byteS.length) {
            res = new byte[byteR.length * 2];
          } else {
            res = new byte[byteS.length * 2];
          }

          System.arraycopy(byteR, 0, res, res.length / 2 - byteR.length, byteR.length);
          System.arraycopy(byteS, 0, res, res.length - byteS.length, byteS.length);

          return new DataBuffer(res);
        }
      }
    } catch (Exception e) {
    } finally {
      try {
        dIn.close();
      } catch (Exception e) {
        // ???
      }
    }
    return new DataBuffer(sign);
  }
Ejemplo n.º 27
0
  public static String getStringOid(DataBuffer buffer) {
    // terrible code, due to changes in BC's API
    // buffer should only contain an OID value, i.e. 0x06 tag and length
    // field are missing
    byte[] tagBuf = {(byte) 0x06};
    byte[] sizeBuf = new byte[] {(byte) buffer.size()};
    DataBuffer tmp = concat(tagBuf, sizeBuf, buffer.toByteArray());
    ASN1InputStream aIn = new ASN1InputStream(tmp.toByteArray());
    ASN1ObjectIdentifier o = null;
    try {
      o = (ASN1ObjectIdentifier) aIn.readObject();
    } catch (IOException e) {
    } finally {
      try {
        aIn.close();
      } catch (Exception e) {
        // ???
      }
    }

    return o.getId();
  }
Ejemplo n.º 28
0
 private static boolean certHasPolicy(X509Certificate cert, String sOid) {
   try {
     if (m_logger.isDebugEnabled())
       m_logger.debug("Read cert policies: " + cert.getSerialNumber().toString());
     ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
     ASN1InputStream aIn = new ASN1InputStream(bIn);
     ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
     X509CertificateStructure obj = new X509CertificateStructure(seq);
     TBSCertificateStructure tbsCert = obj.getTBSCertificate();
     if (tbsCert.getVersion() == 3) {
       X509Extensions ext = tbsCert.getExtensions();
       if (ext != null) {
         Enumeration en = ext.oids();
         while (en.hasMoreElements()) {
           DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement();
           X509Extension extVal = ext.getExtension(oid);
           ASN1OctetString oct = extVal.getValue();
           ASN1InputStream extIn = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets()));
           // if (oid.equals(X509Extensions.CertificatePolicies)) { // bc 146 ja jdk 1.6 puhul -
           // X509Extension.certificatePolicies
           if (oid.equals(X509Extension.certificatePolicies)) { // bc 146 ja jdk 1.6 puhul -
             // X509Extension.certificatePolicies
             ASN1Sequence cp = (ASN1Sequence) extIn.readObject();
             for (int i = 0; i != cp.size(); i++) {
               PolicyInformation pol = PolicyInformation.getInstance(cp.getObjectAt(i));
               DERObjectIdentifier dOid = pol.getPolicyIdentifier();
               String soid2 = dOid.getId();
               if (m_logger.isDebugEnabled()) m_logger.debug("Policy: " + soid2);
               if (soid2.startsWith(sOid)) return true;
             }
           }
         }
       }
     }
   } catch (Exception ex) {
     m_logger.error("Error reading cert policies: " + ex);
   }
   return false;
 }
Ejemplo n.º 29
0
 /**
  * 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);
     DERObject 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);
 }
  /**
   * Constructs an <code>EncryptedPrivateKeyInfo</code> from the encryption algorithm parameters and
   * the encrypted data.
   *
   * <p>Note: the <code>encrypedData</code> is cloned when constructing this object.
   *
   * @param algParams the algorithm parameters for the encryption algorithm. <code>
   *     algParams.getEncoded()</code> should return the ASN.1 encoded bytes of the <code>parameters
   *     </code> field of the <code>AlgorithmIdentifer</code> component of the <code>
   *     EncryptedPrivateKeyInfo</code> type.
   * @param encryptedData encrypted data.
   * @exception NullPointerException if <code>algParams</code> or <code>encryptedData</code> is
   *     null.
   * @exception IllegalArgumentException if <code>encryptedData</code> is empty, i.e. 0-length.
   * @exception NoSuchAlgorithmException if the specified algName of the specified <code>algParams
   *     </code> parameter is not supported.
   */
  public EncryptedPrivateKeyInfo(AlgorithmParameters algParams, byte[] encryptedData)
      throws NullPointerException, IllegalArgumentException, NoSuchAlgorithmException {
    if (algParams == null || encryptedData == null) {
      throw new NullPointerException("parameters null");
    }

    org.bouncycastle.asn1.x509.AlgorithmIdentifier kAlgId = null;

    try {
      ByteArrayInputStream bIn = new ByteArrayInputStream(algParams.getEncoded());
      ASN1InputStream dIn = new ASN1InputStream(bIn);

      kAlgId =
          new AlgorithmIdentifier(
              new DERObjectIdentifier(algParams.getAlgorithm()), dIn.readObject());
    } catch (IOException e) {
      throw new IllegalArgumentException("error in encoding: " + e.toString());
    }

    infoObj =
        new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo(
            kAlgId, (byte[]) encryptedData.clone());
    algP = this.getParameters();
  }