List of usage examples for org.bouncycastle.cms SignerInfoGeneratorBuilder build
public SignerInfoGenerator build(ContentSigner contentSigner, byte[] subjectKeyIdentifier) throws OperatorCreationException
From source file:org.signserver.module.tsa.MSAuthCodeTimeStampSigner.java
License:Open Source License
/** * The main method performing the actual timestamp operation. * Expects the signRequest to be a GenericSignRequest contining a * TimeStampRequest/* w w w. j a v a 2 s. c om*/ * * @param signRequest * @param requestContext * @return the sign response * @see org.signserver.server.IProcessable#processData(org.signserver.common.ProcessRequest, org.signserver.common.RequestContext) */ public ProcessResponse processData(final ProcessRequest signRequest, final RequestContext requestContext) throws IllegalRequestException, CryptoTokenOfflineException, SignServerException { // Log values final LogMap logMap = LogMap.getInstance(requestContext); try { final ISignRequest sReq = (ISignRequest) signRequest; final byte[] requestbytes = (byte[]) sReq.getRequestData(); if (requestbytes == null || requestbytes.length == 0) { LOG.error("Request must contain data"); throw new IllegalRequestException("Request must contain data"); } // Check that the request contains a valid TimeStampRequest object. if (!(signRequest instanceof GenericSignRequest)) { final IllegalRequestException exception = new IllegalRequestException( "Recieved request wasn't an expected GenericSignRequest. "); LOG.error("Received request wasn't an expected GenericSignRequest"); throw exception; } if (!((sReq.getRequestData() instanceof TimeStampRequest) || (sReq.getRequestData() instanceof byte[]))) { final IllegalRequestException exception = new IllegalRequestException( "Recieved request data wasn't an expected TimeStampRequest. "); LOG.error("Received request data wasn't an expected TimeStampRequest"); throw exception; } if (!validChain) { LOG.error("Certificate chain not correctly configured"); throw new CryptoTokenOfflineException("Certificate chain not correctly configured"); } ASN1Primitive asn1obj = ASN1Primitive.fromByteArray(Base64.decode(requestbytes)); ASN1Sequence asn1seq = ASN1Sequence.getInstance(asn1obj); if (asn1seq.size() != 2) { LOG.error("Wrong structure, should be an ASN1Sequence with 2 elements"); throw new IllegalRequestException("Wrong structure, should be an ASN1Sequence with 2 elements"); } ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1seq.getObjectAt(0)); ASN1Sequence asn1seq1 = ASN1Sequence.getInstance(asn1seq.getObjectAt(1)); final ContentInfo ci = new ContentInfo(asn1seq1); if (!oid.getId().equals(msOID)) { LOG.error("Invalid OID in request: " + oid.getId()); throw new IllegalRequestException("Invalid OID in request: " + oid.getId()); } if (asn1seq1.size() != 2) { LOG.error( "Wrong structure, should be an ASN1Sequence with 2 elements as the value of element 0 in the outer ASN1Sequence"); throw new IllegalRequestException( "Wrong structure, should be an ASN1Sequence with 2 elements as the value of element 0 in the outer ASN1Sequence"); } oid = ASN1ObjectIdentifier.getInstance(asn1seq1.getObjectAt(0)); if (!oid.getId().equals(dataOID)) { throw new IllegalRequestException("Wrong contentType OID: " + oid.getId()); } ASN1TaggedObject tag = ASN1TaggedObject.getInstance(asn1seq1.getObjectAt(1)); if (tag.getTagNo() != 0) { throw new IllegalRequestException("Wrong tag no (should be 0): " + tag.getTagNo()); } ASN1OctetString octets = ASN1OctetString.getInstance(tag.getObject()); byte[] content = octets.getOctets(); final ITimeSource timeSrc; final Date date; byte[] der; ICryptoInstance crypto = null; try { crypto = acquireCryptoInstance(ICryptoToken.PURPOSE_SIGN, signRequest, requestContext); // get signing cert certificate chain and private key List<Certificate> certList = this.getSigningCertificateChain(crypto); if (certList == null) { throw new SignServerException("Null certificate chain. This signer needs a certificate."); } Certificate[] certs = (Certificate[]) certList.toArray(new Certificate[certList.size()]); // Sign X509Certificate x509cert = (X509Certificate) certs[0]; timeSrc = getTimeSource(); if (LOG.isDebugEnabled()) { LOG.debug("TimeSource: " + timeSrc.getClass().getName()); } date = timeSrc.getGenTime(); if (date == null) { throw new ServiceUnavailableException("Time source is not available"); } ASN1EncodableVector signedAttributes = new ASN1EncodableVector(); signedAttributes.add(new Attribute(CMSAttributes.signingTime, new DERSet(new Time(date)))); if (includeSigningCertificateAttribute) { try { final DERInteger serial = new DERInteger(x509cert.getSerialNumber()); final X509CertificateHolder certHolder = new X509CertificateHolder(x509cert.getEncoded()); final X500Name issuer = certHolder.getIssuer(); final GeneralName name = new GeneralName(issuer); final GeneralNames names = new GeneralNames(name); final IssuerSerial is = new IssuerSerial(names, ASN1Integer.getInstance(serial)); final ESSCertID essCertid = new ESSCertID( MessageDigest.getInstance("SHA-1").digest(x509cert.getEncoded()), is); signedAttributes.add(new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificate, new DERSet(new SigningCertificate(essCertid)))); } catch (NoSuchAlgorithmException e) { LOG.error("Can't find SHA-1 implementation: " + e.getMessage()); throw new SignServerException("Can't find SHA-1 implementation", e); } } AttributeTable signedAttributesTable = new AttributeTable(signedAttributes); DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator( signedAttributesTable); final String provider = cryptoToken.getProvider(ICryptoToken.PROVIDERUSAGE_SIGN); SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()); signerInfoBuilder.setSignedAttributeGenerator(signedAttributeGenerator); JcaContentSignerBuilder contentSigner = new JcaContentSignerBuilder(signatureAlgo); contentSigner.setProvider(provider); final SignerInfoGenerator sig = signerInfoBuilder.build(contentSigner.build(crypto.getPrivateKey()), new X509CertificateHolder(x509cert.getEncoded())); JcaCertStore cs = new JcaCertStore(certList); CMSTypedData cmspba = new CMSProcessableByteArray(content); CMSSignedData cmssd = MSAuthCodeCMSUtils.generate(cmspba, true, Arrays.asList(sig), MSAuthCodeCMSUtils.getCertificatesFromStore(cs), Collections.emptyList(), ci); der = ASN1Primitive.fromByteArray(cmssd.getEncoded()).getEncoded(); } finally { releaseCryptoInstance(crypto, requestContext); } // Log values logMap.put(ITimeStampLogger.LOG_TSA_TIME, String.valueOf(date.getTime())); logMap.put(ITimeStampLogger.LOG_TSA_TIMESOURCE, timeSrc.getClass().getSimpleName()); final String archiveId = createArchiveId(requestbytes, (String) requestContext.get(RequestContext.TRANSACTION_ID)); final GenericSignResponse signResponse; byte[] signedbytes = Base64.encode(der, false); logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPRESPONSE_ENCODED, new String(signedbytes)); final Collection<? extends Archivable> archivables = Arrays.asList( new DefaultArchivable(Archivable.TYPE_REQUEST, REQUEST_CONTENT_TYPE, requestbytes, archiveId), new DefaultArchivable(Archivable.TYPE_RESPONSE, RESPONSE_CONTENT_TYPE, signedbytes, archiveId)); if (signRequest instanceof GenericServletRequest) { signResponse = new GenericServletResponse(sReq.getRequestID(), signedbytes, getSigningCertificate(signRequest, requestContext), archiveId, archivables, RESPONSE_CONTENT_TYPE); } else { signResponse = new GenericSignResponse(sReq.getRequestID(), signedbytes, getSigningCertificate(signRequest, requestContext), archiveId, archivables); } // The client can be charged for the request requestContext.setRequestFulfilledByWorker(true); return signResponse; } catch (IOException e) { final IllegalRequestException exception = new IllegalRequestException("IOException: " + e.getMessage(), e); LOG.error("IOException: ", e); logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage()); throw exception; } catch (CMSException e) { final SignServerException exception = new SignServerException(e.getMessage(), e); LOG.error("CMSException: ", e); logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage()); throw exception; } catch (OperatorCreationException e) { final SignServerException exception = new SignServerException(e.getMessage(), e); LOG.error("OperatorCreationException: ", e); logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage()); throw exception; } catch (CertificateEncodingException e) { final SignServerException exception = new SignServerException(e.getMessage(), e); LOG.error("CertificateEncodingException: ", e); logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage()); throw exception; } catch (ArrayIndexOutOfBoundsException e) { // the BC base64 decoder doesn't check the the base64 input length... final IllegalRequestException exception = new IllegalRequestException( "ArrayIndexOutOfBoundsException: " + e.getMessage(), e); LOG.error("ArrayIndexOutOfBoundsException: ", e); logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage()); throw exception; } }