org.bouncycastle.asn1.cms.Attribute Java Examples

The following examples show how to use org.bouncycastle.asn1.cms.Attribute. 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: CAdESSignature.java    From dss with GNU Lesser General Public License v2.1 7 votes vote down vote up
private SignerAttribute getSignerAttributeV1() {
	final Attribute id_aa_ets_signerAttr = getSignedAttribute(PKCSObjectIdentifiers.id_aa_ets_signerAttr);
	if (id_aa_ets_signerAttr != null) {
		final ASN1Set attrValues = id_aa_ets_signerAttr.getAttrValues();
		final ASN1Encodable attrValue = attrValues.getObjectAt(0);
		try {
			return SignerAttribute.getInstance(attrValue);
		} catch (Exception e) {
			String warningMessage = "Unable to parse signerAttr - [{}]. Reason : {}";
			if (LOG.isDebugEnabled()) {
				LOG.warn(warningMessage, Utils.toBase64(DSSASN1Utils.getDEREncoded(attrValue)), e.getMessage(), e);
			} else {
				LOG.warn(warningMessage, Utils.toBase64(DSSASN1Utils.getDEREncoded(attrValue)), e.getMessage());
			}
		}
	}
	return null;
}
 
Example #2
Source File: DSSASN1UtilsTest.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void isArchiveTimeStampTokenTest() {
	String atstV2 = "MIIIhwYLKoZIhvcNAQkQAjAxggh2MIIIcgYJKoZIhvcNAQcCoIIIYzCCCF8CAQMxDzANBglghkgBZQMEAgEFADCCARMGCyqGSIb3DQEJEAEEoIIBAgSB/zCB/AIBAQYKKwYBBAH7SwUCAjAxMA0GCWCGSAFlAwQCAQUABCAm67S7cA/ArzsncKnDKJk7AQVkbbH2LmjhxjNFGKEKeAIVAKQr5q6pobk+BGS1xZJBa0LrWjgtGBMyMDE4MDUwNzE0MTMxNy41OTNaMAOAAQECCQDdRKjMw1Tj/aB8pHoweDEpMCcGA1UEAxMgVW5pdmVyc2lnbiBUaW1lc3RhbXBpbmcgVW5pdCAwMjExHDAaBgNVBAsTEzAwMDIgNDM5MTI5MTY0MDAwMjYxI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NQIQWh/wl2n+6D045tXkVdEH/zANBgkqhkiG9w0BAQsFAASCAQA4NsVVHBUrIs+zoonsl2eFUVwBehoTZJJvLSp41Q3jdAci2ppTzL/8rsvlv3RwDc6lMcOFDZhSuKOIT8rLXPg050xAglxUzkN0r9WpscQ6/cfJZmvVTf01gERTYuqrLhs5lF2qdEOty+42VeJB4hW/gAunEQxJuOyO1xGRBkgyIQq2t63FcwR/+Qw9IWRByNp15Bdt30HpvmyvhR3y/T4hK/9NatRAxoBIRhHXlwUT15Bphf22bDuOyEJyOYnviAvpcUq0g5v7KQcIJdmk93elzo+n8yIwCS7lm3XhZYLsyocLbQBP6oNCZlrNZ4YL4SuMcP0JWW7jfj/+OzWGax8H";
	ASN1Primitive asn1Primitive = DSSASN1Utils.toASN1Primitive(Utils.fromBase64(atstV2));
	Attribute atstV2Attibute = new Attribute(OID.id_aa_ets_archiveTimestampV2, new DERSet(asn1Primitive));
	assertTrue(DSSASN1Utils.isArchiveTimeStampToken(atstV2Attibute));
	
	String atstV3 = "MIIJWwYJKoZIhvcNAQcCoIIJTDCCCUgCAQMxDzANBglghkgBZQMEAgMFADCB/gYLKoZIhvcNAQkQAQSgge4EgeswgegCAQEGBgQAj2cBATAxMA0GCWCGSAFlAwQCAQUABCCn0cRUUvQwpjtFZ8VAx0nzxzu3gZ2Ymqcp87qgiY/4OQIIXuTHubzkaM4YDzIwMjAwNDExMTIzNDQwWjADAgEBAgiO+SBfQ41ZO6B+pHwwejEnMCUGA1UEAwweU0sgVElNRVNUQU1QSU5HIEFVVEhPUklUWSAyMDIwMRcwFQYDVQRhDA5OVFJFRS0xMDc0NzAxMzEMMAoGA1UECwwDVFNBMRswGQYDVQQKDBJTSyBJRCBTb2x1dGlvbnMgQVMxCzAJBgNVBAYTAkVFoIIEGjCCBBYwggL+oAMCAQICEGI2fXRa2UOrXaRQuV4/+m4wDQYJKoZIhvcNAQELBQAwdTELMAkGA1UEBhMCRUUxIjAgBgNVBAoMGUFTIFNlcnRpZml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/UdDN30xrit7YaW16UNQyvFSt9TTx8LL2mJvl1tjDrKn9V9ua4+B31nsYF6XT2ypfEaXZV1pEWqA20+RRcCctdMXSQl7UTx0L0BCfTBRsd86Me/Dk9J1yJkEeOKXfsTEtnKAQThjWtw4qGtswyqeCKh+EMCe62B5ZC+1bZTlohfD1GhggEHMIIBAwYGBACNRQIFMYH4MIH1MGYEIK3f+m/QgJpUqfCzH9JfdL9/LXrhHID9mdqg+2A6Zc0OBCCkXt47u/CciuFccu/AcmjWk6IcmW/VHmfKB5Rg/W2IcwQgYMHF0qMQHKR1OJ2F1UQbg+HTVL+OJeft+dR5H4CzDtowADCBiAQgvqmBrWZOoI5LCE6ZgL6B1pSwGikyP/Gpw87i+EyQp0cEIHmnEgy9yobW4GAfAad4eiVXn6pdMKNizXvUwzqd/eyKBCBu1yd6G1zNfHMHbTc/VvEe5Q85N/6gpJekpgWhLuBQxQQg3WcimJCwZgUxiFzPw7zMX8F4+FTiNC/lXpKaOmvbSQE=";
	asn1Primitive = DSSASN1Utils.toASN1Primitive(Utils.fromBase64(atstV3));
	Attribute atstV3Attibute = new Attribute(OID.id_aa_ets_archiveTimestampV3, new DERSet(asn1Primitive));
	assertTrue(DSSASN1Utils.isArchiveTimeStampToken(atstV3Attibute));
	
	String sigTst = "MIIVJQYJKoZIhvcNAQcCoIIVFjCCFRICAQMxDzANBglghkgBZQMEAgEFADCCARMGCyqGSIb3DQEJEAEEoIIBAgSB/zCB/AIBAQYKKwYBBAH7SwUCAjAxMA0GCWCGSAFlAwQCAQUABCBT2S93XuvGV5XB9P74rlXpEBNQw7v+LkhVqlWcwyGgDwIVAKzJneGO+8crMY8T0qaCcD2284U4GBMyMDE4MDUwNzE0MTMxMS4xMDRaMAOAAQECCQDAIEqncxQduqB8pHoweDEpMCcGA1UEAxMgVW5pdmVyc2lnbiBUaW1lc3RhbXBpbmcgVW5pdCAwMjAxHDAaBgNVBAsTEzAwMDIgNDM5MTI5MTY0MDAwMjYxIDAeBgNVBA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0lAQH/BAwwCgYIKwYBBQUHAwgwHwYDVR0jBBgwFoAU+k3tVzu9P/ORM5oLOaR/XRLdB0YwDQYJKoZIhvcNAQELBQADggEBADNaZmy7AZ0OsCKPnmQOxpvbIFTxZFerE/4ysyPlVd9f15bgreBWekK0MaTZ32C3Clv2k5S31797WcXz6EmkkaNFHcEAetsChyitR7dq6wyzYPxlyRVIBm8lR3fCaIaYcUoGoXaimcIysOgc+RrqvgcXiZ7Hi2yNmtpg0DVzVnYAS5EjSJcGsjcTlFtcNqEl7L1FqP0DqsGwW/sjef1BRzTDB0IMrItiAkV3zvVXE67UwC8l8DtJaveb+KBCvhL2wcBijfilXzIdwBBg7w/rtLaTDFUFqn4WvWk4buoQESbb7WK0KNM9McSPF8OlyNggkgySgoouX70t9POZEGMZyZ0=";
	asn1Primitive = DSSASN1Utils.toASN1Primitive(Utils.fromBase64(sigTst));
	Attribute sigTstsAttibute = new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, new DERSet(asn1Primitive));
	assertFalse(DSSASN1Utils.isArchiveTimeStampToken(sigTstsAttibute));
	
	String certValues = "MIIL6wYLKoZIhvcNAQkQAhcxggvaMIIL1jCCBZ8wggSHoAMCAQICFDdbittYXdJlQ+xDC4cAUwx+EP2eMA0GCSqGSIb3DQEBCwUAMH8xCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMSUwIwYDVQQLExxSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MS4wLAYDVQQDEyVRdW9WYWRpcyBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTE0MDUzMDE4MTU0OVoXDTIxMDMxNzE4MzMzM1owaDELMAkGA1UEBhMCTkwxIDAeBgNVBAoTF1F1b1ZhZGlzIFRydXN0bGluayBCLlYuMTcwNQYDVQQDEy5RdW9WYWRpcyBFVSBJc3N1aW5nIENlcnRpZmljYXRpb24gQXV0aG9yaXR5IEczMIICIjANBgkqhkiG9w0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sB8ddJM/bC0aHcu3viaYZ+tH3UwLOEVs0ebmVouYOhTg543n0u3uXS/ZlgKXSDG7NnUsfg7n717MG94RUQj9FLux7PPENPAaxP9VN8MaX4QQw4ybrVxGlSbZZlcMHL3++U26Nga+Oekasr261b6SAI4ro6amxMIo8pAR38LSwnAbI15mUDv+Ow712yGdf7ezMJkLZp1u/A6WYAsuPU2YbZ7iFofX1ApvGJyDWVv3nVjipjQ/xgcdcKvPwHhaQd4kJ8+LYsiFPehm/7xXSG3dUWkVUgNcAmOzZH10Z9OfPYDJlQgNxJJ+aloYiFtQKuc2+6cT0PwHcMDRICnGKZ+rweMUkI0v9b6fqnZ8OohiSKOVeWwrWqVIKEYZULZryJqdJfZ88LXUoA==";
	asn1Primitive = DSSASN1Utils.toASN1Primitive(Utils.fromBase64(certValues));
	Attribute certValuesAttibute = new Attribute(PKCSObjectIdentifiers.id_aa_ets_certValues, new DERSet(asn1Primitive));
	assertFalse(DSSASN1Utils.isArchiveTimeStampToken(certValuesAttibute));
}
 
Example #3
Source File: SigningCertificateV2.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
	public Attribute getValue() throws SignerException {
		try {
			X509Certificate cert = (X509Certificate) certificates[0];
			X509Certificate issuerCert = (X509Certificate) certificates[1];
			Digest digest = DigestFactory.getInstance().factoryDefault();
			digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
			byte[] certHash = digest.digest(cert.getEncoded());
			X500Name dirName = new X500Name(issuerCert.getSubjectX500Principal().getName());
			GeneralName name = new GeneralName(dirName);
			GeneralNames issuer = new GeneralNames(name);
			ASN1Integer serialNumber = new ASN1Integer(cert.getSerialNumber());
			IssuerSerial issuerSerial = new IssuerSerial(issuer, serialNumber);
			AlgorithmIdentifier algId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256);// SHA-256
			ESSCertIDv2 essCertIDv2 = new ESSCertIDv2(algId, certHash, issuerSerial);
//			return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(essCertIDv2)));
			return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(
					new ASN1Encodable[] { new DERSequence(essCertIDv2) })));
		} catch (CertificateEncodingException ex) {
			throw new SignerException(ex.getMessage());
		}
	}
 
Example #4
Source File: TimeStampToken.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Attribute getValue() throws SignerException {
    try {
        logger.info(cadesMessagesBundle.getString("info.tsa.connecting"));

        if (timeStampGenerator != null) {
              //Inicializa os valores para o timestmap
        	timeStampGenerator.initialize(content, privateKey, certificates, hash);

            //Obtem o carimbo de tempo atraves do servidor TSA
            byte[] response = timeStampGenerator.generateTimeStamp();

            //Valida o carimbo de tempo gerado
            timeStampGenerator.validateTimeStamp(content, response, hash);

            return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(ASN1Primitive.fromByteArray(response)));
        } else {
            throw new SignerException(cadesMessagesBundle.getString("error.tsa.not.found"));
        }
    } catch (SecurityException | IOException ex) {
        throw new SignerException(ex.getMessage());
    }
}
 
Example #5
Source File: SigningCertificate.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Attribute getValue() {
    try {
        X509Certificate cert = (X509Certificate) certificates[0];
        Digest digest = DigestFactory.getInstance().factoryDefault();
        digest.setAlgorithm(DigestAlgorithmEnum.SHA_1);
        byte[] hash = digest.digest(cert.getEncoded());
        X500Name dirName = new X500Name(cert.getSubjectDN().getName());
        GeneralName name = new GeneralName(dirName);
        GeneralNames issuer = new GeneralNames(name);
        ASN1Integer serial = new ASN1Integer(cert.getSerialNumber());
        IssuerSerial issuerSerial = new IssuerSerial(issuer, serial);
        ESSCertID essCertId = new ESSCertID(hash, issuerSerial);
        return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(new ASN1Encodable[]{new DERSequence(essCertId), new DERSequence(DERNull.INSTANCE)})));

    } catch (CertificateEncodingException ex) {
        throw new SignerException(ex.getMessage());
    }
}
 
Example #6
Source File: EscTimeStamp.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Attribute getValue() throws SignerException {
	try {
        logger.info(cadesMessagesBundle.getString("info.tsa.connecting"));

        if (timeStampGenerator != null) {
              //Inicializa os valores para o timestmap
        	timeStampGenerator.initialize(content, privateKey, certificates, hash);

            //Obtem o carimbo de tempo atraves do servidor TSA
            byte[] response = timeStampGenerator.generateTimeStamp();

            //Valida o carimbo de tempo gerado
            timeStampGenerator.validateTimeStamp(content, response, hash);

            return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(ASN1Primitive.fromByteArray(response)));
        } else {
            throw new SignerException(cadesMessagesBundle.getString("error.tsa.not.found"));
        }
    } catch (SecurityException | IOException ex) {
    }
    throw new UnsupportedOperationException(cadesMessagesBundle.getString("error.not.supported",getClass().getName()));
}
 
Example #7
Source File: CAdESTimeStampSigner.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Timestamp checkTimeStamp(byte[] timeStamp, byte[] content,  byte[] hash){
	try {
		Security.addProvider(new BouncyCastleProvider());
		ais = new ASN1InputStream(new ByteArrayInputStream(timeStamp));
	    ASN1Sequence seq=(ASN1Sequence)ais.readObject();
        Attribute attributeTimeStamp = new Attribute((ASN1ObjectIdentifier)seq.getObjectAt(0), (ASN1Set)seq.getObjectAt(1));
        byte[] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded();
        TimeStampOperator timeStampOperator = new TimeStampOperator();
        if (content != null){
        	timeStampOperator.validate(content, varTimeStamp,null);
        }else{
        	timeStampOperator.validate(null, varTimeStamp,hash);
        }			
		TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
		Timestamp timeStampSigner = new Timestamp(timeStampToken);
		return timeStampSigner;
	} catch (CertificateCoreException | IOException | TSPException
			| CMSException e) {
		throw new SignerException(e);
	}

}
 
Example #8
Source File: CMSSignedDataWrapper.java    From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 6 votes vote down vote up
private static ASN1Set buildSignedAttributes(byte[] hash, Date dateTime, X509Certificate cert) throws Exception {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new Attribute(CMSAttributes.contentType, new DERSet(PKCSObjectIdentifiers.data)));
    if (dateTime != null)
        v.add(new Attribute(CMSAttributes.signingTime, new DERSet(new Time(dateTime))));
    v.add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(hash))));

    // CADES support section
    ASN1EncodableVector aaV2 = new ASN1EncodableVector();
    AlgorithmIdentifier algoId = new AlgorithmIdentifier(new ASN1ObjectIdentifier(CMSSignedDataGenerator.DIGEST_SHA256), null);
    aaV2.add(algoId);
    byte[] dig = SignUtils.calculateHASH(CMSSignedDataGenerator.DIGEST_SHA256, cert.getEncoded());
    aaV2.add(new DEROctetString(dig));
    Attribute cades = new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificateV2, new DERSet(new DERSequence(new DERSequence(new DERSequence(aaV2)))));
    v.add(cades);

    ASN1Set signedAttributes = new DERSet(v);
    return signedAttributes;
}
 
Example #9
Source File: TimeStampValidatorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void validateTimeStampToken(byte[] bs, TimeStampToken tsToken) throws InvalidTimeStampException, TechnicalConnectorException {
   byte[] calculatedDigest = ConnectorCryptoUtils.calculateDigest(tsToken.getTimeStampInfo().getMessageImprintAlgOID().getId(), bs);
   byte[] tokenDigestValue = tsToken.getTimeStampInfo().getMessageImprintDigest();
   if (!MessageDigest.isEqual(calculatedDigest, tokenDigestValue)) {
      throw new InvalidTimeStampException("Response for different message imprint digest.");
   } else {
      Attribute scV1 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificate);
      Attribute scV2 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificateV2);
      if (scV1 == null && scV2 == null) {
         throw new InvalidTimeStampException("no signing certificate attribute present.", (Exception)null);
      } else if (scV1 != null && scV2 != null) {
         throw new InvalidTimeStampException("Conflicting signing certificate attributes present.");
      } else {
         this.validateTimeStampToken(tsToken);
      }
   }
}
 
Example #10
Source File: TimeStampValidatorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void validateTimeStampToken(byte[] bs, TimeStampToken tsToken) throws InvalidTimeStampException, TechnicalConnectorException {
   byte[] calculatedDigest = ConnectorCryptoUtils.calculateDigest(tsToken.getTimeStampInfo().getMessageImprintAlgOID().getId(), bs);
   byte[] tokenDigestValue = tsToken.getTimeStampInfo().getMessageImprintDigest();
   if (!MessageDigest.isEqual(calculatedDigest, tokenDigestValue)) {
      throw new InvalidTimeStampException("Response for different message imprint digest.");
   } else {
      Attribute scV1 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificate);
      Attribute scV2 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificateV2);
      if (scV1 == null && scV2 == null) {
         throw new InvalidTimeStampException("no signing certificate attribute present.", (Exception)null);
      } else if (scV1 != null && scV2 != null) {
         throw new InvalidTimeStampException("Conflicting signing certificate attributes present.");
      } else {
         this.validateTimeStampToken(tsToken);
      }
   }
}
 
Example #11
Source File: TimeStampValidatorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void validateTimeStampToken(byte[] bs, TimeStampToken tsToken) throws InvalidTimeStampException, TechnicalConnectorException {
   byte[] calculatedDigest = ConnectorCryptoUtils.calculateDigest(tsToken.getTimeStampInfo().getMessageImprintAlgOID().getId(), bs);
   byte[] tokenDigestValue = tsToken.getTimeStampInfo().getMessageImprintDigest();
   if (!MessageDigest.isEqual(calculatedDigest, tokenDigestValue)) {
      throw new InvalidTimeStampException("Response for different message imprint digest.");
   } else {
      Attribute scV1 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificate);
      Attribute scV2 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificateV2);
      if (scV1 == null && scV2 == null) {
         throw new InvalidTimeStampException("no signing certificate attribute present.", (Exception)null);
      } else if (scV1 != null && scV2 != null) {
         throw new InvalidTimeStampException("Conflicting signing certificate attributes present.");
      } else {
         this.validateTimeStampToken(tsToken);
      }
   }
}
 
Example #12
Source File: CertValues.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
  public Attribute getValue() throws SignerException {

  	List<org.bouncycastle.asn1.x509.Certificate> certificateValues = new ArrayList<org.bouncycastle.asn1.x509.Certificate>();
  	try {
  		
  		int chainSize = certificates.length -1;
   		  for (int i = 0; i < chainSize; i++ ){
  		  	    X509Certificate cert = (X509Certificate) certificates[i];
  		  	  byte data[] = cert.getEncoded();
  		  	  certificateValues.add(org.bouncycastle.asn1.x509.Certificate.getInstance(data));    		  	  
  		 }	 
  		  org.bouncycastle.asn1.x509.Certificate[] certValuesArray = new org.bouncycastle.asn1.x509.Certificate[certificateValues.size()];
	return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(certificateValues.toArray(certValuesArray))));
  	} catch (CertificateEncodingException e) {
  		throw new SignerException(e.getMessage());
}
  }
 
Example #13
Source File: CMSCertificateSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void extractCertificateRefsFromUnsignedAttribute(ASN1ObjectIdentifier attributeOid, CertificateRefOrigin origin) {
	AttributeTable unsignedAttributes = currentSignerInformation.getUnsignedAttributes();
	if (unsignedAttributes != null) {
		Attribute attribute = unsignedAttributes.get(attributeOid);
		if (attribute != null) {
			final ASN1Sequence seq = (ASN1Sequence) attribute.getAttrValues().getObjectAt(0);
			for (int ii = 0; ii < seq.size(); ii++) {
				try {
					OtherCertID otherCertId = OtherCertID.getInstance(seq.getObjectAt(ii));
					CertificateRef certRef = DSSASN1Utils.getCertificateRef(otherCertId);
					certRef.setOrigin(origin);
					addCertificateRef(certRef, origin);
				} catch (Exception e) {
					LOG.warn("Unable to parse encapsulated OtherCertID : {}", e.getMessage());
				}
			}
		}
	}
}
 
Example #14
Source File: JarSigner.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private static CMSSignedData addTimestamp(String tsaUrl, CMSSignedData signedData) throws IOException {

		Collection<SignerInformation> signerInfos = signedData.getSignerInfos().getSigners();

		// get signature of first signer (should be the only one)
		SignerInformation si = signerInfos.iterator().next();
		byte[] signature = si.getSignature();

		// send request to TSA
		byte[] token = TimeStampingClient.getTimeStampToken(tsaUrl, signature, DigestType.SHA1);

		// create new SignerInformation with TS attribute
		Attribute tokenAttr = new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken,
				new DERSet(ASN1Primitive.fromByteArray(token)));
		ASN1EncodableVector timestampVector = new ASN1EncodableVector();
		timestampVector.add(tokenAttr);
		AttributeTable at = new AttributeTable(timestampVector);
		si = SignerInformation.replaceUnsignedAttributes(si, at);
		signerInfos.clear();
		signerInfos.add(si);
		SignerInformationStore newSignerStore = new SignerInformationStore(signerInfos);

		// create new signed data
		CMSSignedData newSignedData = CMSSignedData.replaceSigners(signedData, newSignerStore);
		return newSignedData;
	}
 
Example #15
Source File: CAdESTimestampDataBuilder.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public DSSDocument getTimestampX1Data(TimestampToken timestampToken) {
	try (ByteArrayOutputStream data = new ByteArrayOutputStream()) {
		data.write(signerInformation.getSignature());
		// We don't include the outer SEQUENCE, only the attrType and
		// attrValues as stated by the TS §6.3.5, NOTE 2

		final Attribute attribute = CMSUtils.getUnsignedAttribute(signerInformation, id_aa_signatureTimeStampToken);
		if (attribute != null) {
			data.write(DSSASN1Utils.getDEREncoded(attribute.getAttrType()));
			data.write(DSSASN1Utils.getDEREncoded(attribute.getAttrValues()));
		}
		// Method is common to Type 1 and Type 2
		data.write(getTimestampX2DataBytes(timestampToken));
		byte[] byteArray = data.toByteArray();
		return new InMemoryDocument(byteArray);
	} catch (IOException e) {
		throw new DSSException(e);
	}
}
 
Example #16
Source File: CAdESTimestampDataBuilder.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private byte[] getTimestampX2DataBytes(final TimestampToken timestampToken) {
	try (ByteArrayOutputStream data = new ByteArrayOutputStream()) {
		// Those are common to Type 1 and Type 2
		final Attribute certAttribute = CMSUtils.getUnsignedAttribute(signerInformation, id_aa_ets_certificateRefs);
		final Attribute revAttribute = CMSUtils.getUnsignedAttribute(signerInformation, id_aa_ets_revocationRefs);
		if (certAttribute != null) {
			data.write(DSSASN1Utils.getDEREncoded(certAttribute.getAttrType()));
			data.write(DSSASN1Utils.getDEREncoded(certAttribute.getAttrValues()));
		}
		if (revAttribute != null) {
			data.write(DSSASN1Utils.getDEREncoded(revAttribute.getAttrType()));
			data.write(DSSASN1Utils.getDEREncoded(revAttribute.getAttrValues()));
		}

		return data.toByteArray();
	} catch (IOException e) {
		throw new DSSException(e);
	}
}
 
Example #17
Source File: CMSCertificateSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void extractCertificateValues() {
	AttributeTable unsignedAttributes = currentSignerInformation.getUnsignedAttributes();
	if (unsignedAttributes != null) {
		Attribute attribute = unsignedAttributes.get(id_aa_ets_certValues);
		if (attribute != null) {
			final ASN1Sequence seq = (ASN1Sequence) attribute.getAttrValues().getObjectAt(0);
			for (int ii = 0; ii < seq.size(); ii++) {
				try {
					final Certificate cs = Certificate.getInstance(seq.getObjectAt(ii));
					addCertificate(DSSUtils.loadCertificate(cs.getEncoded()), CertificateOrigin.CERTIFICATE_VALUES);
				} catch (Exception e) {
					LOG.warn("Unable to parse encapsulated certificate : {}", e.getMessage());
				}
			}
		}
	}
}
 
Example #18
Source File: CAdESTimestampDataBuilder.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Remove any archive-timestamp-v2/3 attribute added after the
 * timestampToken
 */
private ASN1Sequence filterUnauthenticatedAttributes(ASN1Set unauthenticatedAttributes, TimestampToken timestampToken) {
	ASN1EncodableVector result = new ASN1EncodableVector();
	for (int ii = 0; ii < unauthenticatedAttributes.size(); ii++) {

		final Attribute attribute = Attribute.getInstance(unauthenticatedAttributes.getObjectAt(ii));
		final ASN1ObjectIdentifier attrType = attribute.getAttrType();
		if (id_aa_ets_archiveTimestampV2.equals(attrType) || id_aa_ets_archiveTimestampV3.equals(attrType)) {
			try {

				TimeStampToken token = DSSASN1Utils.getTimeStampToken(attribute);
				if (!token.getTimeStampInfo().getGenTime().before(timestampToken.getGenerationTime())) {
					continue;
				}
			} catch (Exception e) {
				throw new DSSException(e);
			}
		}
		result.add(unauthenticatedAttributes.getObjectAt(ii));
	}
	return new DERSequence(result);
}
 
Example #19
Source File: CMSCertificateSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void extractSigningCertificateV2(Attribute attribute) {
	final ASN1Set attrValues = attribute.getAttrValues();
	for (int ii = 0; ii < attrValues.size(); ii++) {
		final ASN1Encodable asn1Encodable = attrValues.getObjectAt(ii);
		try {
			final SigningCertificateV2 signingCertificate = SigningCertificateV2.getInstance(asn1Encodable);
			if (signingCertificate != null) {
				extractESSCertIDv2s(signingCertificate.getCerts(), CertificateRefOrigin.SIGNING_CERTIFICATE);
			} else {
				LOG.warn("SigningCertificateV2 attribute is null");
			}
		} catch (Exception e) {
			LOG.warn("SigningCertificateV2 attribute '{}' is not well defined!", Utils.toBase64(DSSASN1Utils.getDEREncoded(asn1Encodable)));
		}
	}
}
 
Example #20
Source File: CMSCertificateSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void extractSigningCertificateV1(Attribute attribute) {
	final ASN1Set attrValues = attribute.getAttrValues();
	for (int ii = 0; ii < attrValues.size(); ii++) {
		final ASN1Encodable asn1Encodable = attrValues.getObjectAt(ii);
		try {
			final SigningCertificate signingCertificate = SigningCertificate.getInstance(asn1Encodable);
			if (signingCertificate != null) {
				extractESSCertIDs(signingCertificate.getCerts(), CertificateRefOrigin.SIGNING_CERTIFICATE);
			} else {
				LOG.warn("SigningCertificate attribute is null");
			}
		} catch (Exception e) {
			LOG.warn("SigningCertificate attribute '{}' is not well defined!", Utils.toBase64(DSSASN1Utils.getDEREncoded(asn1Encodable)));
		}
	}
}
 
Example #21
Source File: CMSOCSPSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void collectRevocationRefs(AttributeTable unsignedAttributes, ASN1ObjectIdentifier revocationReferencesAttribute, RevocationRefOrigin origin) {
	final Attribute attribute = unsignedAttributes.get(revocationReferencesAttribute);
	if (attribute == null) {
		return;
	}
	final ASN1Set attrValues = attribute.getAttrValues();
	if (attrValues.size() <= 0) {
		return;
	}

	final ASN1Encodable attrValue = attrValues.getObjectAt(0);
	final ASN1Sequence completeRevocationRefs = (ASN1Sequence) attrValue;
	for (int i = 0; i < completeRevocationRefs.size(); i++) {

		final CrlOcspRef otherCertId = CrlOcspRef.getInstance(completeRevocationRefs.getObjectAt(i));
		final OcspListID ocspListID = otherCertId.getOcspids();
		if (ocspListID != null) {
			for (final OcspResponsesID ocspResponsesID : ocspListID.getOcspResponses()) {
				final OCSPRef ocspRef = new OCSPRef(ocspResponsesID);
				addRevocationReference(ocspRef, origin);
			}
		}
	}
}
 
Example #22
Source File: CAdESLevelBaselineB.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * ETSI TS 101 733 V2.2.1 (2013-04)
 *
 * 5.10.2 content-identifier Attribute
 * The content-identifier attribute provides an identifier for the signed content, for use when a reference may be
 * later required to that content; for example, in the content-reference attribute in other signed data sent later.
 * The
 * content-identifier shall be a signed attribute. content-identifier attribute type values for the ES have an ASN.1
 * type ContentIdentifier, as defined in
 * ESS (RFC 2634 [5]).
 *
 * The minimal content-identifier attribute should contain a concatenation of user-specific identification
 * information (such as a user name or public keying material identification information), a GeneralizedTime string,
 * and a random number.
 *
 * @param parameters
 * @param signedAttributes
 */
private void addContentIdentifier(final CAdESSignatureParameters parameters, final ASN1EncodableVector signedAttributes) {
	/* this attribute is prohibited in PAdES B */
	if (padesUsage) {
		return;
	}

	final String contentIdentifierPrefix = parameters.getContentIdentifierPrefix();
	if (Utils.isStringNotBlank(contentIdentifierPrefix)) {
		if (Utils.isStringBlank(parameters.getContentIdentifierSuffix())) {
			StringBuilder suffixBuilder = new StringBuilder();
			suffixBuilder.append(new ASN1GeneralizedTime(new Date()).getTimeString());
			suffixBuilder.append(new SecureRandom().nextLong());
			parameters.setContentIdentifierSuffix(suffixBuilder.toString());
		}
		final String contentIdentifierString = contentIdentifierPrefix + parameters.getContentIdentifierSuffix();
		final ContentIdentifier contentIdentifier = new ContentIdentifier(contentIdentifierString.getBytes());
		final DERSet attrValues = new DERSet(contentIdentifier);
		final Attribute attribute = new Attribute(id_aa_contentIdentifier, attrValues);
		signedAttributes.add(attribute);
	}
}
 
Example #23
Source File: CAdESLevelBaselineB.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * ETSI TS 101 733 V2.2.1 (2013-04)
 *
 * 5.11.1 commitment-type-indication Attribute
 * There may be situations where a signer wants to explicitly indicate to a verifier that by signing the data, it
 * illustrates a
 * type of commitment on behalf of the signer. The commitment-type-indication attribute conveys such
 * information.
 *
 * @param parameters
 * @param signedAttributes
 */
private void addCommitmentType(final CAdESSignatureParameters parameters, final ASN1EncodableVector signedAttributes) {

	// TODO (19/08/2014): commitmentTypeQualifier is not implemented
	final List<CommitmentType> commitmentTypeIndications = parameters.bLevel().getCommitmentTypeIndications();
	if (Utils.isCollectionNotEmpty(commitmentTypeIndications)) {

		final int size = commitmentTypeIndications.size();
		ASN1Encodable[] asn1Encodables = new ASN1Encodable[size];
		for (int ii = 0; ii < size; ii++) {
			
			final CommitmentType commitmentType = commitmentTypeIndications.get(ii);
			if (commitmentType.getOid() == null) {
				throw new DSSException("The commitmentTypeIndication OID must be defined for CAdES creation!");
			}

			final ASN1ObjectIdentifier objectIdentifier = new ASN1ObjectIdentifier(commitmentType.getOid());
			final CommitmentTypeIndication commitmentTypeIndication = new CommitmentTypeIndication(objectIdentifier);
			asn1Encodables[ii] = commitmentTypeIndication.toASN1Primitive(); // DER encoded
		}
		final DERSet attrValues = new DERSet(asn1Encodables);
		final Attribute attribute = new Attribute(id_aa_ets_commitmentType, attrValues);
		signedAttributes.add(attribute);
	}
}
 
Example #24
Source File: CAdESLevelBaselineB.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void addSigningTimeAttribute(final CAdESSignatureParameters parameters, final ASN1EncodableVector signedAttributes) {
	/*
	 * In PAdES, we don't include the signing time : ETSI TS 102 778-3 V1.2.1
	 * (2010-07): 4.5.3 signing-time Attribute
	 */
	if (padesUsage) {
		return;
	}

	final Date signingDate = parameters.bLevel().getSigningDate();
	if (signingDate != null) {
		final DERSet attrValues = new DERSet(new Time(signingDate));
		final Attribute attribute = new Attribute(pkcs_9_at_signingTime, attrValues);
		signedAttributes.add(attribute);
	}
}
 
Example #25
Source File: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
public byte[] getArchiveTimestampDataV3(SignerInformation signerInformation, Attribute atsHashIndexAttribute, byte[] originalDocumentDigest) {
	final byte[] encodedContentType = getEncodedContentType(cmsSignedData); // OID
	final byte[] signedDataDigest = originalDocumentDigest;
	final byte[] encodedFields = getSignedFields(signerInformation);
	final byte[] encodedAtsHashIndex = DSSASN1Utils.getDEREncoded(atsHashIndexAttribute.getAttrValues().getObjectAt(0));
	/**
	 * The input for the archive-time-stamp-v3’s message imprint computation shall be the concatenation (in the
	 * order shown by the list below) of the signed data hash (see bullet 2 below) and certain fields in their
	 * binary encoded
	 * form without any modification and including the tag, length and value octets:
	 */
	final byte[] dataToTimestamp = DSSUtils.concatenate(encodedContentType, signedDataDigest, encodedFields, encodedAtsHashIndex);
	if (LOG.isDebugEnabled()) {
		LOG.debug("eContentType={}", encodedContentType != null ? Utils.toHex(encodedContentType) : encodedContentType);
		LOG.debug("signedDataDigest={}", signedDataDigest != null ? Utils.toHex(signedDataDigest) : signedDataDigest);
		LOG.debug("encodedFields=see above");
		LOG.debug("encodedAtsHashIndex={}", encodedAtsHashIndex != null ? Utils.toHex(encodedAtsHashIndex) : encodedAtsHashIndex);
		LOG.debug("Archive Timestamp Data v3 is: {}", dataToTimestamp != null ? Utils.toHex(dataToTimestamp) : dataToTimestamp);
	}
	return dataToTimestamp;
}
 
Example #26
Source File: TimeStampValidatorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void validateTimeStampToken(byte[] bs, TimeStampToken tsToken) throws InvalidTimeStampException, TechnicalConnectorException {
   byte[] calculatedDigest = ConnectorCryptoUtils.calculateDigest(tsToken.getTimeStampInfo().getMessageImprintAlgOID().getId(), bs);
   byte[] tokenDigestValue = tsToken.getTimeStampInfo().getMessageImprintDigest();
   if (!MessageDigest.isEqual(calculatedDigest, tokenDigestValue)) {
      throw new InvalidTimeStampException("Response for different message imprint digest.");
   } else {
      Attribute scV1 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificate);
      Attribute scV2 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificateV2);
      if (scV1 == null && scV2 == null) {
         throw new InvalidTimeStampException("no signing certificate attribute present.", (Exception)null);
      } else if (scV1 != null && scV2 != null) {
         throw new InvalidTimeStampException("Conflicting signing certificate attributes present.");
      } else {
         this.validateTimeStampToken(tsToken);
      }
   }
}
 
Example #27
Source File: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * The field unsignedAttrsHashIndex is a sequence of octet strings. Each one contains the hash value of one
 * instance of Attribute within unsignedAttrs field of the SignerInfo. A hash value for every instance of
 * Attribute, as present at the time when the corresponding archive time-stamp is requested, shall be included in
 * unsignedAttrsHashIndex. No other hash values shall be included in this field.
 *
 * @param signerInformation {@link SignerInformation}
 * @param atsHashIndexVersionIdentifier {@link ASN1ObjectIdentifier} of the ats-hash-index table version to create
 * @return
 */
private ASN1Sequence getUnsignedAttributesHashIndex(SignerInformation signerInformation, ASN1ObjectIdentifier atsHashIndexVersionIdentifier) {

	final ASN1EncodableVector unsignedAttributesHashIndex = new ASN1EncodableVector();
	AttributeTable unsignedAttributes = signerInformation.getUnsignedAttributes();
	final ASN1EncodableVector asn1EncodableVector = unsignedAttributes.toASN1EncodableVector();
	for (int i = 0; i < asn1EncodableVector.size(); i++) {
		final Attribute attribute = (Attribute) asn1EncodableVector.get(i);
		if (!excludedAttributesFromAtsHashIndex.contains(attribute.getAttrType())) {
			List<DEROctetString> attributeDerOctetStringHashes = getAttributeDerOctetStringHashes(attribute, atsHashIndexVersionIdentifier);
			for (DEROctetString derOctetStringDigest : attributeDerOctetStringHashes) {
				unsignedAttributesHashIndex.add(derOctetStringDigest);
			}
		}
	}
	return new DERSequence(unsignedAttributesHashIndex);
}
 
Example #28
Source File: CalculateDigest.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/57926872/signed-pdf-content-digest-that-was-calculated-during-verification-is-diffrent-th">
 * Signed PDF content digest that was calculated during verification is diffrent than decripted digest from signature
 * </a>
 * <br/>
 * <a href="https://drive.google.com/open?id=1UlOZOp-UYllK7Ra35dggccoWdhcb_Ntp">
 * TEST-signed-pades-baseline-b.pdf
 * </a>
 * <p>
 * The code here demonstrates how to retrieve the messageDigest
 * signed attribute value from a signed PDF. For production use
 * obviously some null checks are required.
 * </p>
 */
@Test
public void testExtractMessageDigestAttributeForUser2893427() throws IOException, CMSException {
    try (   InputStream resource = getClass().getResourceAsStream("TEST-signed-pades-baseline-b.pdf")   ) {
        byte[] bytes = IOUtils.toByteArray(resource);
        PDDocument document = Loader.loadPDF(bytes);
        List<PDSignature> signatures = document.getSignatureDictionaries();
        PDSignature sig = signatures.get(0);
        byte[] cmsBytes = sig.getContents(bytes);
        CMSSignedData cms = new CMSSignedData(cmsBytes);
        SignerInformation signerInformation = cms.getSignerInfos().iterator().next();
        Attribute attribute = signerInformation.getSignedAttributes().get(PKCSObjectIdentifiers.pkcs_9_at_messageDigest);
        ASN1Encodable value = attribute.getAttributeValues()[0];
        System.out.printf("MessageDigest attribute value: %s\n", value);
    }
}
 
Example #29
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates a CMSSignedData from the provided {@code attribute}
 * @param attribute {@link Attribute} to generate {@link CMSSignedData} from
 * @return {@link CMSSignedData}
 * @throws IOException in case of encoding exception
 * @throws CMSException in case if the provided {@code attribute} cannot be converted to {@link CMSSignedData}
 */
public static CMSSignedData getCMSSignedData(Attribute attribute) throws CMSException, IOException {
	ASN1Encodable value = getAsn1Encodable(attribute);
	if (value instanceof DEROctetString) {
		LOG.warn("Illegal content for CMSSignedData (OID : {}) : OCTET STRING is not allowed !", attribute.getAttrType());
	} else {
		ASN1Primitive asn1Primitive = value.toASN1Primitive();
		return new CMSSignedData(asn1Primitive.getEncoded());
	}
	return null;
}
 
Example #30
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns {@code ASN1ObjectIdentifier} of the found AtsHashIndex
 * @param timestampUnsignedAttributes {@link AttributeTable} of the timestamp's unsignedAttributes
 * @return {@link ASN1ObjectIdentifier} of the AtsHashIndex element version
 */
public static ASN1ObjectIdentifier getAtsHashIndexVersionIdentifier(AttributeTable timestampUnsignedAttributes) {
	if (timestampUnsignedAttributes != null) {
		Attributes attributes = timestampUnsignedAttributes.toASN1Structure();
		for (Attribute attribute : attributes.getAttributes()) {
			ASN1ObjectIdentifier attrType = attribute.getAttrType();
			if (id_aa_ATSHashIndex.equals(attrType) || id_aa_ATSHashIndexV2.equals(attrType) || id_aa_ATSHashIndexV3.equals(attrType)) {
				LOG.debug("Unsigned attribute of type [{}] found in the timestamp.", attrType);
				return attrType;
			}
		}
		LOG.warn("The timestamp unsignedAttributes does not contain ATSHashIndex!");
	}
	return null;
}