Exemplo n.º 1
0
  public PublicKey getPublicCAKey()
      throws InvalidKeySpecException, IOException, NoSuchAlgorithmException,
          NoSuchProviderException {
    ChipAuthenticationPublicKeyInfo info =
        securityInfos.getDefaultChipAuthenticationPublicKeyInfo();
    AlgorithmParameterSpec algorithmParameterSpec =
        securityInfos.getDefaultCADomainParameter().getAlgorithmParameterSpec();
    Type type = securityInfos.getDefaultCADomainParameter().getType();

    PublicKey pubKey = null;
    if (type == Type.ECDH) {
      ECParameterSpec eps = (ECParameterSpec) algorithmParameterSpec;
      DEROctetString dos =
          new DEROctetString(info.getSubjectPublicKeyInfo().getPublicKeyData().getBytes());

      ECPoint point = new X9ECPoint(eps.getCurve(), dos).getPoint();
      ECPublicKeySpec eks = new ECPublicKeySpec(point, eps);

      pubKey = new JCEECPublicKey(type.toString(), eks);

    } else {

      DHParameterSpec dps = (DHParameterSpec) algorithmParameterSpec;
      ASN1Integer dos =
          new ASN1Integer(info.getSubjectPublicKeyInfo().getPublicKeyData().getBytes());
      DHPublicKeySpec keySpec = new DHPublicKeySpec(dos.getPositiveValue(), dps.getP(), dps.getG());
      KeyFactory kf = KeyFactory.getInstance(type.toString());
      return kf.generatePublic(keySpec);
    }

    return pubKey;
  }
Exemplo n.º 2
0
 private MonetaryValue(ASN1Sequence seq) {
   Enumeration e = seq.getObjects();
   // currency
   currency = Iso4217CurrencyCode.getInstance(e.nextElement());
   // hashAlgorithm
   amount = ASN1Integer.getInstance(e.nextElement());
   // exponent
   exponent = ASN1Integer.getInstance(e.nextElement());
 }
Exemplo n.º 3
0
  private ResponseData(ASN1Sequence seq) {
    int index = 0;

    if (seq.getObjectAt(0) instanceof ASN1TaggedObject) {
      ASN1TaggedObject o = (ASN1TaggedObject) seq.getObjectAt(0);

      if (o.getTagNo() == 0) {
        this.versionPresent = true;
        this.version = ASN1Integer.getInstance((ASN1TaggedObject) seq.getObjectAt(0), true);
        index++;
      } else {
        this.version = V1;
      }
    } else {
      this.version = V1;
    }

    this.responderID = ResponderID.getInstance(seq.getObjectAt(index++));
    this.producedAt = (DERGeneralizedTime) seq.getObjectAt(index++);
    this.responses = (ASN1Sequence) seq.getObjectAt(index++);

    if (seq.size() > index) {
      this.responseExtensions =
          Extensions.getInstance((ASN1TaggedObject) seq.getObjectAt(index), true);
    }
  }
  /**
   * Fetches delta CRLs according to RFC 3280 section 5.2.4.
   *
   * @param currentDate The date for which the delta CRLs must be valid.
   * @param paramsPKIX The extended PKIX parameters.
   * @param completeCRL The complete CRL the delta CRL is for.
   * @return A <code>Set</code> of <code>X509CRL</code>s with delta CRLs.
   * @throws AnnotatedException if an exception occurs while picking the delta CRLs.
   */
  protected static Set getDeltaCRLs(
      Date currentDate, ExtendedPKIXParameters paramsPKIX, X509CRL completeCRL)
      throws AnnotatedException {

    X509CRLStoreSelector deltaSelect = new X509CRLStoreSelector();

    // 5.2.4 (a)
    try {
      deltaSelect.addIssuerName(
          CertPathValidatorUtilities.getIssuerPrincipal(completeCRL).getEncoded());
    } catch (IOException e) {
      throw new AnnotatedException("Cannot extract issuer from CRL.", e);
    }

    BigInteger completeCRLNumber = null;
    try {
      ASN1Primitive derObject =
          CertPathValidatorUtilities.getExtensionValue(completeCRL, CRL_NUMBER);
      if (derObject != null) {
        completeCRLNumber = ASN1Integer.getInstance(derObject).getPositiveValue();
      }
    } catch (Exception e) {
      throw new AnnotatedException("CRL number extension could not be extracted from CRL.", e);
    }

    // 5.2.4 (b)
    byte[] idp = null;
    try {
      idp = completeCRL.getExtensionValue(ISSUING_DISTRIBUTION_POINT);
    } catch (Exception e) {
      throw new AnnotatedException(
          "Issuing distribution point extension value could not be read.", e);
    }

    // 5.2.4 (d)

    deltaSelect.setMinCRLNumber(
        completeCRLNumber == null ? null : completeCRLNumber.add(BigInteger.valueOf(1)));

    deltaSelect.setIssuingDistributionPoint(idp);
    deltaSelect.setIssuingDistributionPointEnabled(true);

    // 5.2.4 (c)
    deltaSelect.setMaxBaseCRLNumber(completeCRLNumber);

    // find delta CRLs
    Set temp = CRL_UTIL.findCRLs(deltaSelect, paramsPKIX, currentDate);

    Set result = new HashSet();

    for (Iterator it = temp.iterator(); it.hasNext(); ) {
      X509CRL crl = (X509CRL) it.next();

      if (isDeltaCRL(crl)) {
        result.add(crl);
      }
    }

    return result;
  }
Exemplo n.º 5
0
  private SinglePubInfo(ASN1Sequence seq) {
    pubMethod = ASN1Integer.getInstance(seq.getObjectAt(0));

    if (seq.size() == 2) {
      pubLocation = GeneralName.getInstance(seq.getObjectAt(1));
    }
  }
Exemplo n.º 6
0
  public X9Curve(X9FieldID fieldID, ASN1Sequence seq) {
    fieldIdentifier = fieldID.getIdentifier();
    if (fieldIdentifier.equals(prime_field)) {
      BigInteger p = ((ASN1Integer) fieldID.getParameters()).getValue();
      X9FieldElement x9A = new X9FieldElement(p, (ASN1OctetString) seq.getObjectAt(0));
      X9FieldElement x9B = new X9FieldElement(p, (ASN1OctetString) seq.getObjectAt(1));
      curve = new ECCurve.Fp(p, x9A.getValue().toBigInteger(), x9B.getValue().toBigInteger());
    } else if (fieldIdentifier.equals(characteristic_two_field)) {
      // Characteristic two field
      ASN1Sequence parameters = ASN1Sequence.getInstance(fieldID.getParameters());
      int m = ((ASN1Integer) parameters.getObjectAt(0)).getValue().intValue();
      ASN1ObjectIdentifier representation = (ASN1ObjectIdentifier) parameters.getObjectAt(1);

      int k1 = 0;
      int k2 = 0;
      int k3 = 0;

      if (representation.equals(tpBasis)) {
        // Trinomial basis representation
        k1 = ASN1Integer.getInstance(parameters.getObjectAt(2)).getValue().intValue();
      } else if (representation.equals(ppBasis)) {
        // Pentanomial basis representation
        ASN1Sequence pentanomial = ASN1Sequence.getInstance(parameters.getObjectAt(2));
        k1 = ASN1Integer.getInstance(pentanomial.getObjectAt(0)).getValue().intValue();
        k2 = ASN1Integer.getInstance(pentanomial.getObjectAt(1)).getValue().intValue();
        k3 = ASN1Integer.getInstance(pentanomial.getObjectAt(2)).getValue().intValue();
      } else {
        throw new IllegalArgumentException("This type of EC basis is not implemented");
      }
      X9FieldElement x9A = new X9FieldElement(m, k1, k2, k3, (ASN1OctetString) seq.getObjectAt(0));
      X9FieldElement x9B = new X9FieldElement(m, k1, k2, k3, (ASN1OctetString) seq.getObjectAt(1));
      // TODO Is it possible to get the order (n) and cofactor(h) too?
      curve =
          new ECCurve.F2m(
              m, k1, k2, k3, x9A.getValue().toBigInteger(), x9B.getValue().toBigInteger());
    } else {
      throw new IllegalArgumentException("This type of ECCurve is not implemented");
    }

    if (seq.size() == 3) {
      seed = ((DERBitString) seq.getObjectAt(2)).getBytes();
    }
  }
  private PolicyConstraints(ASN1Sequence seq) {
    if (seq.size() > 2) {
      throw new IllegalArgumentException("sequence length > 2");
    }

    for (int i = 0; i < seq.size(); i++) {
      ASN1TaggedObject taggedObj = ASN1TaggedObject.getInstance(seq.getObjectAt(i));
      switch (taggedObj.getTagNo()) {
        case 0:
          requireExplicitPolicy =
              ASN1Integer.getInstance(taggedObj.getObject()).getValue().intValue();
          break;
        case 1:
          inhibitPolicyMapping =
              ASN1Integer.getInstance(taggedObj.getObject()).getValue().intValue();
          break;
        default:
          throw new IllegalArgumentException("wrong tag number");
      }
    }
  }
  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);
  }
Exemplo n.º 9
0
  private ErrorMsgContent(ASN1Sequence seq) {
    Enumeration en = seq.getObjects();

    pkiStatusInfo = PKIStatusInfo.getInstance(en.nextElement());

    while (en.hasMoreElements()) {
      Object o = en.nextElement();

      if (o instanceof ASN1Integer) {
        errorCode = ASN1Integer.getInstance(o);
      } else {
        errorDetails = PKIFreeText.getInstance(o);
      }
    }
  }
Exemplo n.º 10
0
  /**
   * Produce an object suitable for an ASN1OutputStream.
   *
   * <pre>
   * ResponseData ::= SEQUENCE {
   *     version              [0] EXPLICIT Version DEFAULT v1,
   *     responderID              ResponderID,
   *     producedAt               GeneralizedTime,
   *     responses                SEQUENCE OF SingleResponse,
   *     responseExtensions   [1] EXPLICIT Extensions OPTIONAL }
   * </pre>
   */
  public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector();

    if (versionPresent || !version.equals(V1)) {
      v.add(new DERTaggedObject(true, 0, version));
    }

    v.add(responderID);
    v.add(producedAt);
    v.add(responses);
    if (responseExtensions != null) {
      v.add(new DERTaggedObject(true, 1, responseExtensions));
    }

    return new DERSequence(v);
  }
Exemplo n.º 11
0
  private PKIStatusInfo(ASN1Sequence seq) {
    this.status = ASN1Integer.getInstance(seq.getObjectAt(0));

    this.statusString = null;
    this.failInfo = null;

    if (seq.size() > 2) {
      this.statusString = PKIFreeText.getInstance(seq.getObjectAt(1));
      this.failInfo = DERBitString.getInstance(seq.getObjectAt(2));
    } else if (seq.size() > 1) {
      Object obj = seq.getObjectAt(1);
      if (obj instanceof DERBitString) {
        this.failInfo = DERBitString.getInstance(obj);
      } else {
        this.statusString = PKIFreeText.getInstance(obj);
      }
    }
  }
  /**
   * Create a public key from the passed in SubjectPublicKeyInfo
   *
   * @param keyInfo the SubjectPublicKeyInfo containing the key data
   * @return the appropriate key parameter
   * @throws IOException on an error decoding the key
   */
  public static AsymmetricKeyParameter createKey(SubjectPublicKeyInfo keyInfo) throws IOException {
    AlgorithmIdentifier algId = keyInfo.getAlgorithm();

    if (algId.getAlgorithm().equals(PKCSObjectIdentifiers.rsaEncryption)
        || algId.getAlgorithm().equals(X509ObjectIdentifiers.id_ea_rsa)) {
      RSAPublicKey pubKey = RSAPublicKey.getInstance(keyInfo.parsePublicKey());

      return new RSAKeyParameters(false, pubKey.getModulus(), pubKey.getPublicExponent());
    } else if (algId.getAlgorithm().equals(X9ObjectIdentifiers.dhpublicnumber)) {
      DHPublicKey dhPublicKey = DHPublicKey.getInstance(keyInfo.parsePublicKey());

      BigInteger y = dhPublicKey.getY().getValue();

      DHDomainParameters dhParams = DHDomainParameters.getInstance(algId.getParameters());

      BigInteger p = dhParams.getP().getValue();
      BigInteger g = dhParams.getG().getValue();
      BigInteger q = dhParams.getQ().getValue();

      BigInteger j = null;
      if (dhParams.getJ() != null) {
        j = dhParams.getJ().getValue();
      }

      DHValidationParameters validation = null;
      DHValidationParms dhValidationParms = dhParams.getValidationParms();
      if (dhValidationParms != null) {
        byte[] seed = dhValidationParms.getSeed().getBytes();
        BigInteger pgenCounter = dhValidationParms.getPgenCounter().getValue();

        // TODO Check pgenCounter size?

        validation = new DHValidationParameters(seed, pgenCounter.intValue());
      }

      return new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation));
    } else if (algId.getAlgorithm().equals(PKCSObjectIdentifiers.dhKeyAgreement)) {
      DHParameter params = DHParameter.getInstance(algId.getParameters());
      ASN1Integer derY = (ASN1Integer) keyInfo.parsePublicKey();

      BigInteger lVal = params.getL();
      int l = lVal == null ? 0 : lVal.intValue();
      DHParameters dhParams = new DHParameters(params.getP(), params.getG(), null, l);

      return new DHPublicKeyParameters(derY.getValue(), dhParams);
    }
    // BEGIN android-removed
    // else if (algId.getAlgorithm().equals(OIWObjectIdentifiers.elGamalAlgorithm))
    // {
    //     ElGamalParameter params = new ElGamalParameter((ASN1Sequence)algId.getParameters());
    //     ASN1Integer derY = (ASN1Integer)keyInfo.parsePublicKey();
    //
    //     return new ElGamalPublicKeyParameters(derY.getValue(), new ElGamalParameters(
    //         params.getP(), params.getG()));
    // }
    // END android-removed
    else if (algId.getAlgorithm().equals(X9ObjectIdentifiers.id_dsa)
        || algId.getAlgorithm().equals(OIWObjectIdentifiers.dsaWithSHA1)) {
      ASN1Integer derY = (ASN1Integer) keyInfo.parsePublicKey();
      ASN1Encodable de = algId.getParameters();

      DSAParameters parameters = null;
      if (de != null) {
        DSAParameter params = DSAParameter.getInstance(de.toASN1Primitive());
        parameters = new DSAParameters(params.getP(), params.getQ(), params.getG());
      }

      return new DSAPublicKeyParameters(derY.getValue(), parameters);
    } else if (algId.getAlgorithm().equals(X9ObjectIdentifiers.id_ecPublicKey)) {
      X962Parameters params = X962Parameters.getInstance(algId.getParameters());

      X9ECParameters x9;
      if (params.isNamedCurve()) {
        ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) params.getParameters();
        x9 = ECNamedCurveTable.getByOID(oid);
      } else {
        x9 = X9ECParameters.getInstance(params.getParameters());
      }

      ASN1OctetString key = new DEROctetString(keyInfo.getPublicKeyData().getBytes());
      X9ECPoint derQ = new X9ECPoint(x9.getCurve(), key);

      // TODO We lose any named parameters here

      ECDomainParameters dParams =
          new ECDomainParameters(x9.getCurve(), x9.getG(), x9.getN(), x9.getH(), x9.getSeed());

      return new ECPublicKeyParameters(derQ.getPoint(), dParams);
    } else {
      throw new RuntimeException("algorithm identifier in key not recognised");
    }
  }
Exemplo n.º 13
0
 public BigInteger getStatus() {
   return status.getValue();
 }
Exemplo n.º 14
0
 public PKIStatusInfo(PKIStatus status, PKIFreeText statusString, PKIFailureInfo failInfo) {
   this.status = ASN1Integer.getInstance(status.toASN1Primitive());
   ;
   this.statusString = statusString;
   this.failInfo = failInfo;
 }
Exemplo n.º 15
0
 /**
  * @param status
  * @param statusString
  */
 public PKIStatusInfo(PKIStatus status, PKIFreeText statusString) {
   this.status = ASN1Integer.getInstance(status.toASN1Primitive());
   this.statusString = statusString;
 }
Exemplo n.º 16
0
 /** @param status */
 public PKIStatusInfo(PKIStatus status) {
   this.status = ASN1Integer.getInstance(status.toASN1Primitive());
 }
Exemplo n.º 17
0
  /**
   * 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();
  }
Exemplo n.º 18
0
 public BigInteger getAmount() {
   return amount.getValue();
 }
Exemplo n.º 19
0
  @Override
  protected Object doExecute() throws Exception {
    Set<String> caNames = caClient.getCaNames();
    if (isEmpty(caNames)) {
      throw new IllegalCmdParamException("no CA is configured");
    }

    if (caName != null && !caNames.contains(caName)) {
      throw new IllegalCmdParamException(
          "CA " + caName + " is not within the configured CAs " + caNames);
    }

    if (caName == null) {
      if (caNames.size() == 1) {
        caName = caNames.iterator().next();
      } else {
        throw new IllegalCmdParamException(
            "no caname is specified, one of " + caNames + " is required");
      }
    }

    X509CRL crl = null;
    try {
      crl = retrieveCRL(caName);
    } catch (PKIErrorException e) {
      throw new CmdFailure("received no CRL from server: " + e.getMessage());
    }

    if (crl == null) {
      throw new CmdFailure("received no CRL from server");
    }

    saveVerbose("saved CRL to file", new File(outFile), crl.getEncoded());

    if (withBaseCRL.booleanValue()) {
      byte[] octetString = crl.getExtensionValue(Extension.deltaCRLIndicator.getId());
      if (octetString != null) {
        if (baseCRLOut == null) {
          baseCRLOut = outFile + "-baseCRL";
        }

        byte[] extnValue = DEROctetString.getInstance(octetString).getOctets();
        BigInteger baseCrlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue();

        RequestResponseDebug debug = getRequestResponseDebug();
        try {
          crl = caClient.downloadCRL(caName, baseCrlNumber, debug);
        } catch (PKIErrorException e) {
          throw new CmdFailure("received no baseCRL from server: " + e.getMessage());
        } finally {
          saveRequestResponse(debug);
        }

        if (crl == null) {
          throw new CmdFailure("received no baseCRL from server");
        } else {
          saveVerbose("saved baseCRL to file", new File(baseCRLOut), crl.getEncoded());
        }
      }
    }

    return null;
  } // method doExecute
Exemplo n.º 20
0
 public Integer getParameterId() {
   if (parameterId == null) return null; // ID nicht vorhanden
   else return parameterId.getValue().intValue();
 }
Exemplo n.º 21
0
 public int getVersion() {
   return version.getValue().intValue();
 }
Exemplo n.º 22
0
 public BigInteger getExponent() {
   return exponent.getValue();
 }