org.bouncycastle.asn1.cms.ContentInfo Java Examples

The following examples show how to use org.bouncycastle.asn1.cms.ContentInfo. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Client.java    From xipki with Apache License 2.0 6 votes vote down vote up
private ContentInfo encryptThenSign(PkiMessage request, PrivateKey identityKey,
    X509Cert identityCert) throws ScepClientException {
  HashAlgo hashAlgo = caCaps.mostSecureHashAlgo();
  String signatureAlgorithm = ScepUtil.getSignatureAlgorithm(identityKey, hashAlgo);
  ASN1ObjectIdentifier encAlgId;
  if (caCaps.containsCapability(CaCapability.AES)) {
    encAlgId = CMSAlgorithm.AES128_CBC;
  } else if (caCaps.containsCapability(CaCapability.DES3)) {
    encAlgId = CMSAlgorithm.DES_EDE3_CBC;
  } else if (useInsecureAlgorithms) {
    encAlgId = CMSAlgorithm.DES_CBC;
  } else { // no support of DES
    throw new ScepClientException("DES will not be supported by this client");
  }

  try {
    return request.encode(identityKey, signatureAlgorithm, identityCert,
        new X509Cert[]{identityCert}, authorityCertStore.getEncryptionCert(), encAlgId);
  } catch (MessageEncodingException ex) {
    throw new ScepClientException(ex);
  }
}
 
Example #2
Source File: BouncyCastleCrypto.java    From tutorials with MIT License 6 votes vote down vote up
public static boolean verifSignData(final byte[] signedData) throws CMSException, IOException, OperatorCreationException, CertificateException {
    ByteArrayInputStream bIn = new ByteArrayInputStream(signedData);
    ASN1InputStream aIn = new ASN1InputStream(bIn);
    CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject()));
    aIn.close();
    bIn.close();
    Store certs = s.getCertificates();
    SignerInformationStore signers = s.getSignerInfos();
    Collection<SignerInformation> c = signers.getSigners();
    SignerInformation signer = c.iterator().next();
    Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID());
    Iterator<X509CertificateHolder> certIt = certCollection.iterator();
    X509CertificateHolder certHolder = certIt.next();
    boolean verifResult = signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certHolder));
    if (!verifResult) {
        return false;
    }
    return true;
}
 
Example #3
Source File: ScepResponder.java    From xipki with Apache License 2.0 6 votes vote down vote up
private ContentInfo encodeResponse(PkiMessage response, DecodedPkiMessage request)
    throws OperationException {
  Args.notNull(response, "response");
  Args.notNull(request, "request");

  String signatureAlgorithm = getSignatureAlgorithm(responderKey, request.getDigestAlgorithm());
  ContentInfo ci;
  try {
    X509Cert[] cmsCertSet = control.isIncludeSignerCert()
        ? new X509Cert[]{responderCert} : null;

    ci = response.encode(responderKey, signatureAlgorithm, responderCert, cmsCertSet,
        request.getSignatureCert(), request.getContentEncryptionAlgorithm());
  } catch (MessageEncodingException ex) {
    LogUtil.error(LOG, ex, "could not encode response");
    throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
  }
  return ci;
}
 
Example #4
Source File: ScepResponder.java    From xipki with Apache License 2.0 6 votes vote down vote up
public ContentInfo servicePkiOperation(CMSSignedData requestContent, String certprofileName,
    String msgId, AuditEvent event) throws MessageDecodingException, OperationException {
  if (!isOnService()) {
    LOG.warn("SCEP {} is not active", caIdent.getName());
    throw new OperationException(ErrorCode.SYSTEM_UNAVAILABLE);
  }

  DecodedPkiMessage req = DecodedPkiMessage.decode(requestContent, envelopedDataDecryptor, null);

  PkiMessage rep = servicePkiOperation0(requestContent, req, certprofileName, msgId, event);
  audit(event, CaAuditConstants.Scep.NAME_pki_status, rep.getPkiStatus().toString());
  if (rep.getPkiStatus() == PkiStatus.FAILURE) {
    event.setStatus(AuditStatus.FAILED);
  }
  if (rep.getFailInfo() != null) {
    audit(event, CaAuditConstants.Scep.NAME_fail_info, rep.getFailInfo().toString());
  }
  return encodeResponse(rep, req);
}
 
Example #5
Source File: ScepResponder.java    From xipki with Apache License 2.0 6 votes vote down vote up
private ContentInfo createSignedData(X509Cert cert) throws CaException {
  CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();

  CMSSignedData cmsSigneddata;
  try {
    cmsSignedDataGen.addCertificate(cert.toBcCert());
    if (control.isSendCaCert()) {
      cmsSignedDataGen.addCertificate(caEmulator.getCaCert().toBcCert());
    }

    cmsSigneddata = cmsSignedDataGen.generate(new CMSAbsentContent());
  } catch (CMSException ex) {
    throw new CaException(ex);
  }

  return cmsSigneddata.toASN1Structure();
}
 
Example #6
Source File: Client.java    From xipki with Apache License 2.0 6 votes vote down vote up
private EnrolmentResponse enroll(MessageType messageType, CertificationRequest csr,
    PrivateKey identityKey, X509Cert identityCert) throws ScepClientException {
  TransactionId tid;
  try {
    tid = TransactionId.sha1TransactionId(
        csr.getCertificationRequestInfo().getSubjectPublicKeyInfo());
  } catch (InvalidKeySpecException ex) {
    throw new ScepClientException(ex.getMessage(), ex);
  }
  PkiMessage pkiMessage = new PkiMessage(tid, messageType);

  pkiMessage.setMessageData(csr);
  ContentInfo envRequest = encryptThenSign(pkiMessage, identityKey, identityCert);
  ScepHttpResponse httpResp = httpSend(Operation.PKIOperation, envRequest);

  CMSSignedData cmsSignedData = parsePkiMessage(httpResp.getContentBytes());
  DecodedPkiMessage response = decode(cmsSignedData, identityKey, identityCert);
  assertSameNonce(pkiMessage, response);
  return new EnrolmentResponse(response);
}
 
Example #7
Source File: Client.java    From xipki with Apache License 2.0 6 votes vote down vote up
public EnrolmentResponse scepCertPoll(PrivateKey identityKey, X509Cert identityCert,
    TransactionId transactionId, X500Name issuer, X500Name subject) throws ScepClientException {
  Args.notNull(identityKey, "identityKey");
  Args.notNull(identityCert, "identityCert");
  Args.notNull(issuer, "issuer");
  Args.notNull(transactionId, "transactionId");

  initIfNotInited();

  PkiMessage pkiMessage = new PkiMessage(transactionId, MessageType.CertPoll);

  IssuerAndSubject is = new IssuerAndSubject(issuer, subject);
  pkiMessage.setMessageData(is);
  ContentInfo envRequest = encryptThenSign(pkiMessage, identityKey, identityCert);
  ScepHttpResponse httpResp = httpSend(Operation.PKIOperation, envRequest);
  CMSSignedData cmsSignedData = parsePkiMessage(httpResp.getContentBytes());
  DecodedPkiMessage response = decode(cmsSignedData, identityKey, identityCert);
  assertSameNonce(pkiMessage, response);
  return new EnrolmentResponse(response);
}
 
Example #8
Source File: Client.java    From xipki with Apache License 2.0 5 votes vote down vote up
public List<X509Cert> scepGetCert(PrivateKey identityKey, X509Cert identityCert,
    X500Name issuer, BigInteger serialNumber) throws ScepClientException {
  Args.notNull(identityKey, "identityKey");
  Args.notNull(identityCert, "identityCert");
  Args.notNull(issuer, "issuer");
  Args.notNull(serialNumber, "serialNumber");

  initIfNotInited();

  PkiMessage request = new PkiMessage(TransactionId.randomTransactionId(), MessageType.GetCert);

  IssuerAndSerialNumber isn = new IssuerAndSerialNumber(issuer, serialNumber);
  request.setMessageData(isn);
  ContentInfo envRequest = encryptThenSign(request, identityKey, identityCert);
  ScepHttpResponse httpResp = httpSend(Operation.PKIOperation, envRequest);

  CMSSignedData cmsSignedData = parsePkiMessage(httpResp.getContentBytes());
  DecodedPkiMessage response = decode(cmsSignedData, identityKey, identityCert);
  if (response.getPkiStatus() != PkiStatus.SUCCESS) {
    throw new ScepClientException("server returned " + response.getPkiStatus());
  }

  ContentInfo messageData = ContentInfo.getInstance(response.getMessageData());
  try {
    return ScepUtil.getCertsFromSignedData(SignedData.getInstance(messageData.getContent()));
  } catch (CertificateException ex) {
    throw new ScepClientException(ex.getMessage(), ex);
  }
}
 
Example #9
Source File: Client.java    From xipki with Apache License 2.0 5 votes vote down vote up
public X509CRLHolder scepGetCrl(PrivateKey identityKey, X509Cert identityCert,
    X500Name issuer, BigInteger serialNumber) throws ScepClientException {
  Args.notNull(identityKey, "identityKey");
  Args.notNull(identityCert, "identityCert");
  Args.notNull(issuer, "issuer");
  Args.notNull(serialNumber, "serialNumber");

  initIfNotInited();

  PkiMessage pkiMessage = new PkiMessage(TransactionId.randomTransactionId(), MessageType.GetCRL);
  IssuerAndSerialNumber isn = new IssuerAndSerialNumber(issuer, serialNumber);
  pkiMessage.setMessageData(isn);
  ContentInfo request = encryptThenSign(pkiMessage, identityKey, identityCert);
  ScepHttpResponse httpResp = httpSend(Operation.PKIOperation, request);
  CMSSignedData cmsSignedData = parsePkiMessage(httpResp.getContentBytes());
  PkiMessage response = decode(cmsSignedData, identityKey, identityCert);
  if (response.getPkiStatus() != PkiStatus.SUCCESS) {
    throw new ScepClientException("server returned " + response.getPkiStatus());
  }

  ContentInfo messageData = ContentInfo.getInstance(response.getMessageData());

  try {
    return ScepUtil.getCrlFromPkiMessage(SignedData.getInstance(messageData.getContent()));
  } catch (CRLException ex) {
    throw new ScepClientException(ex.getMessage(), ex);
  }
}
 
Example #10
Source File: PdfPublicKeySecurityHandler.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
private ASN1Primitive 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);
    ASN1Primitive 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 ASN1ObjectIdentifier(s), derobject);
    EncryptedContentInfo encryptedcontentinfo = 
        new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring);
    EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, (org.bouncycastle.asn1.ASN1Set) null);
    ContentInfo contentinfo = 
        new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
    return contentinfo.toASN1Primitive();        
}
 
Example #11
Source File: EnrolmentResponse.java    From xipki with Apache License 2.0 5 votes vote down vote up
public EnrolmentResponse(PkiMessage pkcsRep) throws ScepClientException {
  Args.notNull(pkcsRep, "pkcsRep");
  MessageType messageType = pkcsRep.getMessageType();
  if (MessageType.CertRep != messageType) {
    throw new ScepClientException("messageType must not be other than CertRep: " + messageType);
  }
  this.pkcsRep = pkcsRep;

  if (PkiStatus.SUCCESS != pkcsRep.getPkiStatus()) {
    return;
  }

  ASN1Encodable messageData = pkcsRep.getMessageData();
  if (!(messageData instanceof ContentInfo)) {
    throw new ScepClientException("pkcsRep is not a ContentInfo");
  }

  ContentInfo ci = (ContentInfo) messageData;
  SignedData sd = SignedData.getInstance(ci.getContent());
  ASN1Set asn1Certs = sd.getCertificates();
  if (asn1Certs == null || asn1Certs.size() == 0) {
    throw new ScepClientException("no certificate is embedded in pkcsRep");
  }

  try {
    this.certificates = Collections.unmodifiableList(ScepUtil.getCertsFromSignedData(sd));
  } catch (CertificateException ex) {
    throw new ScepClientException(ex.getMessage(), ex);
  }
}
 
Example #12
Source File: ScepResponder.java    From xipki with Apache License 2.0 5 votes vote down vote up
public ContentInfo servicePkiOperation(CMSSignedData requestContent, AuditEvent event)
    throws MessageDecodingException, CaException {
  Args.notNull(requestContent, "requestContent");
  PrivateKey recipientKey = (raEmulator != null) ? raEmulator.getRaKey() : caEmulator.getCaKey();
  X509Cert recipientCert =
      (raEmulator != null) ? raEmulator.getRaCert() : caEmulator.getCaCert();

  EnvelopedDataDecryptorInstance decInstance =
      new EnvelopedDataDecryptorInstance(recipientCert, recipientKey);
  EnvelopedDataDecryptor recipient = new EnvelopedDataDecryptor(decInstance);

  DecodedPkiMessage req = DecodedPkiMessage.decode(requestContent, recipient, null);

  PkiMessage rep = servicePkiOperation0(req, event);
  event.putEventData(AuditEvent.NAME_pkiStatus, rep.getPkiStatus());
  if (rep.getPkiStatus() == PkiStatus.FAILURE) {
    event.setLevel(AuditLevel.ERROR);
  }

  if (rep.getFailInfo() != null) {
    event.putEventData(AuditEvent.NAME_failInfo, rep.getFailInfo());
  }

  String signatureAlgorithm = ScepUtil.getSignatureAlgorithm(getSigningKey(),
      HashAlgo.getInstance(req.getDigestAlgorithm()));

  try {
    X509Cert jceSignerCert = getSigningCert();
    X509Cert[] certs = control.isSendSignerCert()
        ? new X509Cert[]{jceSignerCert} : null;

    return rep.encode(getSigningKey(), signatureAlgorithm, jceSignerCert, certs,
        req.getSignatureCert(), req.getContentEncryptionAlgorithm());
  } catch (Exception ex) {
    throw new CaException(ex);
  }
}
 
Example #13
Source File: ScepResponder.java    From xipki with Apache License 2.0 5 votes vote down vote up
public ContentInfo encode(NextCaMessage nextCaMsg) throws CaException {
  Args.notNull(nextCaMsg, "nextCaMsg");
  try {
    X509Cert jceSignerCert = getSigningCert();
    X509Cert[] certs = control.isSendSignerCert()
        ? new X509Cert[]{jceSignerCert} : null;
    return nextCaMsg.encode(getSigningKey(), jceSignerCert, certs);
  } catch (Exception ex) {
    throw new CaException(ex);
  }
}
 
Example #14
Source File: ScepResponder.java    From xipki with Apache License 2.0 5 votes vote down vote up
private ContentInfo createSignedData(CertificateList crl) throws CaException {
  CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();
  cmsSignedDataGen.addCRL(new X509CRLHolder(crl));

  CMSSignedData cmsSigneddata;
  try {
    cmsSigneddata = cmsSignedDataGen.generate(new CMSAbsentContent());
  } catch (CMSException ex) {
    throw new CaException(ex.getMessage(), ex);
  }

  return cmsSigneddata.toASN1Structure();
}
 
Example #15
Source File: PkiMessage.java    From xipki with Apache License 2.0 5 votes vote down vote up
public ContentInfo encode(PrivateKey signerKey, String signatureAlgorithm, X509Cert signerCert,
    X509Cert[] signerCertSet, X509Cert recipientCert, ASN1ObjectIdentifier encAlgId)
    throws MessageEncodingException {
  Args.notNull(signerKey, "signerKey");
  ContentSigner signer;
  try {
    signer = new JcaContentSignerBuilder(signatureAlgorithm).build(signerKey);
  } catch (OperatorCreationException ex) {
    throw new MessageEncodingException(ex);
  }
  return encode(signer, signerCert, signerCertSet, recipientCert, encAlgId);
}
 
Example #16
Source File: CAdESTimestampDataBuilder.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private byte[] getContentInfoBytes(final SignedData signedData) {
	final ContentInfo content = signedData.getEncapContentInfo();
	byte[] contentInfoBytes;
	if (content.getContent() instanceof BEROctetString) {
		contentInfoBytes = DSSASN1Utils.getBEREncoded(content);
	} else {
		contentInfoBytes = DSSASN1Utils.getDEREncoded(content);
	}
	if (LOG.isTraceEnabled()) {
		LOG.trace("Content Info: {}", DSSUtils.toHex(contentInfoBytes));
	}
	return contentInfoBytes;
}
 
Example #17
Source File: NextCaMessage.java    From xipki with Apache License 2.0 4 votes vote down vote up
public ContentInfo encode(PrivateKey signingKey, X509Cert signerCert,
    X509Cert[] cmsCertSet) throws MessageEncodingException {
  Args.notNull(signingKey, "signingKey");
  Args.notNull(signerCert, "signerCert");

  try {
    CMSSignedDataGenerator degenerateSignedData = new CMSSignedDataGenerator();
    degenerateSignedData.addCertificate(caCert.toBcCert());
    if (CollectionUtil.isNotEmpty(raCerts)) {
      for (X509Cert m : raCerts) {
        degenerateSignedData.addCertificate(m.toBcCert());
      }
    }

    byte[] degenratedSignedDataBytes = degenerateSignedData.generate(
        new CMSAbsentContent()).getEncoded();

    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();

    // I don't known which hash algorithm is supported by the client, use SHA-1
    String signatureAlgo = getSignatureAlgorithm(signingKey, HashAlgo.SHA1);
    ContentSigner signer = new JcaContentSignerBuilder(signatureAlgo).build(signingKey);

    // signerInfo
    JcaSignerInfoGeneratorBuilder signerInfoBuilder = new JcaSignerInfoGeneratorBuilder(
        new BcDigestCalculatorProvider());

    signerInfoBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator());

    SignerInfoGenerator signerInfo = signerInfoBuilder.build(signer, signerCert.toBcCert());
    generator.addSignerInfoGenerator(signerInfo);

    CMSTypedData cmsContent = new CMSProcessableByteArray(CMSObjectIdentifiers.signedData,
        degenratedSignedDataBytes);

    // certificateSet
    ScepUtil.addCmsCertSet(generator, cmsCertSet);
    return generator.generate(cmsContent, true).toASN1Structure();
  } catch (CMSException | CertificateEncodingException | IOException
      | OperatorCreationException ex) {
    throw new MessageEncodingException(ex);
  }
}
 
Example #18
Source File: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * 1) The SignedData.encapContentInfo.eContentType.
 *
 * @param cmsSignedData
 * @return cmsSignedData.getSignedContentTypeOID() as DER encoded
 */
private byte[] getEncodedContentType(final CMSSignedData cmsSignedData) {
	final ContentInfo contentInfo = cmsSignedData.toASN1Structure();
	final SignedData signedData = SignedData.getInstance(contentInfo.getContent());
	return DSSASN1Utils.getDEREncoded(signedData.getEncapContentInfo().getContentType());
}