コード例 #1
0
  private static String csr() {
    try {
      KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
      keyGen.initialize(2048);
      KeyPair keyPair = keyGen.generateKeyPair();
      X500Principal subject =
          new X500Principal(
              "CN = edea87b4-034d-48dc-94dd-e7cdcfdde370/10562468, OU = fgdfgretertgdfg, O = VW, L = US");
      ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").build(keyPair.getPrivate());
      PKCS10CertificationRequestBuilder builder =
          new JcaPKCS10CertificationRequestBuilder(subject, keyPair.getPublic());
      PKCS10CertificationRequest csr = builder.build(signer);

      String type = "CERTIFICATE REQUEST";
      PemObject pem = new PemObject(type, csr.getEncoded());
      StringWriter str = new StringWriter();
      PEMWriter pemWriter = new PEMWriter(str);
      pemWriter.writeObject(pem);
      pemWriter.close();
      str.close();
      Log.d("Test", "" + str);
      return Base64Util.getStringAsBase64(str.toString());
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (OperatorCreationException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return "";
  }
コード例 #2
0
 @Override
 public ContentVerifierProvider getContentVerifierProvider(final PublicKey publicKey)
     throws InvalidKeyException {
   try {
     return KeyUtil.getContentVerifierProvider(publicKey);
   } catch (OperatorCreationException e) {
     throw new InvalidKeyException(e.getMessage(), e);
   }
 }
コード例 #3
0
  /**
   * Generate a certificate signing request (PKCS#10).
   *
   * @param info A PKCS10CertReqInfo
   * @param privateKey Private key for signing the request
   * @param signatureProvider Name of provider to sign with
   * @param publicKey Public key to include in the request
   * @param explicitEccParameters True if the EC domain parameters should be included (ie. not a
   *     named curve)
   * @return the certificate request data
   */
  public static ICertReqData genCertificateRequest(
      ISignerCertReqInfo info,
      final PrivateKey privateKey,
      final String signatureProvider,
      PublicKey publicKey,
      final boolean explicitEccParameters)
      throws IllegalArgumentException {
    LOG.debug(">genCertificateRequest");
    final Base64SignerCertReqData retval;
    if (info instanceof PKCS10CertReqInfo) {
      PKCS10CertReqInfo reqInfo = (PKCS10CertReqInfo) info;
      PKCS10CertificationRequest pkcs10;

      if (LOG.isDebugEnabled()) {
        LOG.debug("signatureAlgorithm: " + reqInfo.getSignatureAlgorithm());
        LOG.debug("subjectDN: " + reqInfo.getSubjectDN());
        LOG.debug("explicitEccParameters: " + explicitEccParameters);
      }

      try {
        // Handle ECDSA key with explicit parameters
        if (explicitEccParameters && publicKey.getAlgorithm().contains("EC")) {
          publicKey = ECKeyUtil.publicToExplicitParameters(publicKey, "BC");
        }

        if (LOG.isDebugEnabled()) {
          LOG.debug("Public key SHA1: " + createKeyHash(publicKey));
          LOG.debug("Public key SHA256: " + KeyUsageCounterHash.create(publicKey));
        }

        // Generate request
        final JcaPKCS10CertificationRequestBuilder builder =
            new JcaPKCS10CertificationRequestBuilder(
                new X500Name(CertTools.stringToBCDNString(reqInfo.getSubjectDN())), publicKey);
        final ContentSigner contentSigner =
            new JcaContentSignerBuilder(reqInfo.getSignatureAlgorithm())
                .setProvider(signatureProvider)
                .build(privateKey);
        pkcs10 = builder.build(contentSigner);
        retval = new Base64SignerCertReqData(Base64.encode(pkcs10.getEncoded()));
      } catch (IOException e) {
        throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
      } catch (OperatorCreationException e) {
        throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
      } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
      } catch (NoSuchProviderException e) {
        throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
      }
      LOG.debug("<genCertificateRequest");
      return retval;
    } else {
      throw new IllegalArgumentException(
          "Unsupported certificate request info type: " + info.getClass().getName());
    }
  }
コード例 #4
0
  public boolean verify(DigestCalculatorProvider calculatorProvider) throws CMSException {
    try {
      ContentInfo content = digestedData.getEncapContentInfo();
      DigestCalculator calc = calculatorProvider.get(digestedData.getDigestAlgorithm());

      OutputStream dOut = calc.getOutputStream();

      dOut.write(((ASN1OctetString) content.getContent()).getOctets());

      return Arrays.areEqual(digestedData.getDigest(), calc.getDigest());
    } catch (OperatorCreationException e) {
      throw new CMSException("unable to create digest calculator: " + e.getMessage(), e);
    } catch (IOException e) {
      throw new CMSException("unable process content: " + e.getMessage(), e);
    }
  }
コード例 #5
0
ファイル: TimestampToken.java プロジェクト: viavansi/dss
  private TimestampValidation validateTimestampToken(
      final TimeStampToken timeStampToken, final CertificateToken issuerToken) {

    TimestampValidity timestampValidity;
    try {

      final JcaSimpleSignerInfoVerifierBuilder verifierBuilder =
          new JcaSimpleSignerInfoVerifierBuilder();
      final X509Certificate x509Certificate = issuerToken.getCertificate();
      final SignerInformationVerifier verifier = verifierBuilder.build(x509Certificate);
      timeStampToken.validate(verifier);
      timestampValidity = TimestampValidity.VALID;
    } catch (IllegalArgumentException e) {
      if (logger.isDebugEnabled()) {
        logger.debug("No signing certificate for timestamp token: ", e);
      } else {
        logger.info("No signing certificate for timestamp token: ", e.getMessage());
      }
      timestampValidity = TimestampValidity.NO_SIGNING_CERTIFICATE;
    } catch (TSPValidationException e) {
      if (logger.isDebugEnabled()) {
        logger.debug("No valid signature for timestamp token: ", e);
      } else {
        logger.info("No valid signature for timestamp token: " + e.getMessage());
      }
      timestampValidity = TimestampValidity.NOT_VALID_SIGNATURE;
    } catch (TSPException e) {
      if (logger.isDebugEnabled()) {
        logger.debug("No valid structure for timestamp token: ", e);
      } else {
        logger.info("No valid structure for timestamp token: " + e.getMessage());
      }
      timestampValidity = TimestampValidity.NOT_VALID_STRUCTURE;
    } catch (OperatorCreationException e) {
      if (logger.isDebugEnabled()) {
        logger.debug("No valid structure for timestamp token: ", e);
      } else {
        logger.info("No valid structure for timestamp token: " + e.getMessage());
      }
      timestampValidity = TimestampValidity.NOT_VALID_STRUCTURE;
    }
    final TimestampValidation timestampValidation = new TimestampValidation(timestampValidity);
    return timestampValidation;
  }
コード例 #6
0
  public boolean isVerified(
      X509CertificateHolder certHolder, DigestCalculatorProvider digesterProvider)
      throws CMPException {
    AlgorithmIdentifier digAlg =
        digestAlgFinder.find(certHolder.toASN1Structure().getSignatureAlgorithm());
    if (digAlg == null) {
      throw new CMPException("cannot find algorithm for digest from signature");
    }

    DigestCalculator digester;

    try {
      digester = digesterProvider.get(digAlg);
    } catch (OperatorCreationException e) {
      throw new CMPException("unable to create digester: " + e.getMessage(), e);
    }

    CMPUtil.derEncodeToStream(certHolder.toASN1Structure(), digester.getOutputStream());

    return Arrays.areEqual(certStatus.getCertHash().getOctets(), digester.getDigest());
  }
コード例 #7
0
  private boolean doVerify(SignerInformationVerifier verifier) throws CMSException {
    String digestName = CMSSignedHelper.INSTANCE.getDigestAlgName(this.getDigestAlgOID());
    String encName = CMSSignedHelper.INSTANCE.getEncryptionAlgName(this.getEncryptionAlgOID());
    String signatureName = digestName + "with" + encName;

    try {
      if (digestCalculator != null) {
        resultDigest = digestCalculator.getDigest();
      } else {
        DigestCalculator calc = verifier.getDigestCalculator(this.getDigestAlgorithmID());
        if (content != null) {
          OutputStream digOut = calc.getOutputStream();

          content.write(digOut);

          digOut.close();
        } else if (signedAttributeSet == null) {
          // TODO Get rid of this exception and just treat content==null as empty not missing?
          throw new CMSException("data not encapsulated in signature - use detached constructor.");
        }

        resultDigest = calc.getDigest();
      }
    } catch (IOException e) {
      throw new CMSException("can't process mime object to create signature.", e);
    } catch (NoSuchAlgorithmException e) {
      throw new CMSException("can't find algorithm: " + e.getMessage(), e);
    } catch (OperatorCreationException e) {
      throw new CMSException("can't create digest calculator: " + e.getMessage(), e);
    }

    // RFC 3852 11.1 Check the content-type attribute is correct
    {
      DERObject validContentType =
          getSingleValuedSignedAttribute(CMSAttributes.contentType, "content-type");
      if (validContentType == null) {
        if (!isCounterSignature && signedAttributeSet != null) {
          throw new CMSException(
              "The content-type attribute type MUST be present whenever signed attributes are present in signed-data");
        }
      } else {
        if (isCounterSignature) {
          throw new CMSException(
              "[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute");
        }

        if (!(validContentType instanceof DERObjectIdentifier)) {
          throw new CMSException(
              "content-type attribute value not of ASN.1 type 'OBJECT IDENTIFIER'");
        }

        DERObjectIdentifier signedContentType = (DERObjectIdentifier) validContentType;

        if (!signedContentType.equals(contentType)) {
          throw new CMSException("content-type attribute value does not match eContentType");
        }
      }
    }

    // RFC 3852 11.2 Check the message-digest attribute is correct
    {
      DERObject validMessageDigest =
          getSingleValuedSignedAttribute(CMSAttributes.messageDigest, "message-digest");
      if (validMessageDigest == null) {
        if (signedAttributeSet != null) {
          throw new CMSException(
              "the message-digest signed attribute type MUST be present when there are any signed attributes present");
        }
      } else {
        if (!(validMessageDigest instanceof ASN1OctetString)) {
          throw new CMSException("message-digest attribute value not of ASN.1 type 'OCTET STRING'");
        }

        ASN1OctetString signedMessageDigest = (ASN1OctetString) validMessageDigest;

        if (!Arrays.constantTimeAreEqual(resultDigest, signedMessageDigest.getOctets())) {
          throw new CMSSignerDigestMismatchException(
              "message-digest attribute value does not match calculated value");
        }
      }
    }

    // RFC 3852 11.4 Validate countersignature attribute(s)
    {
      AttributeTable signedAttrTable = this.getSignedAttributes();
      if (signedAttrTable != null
          && signedAttrTable.getAll(CMSAttributes.counterSignature).size() > 0) {
        throw new CMSException("A countersignature attribute MUST NOT be a signed attribute");
      }

      AttributeTable unsignedAttrTable = this.getUnsignedAttributes();
      if (unsignedAttrTable != null) {
        ASN1EncodableVector csAttrs = unsignedAttrTable.getAll(CMSAttributes.counterSignature);
        for (int i = 0; i < csAttrs.size(); ++i) {
          Attribute csAttr = (Attribute) csAttrs.get(i);
          if (csAttr.getAttrValues().size() < 1) {
            throw new CMSException(
                "A countersignature attribute MUST contain at least one AttributeValue");
          }

          // Note: We don't recursively validate the countersignature value
        }
      }
    }

    try {
      ContentVerifier contentVerifier =
          verifier.getContentVerifier(sigAlgFinder.find(signatureName));
      OutputStream sigOut = contentVerifier.getOutputStream();

      if (signedAttributeSet == null) {
        if (digestCalculator != null) {
          if (contentVerifier instanceof RawContentVerifier) {
            RawContentVerifier rawVerifier = (RawContentVerifier) contentVerifier;

            if (encName.equals("RSA")) {
              DigestInfo digInfo = new DigestInfo(digestAlgorithm, resultDigest);

              return rawVerifier.verify(digInfo.getDEREncoded(), this.getSignature());
            }

            return rawVerifier.verify(resultDigest, this.getSignature());
          }

          throw new CMSException("verifier unable to process raw signature");
        } else if (content != null) {
          // TODO Use raw signature of the hash value instead
          content.write(sigOut);
        }
      } else {
        sigOut.write(this.getEncodedSignedAttributes());
      }

      sigOut.close();

      return contentVerifier.verify(this.getSignature());
    } catch (IOException e) {
      throw new CMSException("can't process mime object to create signature.", e);
    } catch (OperatorCreationException e) {
      throw new CMSException("can't create content verifier: " + e.getMessage(), e);
    }
  }