use of org.bouncycastle.cms.CMSAbsentContent in project xipki by xipki.
the class ScepServlet method service.
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
boolean post;
String method = req.getMethod();
if ("GET".equals(method)) {
post = false;
} else if ("POST".equals(method)) {
post = true;
} else {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
return;
}
AuditEvent event = new AuditEvent();
event.setName(ScepAuditConstants.NAME_PERF);
event.putEventData(ScepAuditConstants.NAME_servletPath, req.getServletPath());
AuditLevel auditLevel = AuditLevel.INFO;
String auditMessage = null;
try {
CaCaps caCaps = responder.getCaCaps();
if (post && !caCaps.containsCapability(CaCapability.POSTPKIOperation)) {
auditMessage = "HTTP POST is not supported";
auditLevel = AuditLevel.ERROR;
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
String operation = req.getParameter("operation");
event.putEventData(ScepAuditConstants.NAME_operation, operation);
if ("PKIOperation".equalsIgnoreCase(operation)) {
CMSSignedData reqMessage;
// parse the request
try {
byte[] content = post ? ScepUtil.read(req.getInputStream()) : Base64.decode(req.getParameter("message"));
reqMessage = new CMSSignedData(content);
} catch (Exception ex) {
auditMessage = "invalid request";
auditLevel = AuditLevel.ERROR;
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
ContentInfo ci;
try {
ci = responder.servicePkiOperation(reqMessage, event);
} catch (MessageDecodingException ex) {
auditMessage = "could not decrypt and/or verify the request";
auditLevel = AuditLevel.ERROR;
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
} catch (CaException ex) {
auditMessage = "system internal error";
auditLevel = AuditLevel.ERROR;
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
byte[] respBytes = ci.getEncoded();
sendToResponse(resp, CT_RESPONSE, respBytes);
} else if (Operation.GetCACaps.getCode().equalsIgnoreCase(operation)) {
// CA-Ident is ignored
byte[] caCapsBytes = responder.getCaCaps().getBytes();
sendToResponse(resp, ScepConstants.CT_TEXT_PLAIN, caCapsBytes);
} else if (Operation.GetCACert.getCode().equalsIgnoreCase(operation)) {
// CA-Ident is ignored
byte[] respBytes;
String ct;
if (responder.getRaEmulator() == null) {
ct = ScepConstants.CT_X509_CA_CERT;
respBytes = responder.getCaEmulator().getCaCertBytes();
} else {
ct = ScepConstants.CT_X509_CA_RA_CERT;
CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator();
try {
cmsSignedDataGen.addCertificate(new X509CertificateHolder(responder.getCaEmulator().getCaCert()));
ct = ScepConstants.CT_X509_CA_RA_CERT;
cmsSignedDataGen.addCertificate(new X509CertificateHolder(responder.getRaEmulator().getRaCert()));
CMSSignedData degenerateSignedData = cmsSignedDataGen.generate(new CMSAbsentContent());
respBytes = degenerateSignedData.getEncoded();
} catch (CMSException ex) {
auditMessage = "system internal error";
auditLevel = AuditLevel.ERROR;
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
}
sendToResponse(resp, ct, respBytes);
} else if (Operation.GetNextCACert.getCode().equalsIgnoreCase(operation)) {
if (responder.getNextCaAndRa() == null) {
auditMessage = "SCEP operation '" + operation + "' is not permitted";
auditLevel = AuditLevel.ERROR;
resp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
try {
NextCaMessage nextCaMsg = new NextCaMessage();
nextCaMsg.setCaCert(ScepUtil.toX509Cert(responder.getNextCaAndRa().getCaCert()));
if (responder.getNextCaAndRa().getRaCert() != null) {
X509Certificate raCert = ScepUtil.toX509Cert(responder.getNextCaAndRa().getRaCert());
nextCaMsg.setRaCerts(Arrays.asList(raCert));
}
ContentInfo signedData = responder.encode(nextCaMsg);
byte[] respBytes = signedData.getEncoded();
sendToResponse(resp, ScepConstants.CT_X509_NEXT_CA_CERT, respBytes);
} catch (Exception ex) {
auditMessage = "system internal error";
auditLevel = AuditLevel.ERROR;
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
} else {
auditMessage = "unknown SCEP operation '" + operation + "'";
auditLevel = AuditLevel.ERROR;
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
// end if ("PKIOperation".equalsIgnoreCase(operation))
} catch (EOFException ex) {
LOG.warn("connection reset by peer", ex);
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} catch (Throwable th) {
LOG.error("Throwable thrown, this should not happen!", th);
auditLevel = AuditLevel.ERROR;
auditMessage = "internal error";
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} finally {
if (event.getLevel() != AuditLevel.ERROR) {
event.setLevel(auditLevel);
}
if (auditMessage != null) {
event.putEventData("error", auditMessage);
}
event.log(LOG);
}
// end try
}
use of org.bouncycastle.cms.CMSAbsentContent in project xipki by xipki.
the class ScepResponder method createSignedData.
// method servicePkiOperation0
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();
}
use of org.bouncycastle.cms.CMSAbsentContent in project signer by demoiselle.
the class CAdESSigner method doSign.
private byte[] doSign(byte[] content, byte[] previewSignature) {
try {
Security.addProvider(new BouncyCastleProvider());
// Completa os certificados ausentes da cadeia, se houver
if (this.certificate == null && this.certificateChain != null && this.certificateChain.length > 0) {
this.certificate = (X509Certificate) this.certificateChain[0];
}
this.certificateChain = CAManager.getInstance().getCertificateChainArray(this.certificate);
if (this.certificateChain.length < 3) {
throw new SignerException(cadesMessagesBundle.getString("error.no.ca", this.certificate.getIssuerDN()));
}
Certificate[] certStore = new Certificate[] {};
CMSSignedData cmsPreviewSignedData = null;
// Importar todos os certificados da assinatura anterior
if (previewSignature != null && previewSignature.length > 0) {
cmsPreviewSignedData = new CMSSignedData(new CMSAbsentContent(), previewSignature);
Collection<X509Certificate> previewCerts = this.getSignersCertificates(cmsPreviewSignedData);
// previewCerts.add(this.certificate);
certStore = previewCerts.toArray(new Certificate[] {});
}
setCertificateManager(new CertificateManager(this.certificate));
// Recupera a lista de algoritmos da politica e o tamanho minimo da
// chave
List<AlgAndLength> listOfAlgAndLength = new ArrayList<AlgAndLength>();
for (AlgAndLength algLength : signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getAlgorithmConstraintSet().getSignerAlgorithmConstraints().getAlgAndLengths()) {
listOfAlgAndLength.add(algLength);
}
AlgAndLength algAndLength = null;
// verificar se o mesmo é permitido pela politica
if (this.pkcs1.getAlgorithm() != null) {
String varSetedAlgorithmOID = AlgorithmNames.getOIDByAlgorithmName(this.pkcs1.getAlgorithm());
for (AlgAndLength algLength : listOfAlgAndLength) {
if (algLength.getAlgID().getValue().equalsIgnoreCase(varSetedAlgorithmOID)) {
algAndLength = algLength;
SignerAlgorithmEnum varSignerAlgorithmEnum = SignerAlgorithmEnum.valueOf(this.pkcs1.getAlgorithm());
String varOIDAlgorithmHash = varSignerAlgorithmEnum.getOIDAlgorithmHash();
ObjectIdentifier varObjectIdentifier = signaturePolicy.getSignPolicyHashAlg().getAlgorithm();
varObjectIdentifier.setValue(varOIDAlgorithmHash);
AlgorithmIdentifier varAlgorithmIdentifier = signaturePolicy.getSignPolicyHashAlg();
varAlgorithmIdentifier.setAlgorithm(varObjectIdentifier);
signaturePolicy.setSignPolicyHashAlg(varAlgorithmIdentifier);
}
}
} else {
algAndLength = listOfAlgAndLength.get(0);
}
if (algAndLength == null) {
throw new SignerException(cadesMessagesBundle.getString("error.no.algorithm.policy"));
}
logger.info(cadesMessagesBundle.getString("info.algorithm.id", algAndLength.getAlgID().getValue()));
logger.info(cadesMessagesBundle.getString("info.algorithm.name", AlgorithmNames.getAlgorithmNameByOID(algAndLength.getAlgID().getValue())));
logger.info(cadesMessagesBundle.getString("info.algorithm.policy.default", AlgorithmNames.getOIDByAlgorithmName(getAlgorithm())));
logger.info(cadesMessagesBundle.getString("info.min.key.length", algAndLength.getMinKeyLength()));
// Recupera o tamanho minimo da chave para validacao
logger.info(cadesMessagesBundle.getString("info.validating.key.length"));
int keyLegth = ((RSAKey) certificate.getPublicKey()).getModulus().bitLength();
if (keyLegth < algAndLength.getMinKeyLength()) {
throw new SignerException(cadesMessagesBundle.getString("error.min.key.length", algAndLength.getMinKeyLength().toString(), keyLegth));
}
AttributeFactory attributeFactory = AttributeFactory.getInstance();
// Consulta e adiciona os atributos assinados
ASN1EncodableVector signedAttributes = new ASN1EncodableVector();
logger.info(cadesMessagesBundle.getString("info.signed.attribute"));
if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules().getMandatedSignedAttr().getObjectIdentifiers() != null) {
for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules().getMandatedSignedAttr().getObjectIdentifiers()) {
SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory.factory(objectIdentifier.getValue());
signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), certificateChain, content, signaturePolicy, this.hash);
signedAttributes.add(signedOrUnsignedAttribute.getValue());
}
}
// Monta a tabela de atributos assinados
AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);
// Create the table table generator that will added to the Signer
// builder
CMSAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(signedAttributesTable);
// Recupera o(s) certificado(s) de confianca para validacao
Collection<X509Certificate> trustedCAs = new HashSet<X509Certificate>();
Collection<CertificateTrustPoint> ctp = signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getSigningCertTrustCondition().getSignerTrustTrees().getCertificateTrustPoints();
for (CertificateTrustPoint certificateTrustPoint : ctp) {
logger.info(cadesMessagesBundle.getString("info.trust.point", certificateTrustPoint.getTrustpoint().getSubjectDN().toString()));
trustedCAs.add(certificateTrustPoint.getTrustpoint());
}
// Efetua a validacao das cadeias do certificado baseado na politica
Collection<X509Certificate> certificateChainTrusted = new HashSet<X509Certificate>();
for (Certificate certCA : certificateChain) {
certificateChainTrusted.add((X509Certificate) certCA);
}
X509Certificate rootOfCertificate = null;
for (X509Certificate tcac : certificateChainTrusted) {
logger.info(tcac.getIssuerDN().toString());
if (CAManager.getInstance().isRootCA(tcac)) {
rootOfCertificate = tcac;
}
}
if (trustedCAs.contains(rootOfCertificate)) {
logger.info(cadesMessagesBundle.getString("info.trust.in.point", rootOfCertificate.getSubjectDN()));
} else {
// Não encontrou na política, verificará nas cadeias do
// componente chain-icp-brasil provavelmente certificado de
// homologação.
logger.warn(cadesMessagesBundle.getString("info.trust.poin.homolog"));
CAManager.getInstance().validateRootCAs(certificateChainTrusted, certificate);
}
// validade da politica
logger.info(cadesMessagesBundle.getString("info.policy.valid.period"));
PolicyValidator pv = new PolicyValidator(this.signaturePolicy, this.policyName);
pv.validate();
// Realiza a assinatura do conteudo
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
gen.addCertificates(this.generatedCertStore(certStore));
String algorithmOID = algAndLength.getAlgID().getValue();
logger.info(cadesMessagesBundle.getString("info.algorithm.id", algorithmOID));
SignerInfoGenerator signerInfoGenerator = new JcaSimpleSignerInfoGeneratorBuilder().setSignedAttributeGenerator(signedAttributeGenerator).setUnsignedAttributeGenerator(null).build(AlgorithmNames.getAlgorithmNameByOID(algorithmOID), this.pkcs1.getPrivateKey(), this.certificate);
gen.addSignerInfoGenerator(signerInfoGenerator);
CMSTypedData cmsTypedData;
// para assinatura do hash, content nulo
if (content == null) {
cmsTypedData = new CMSAbsentContent();
} else {
cmsTypedData = new CMSProcessableByteArray(content);
}
// Efetua a assinatura digital do conteúdo
CMSSignedData cmsSignedData = gen.generate(cmsTypedData, this.attached);
setAttached(false);
// Consulta e adiciona os atributos não assinados//
ASN1EncodableVector unsignedAttributes = new ASN1EncodableVector();
logger.info(cadesMessagesBundle.getString("info.unsigned.attribute"));
Collection<SignerInformation> vNewSigners = cmsSignedData.getSignerInfos().getSigners();
Iterator<SignerInformation> it = vNewSigners.iterator();
SignerInformation oSi = it.next();
if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules().getMandatedUnsignedAttr().getObjectIdentifiers() != null) {
for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules().getMandatedUnsignedAttr().getObjectIdentifiers()) {
SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory.factory(objectIdentifier.getValue());
if (signedOrUnsignedAttribute.getOID().equalsIgnoreCase(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())) {
signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), this.certificateChainTimeStamp, oSi.getSignature(), signaturePolicy, this.hash);
}
if (// EscTimeStamp
signedOrUnsignedAttribute.getOID().equalsIgnoreCase("1.2.840.113549.1.9.16.2.25")) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(oSi.getSignature());
AttributeTable varUnsignedAttributes = oSi.getUnsignedAttributes();
Attribute varAttribute = varUnsignedAttributes.get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId()));
outputStream.write(varAttribute.getAttrType().getEncoded());
outputStream.write(varAttribute.getAttrValues().getEncoded());
varAttribute = varUnsignedAttributes.get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_certificateRefs.getId()));
outputStream.write(varAttribute.getAttrType().getEncoded());
outputStream.write(varAttribute.getAttrValues().getEncoded());
varAttribute = varUnsignedAttributes.get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_revocationRefs.getId()));
outputStream.write(varAttribute.getAttrType().getEncoded());
outputStream.write(varAttribute.getAttrValues().getEncoded());
escTimeStampContent = outputStream.toByteArray();
signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), this.certificateChainTimeStamp, escTimeStampContent, signaturePolicy, this.hash);
} else {
signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), certificateChain, oSi.getSignature(), signaturePolicy, this.hash);
}
unsignedAttributes.add(signedOrUnsignedAttribute.getValue());
AttributeTable unsignedAttributesTable = new AttributeTable(unsignedAttributes);
vNewSigners.remove(oSi);
oSi = SignerInformation.replaceUnsignedAttributes(oSi, unsignedAttributesTable);
vNewSigners.add(oSi);
}
}
// TODO Estudar este método de contra-assinatura posteriormente
if (previewSignature != null && previewSignature.length > 0) {
vNewSigners.addAll(cmsPreviewSignedData.getSignerInfos().getSigners());
}
SignerInformationStore oNewSignerInformationStore = new SignerInformationStore(vNewSigners);
CMSSignedData oSignedData = cmsSignedData;
cmsSignedData = CMSSignedData.replaceSigners(oSignedData, oNewSignerInformationStore);
byte[] result = cmsSignedData.getEncoded();
logger.info(cadesMessagesBundle.getString("info.signature.ok"));
return result;
} catch (CMSException | IOException | OperatorCreationException | CertificateEncodingException ex) {
throw new SignerException(ex);
}
}
Aggregations