use of org.bouncycastle.asn1.ocsp.Signature in project signer by demoiselle.
the class CAdESSigner method check.
/**
* Validation is done only on digital signatures with a single signer. Valid
* only with content of type DATA.: OID ContentType 1.2.840.113549.1.9.3 =
* OID Data 1.2.840.113549.1.7.1
*
* @params content Is only necessary to inform if the PKCS7 package is NOT
* ATTACHED type. If it is of type attached, this parameter will be
* replaced by the contents of the PKCS7 package.
* @params signedData Value in bytes of the PKCS7 package, such as the
* contents of a ".p7s" file. It is not only signature as in the
* case of PKCS1.
*/
@SuppressWarnings("unchecked")
// TODO: Implementar validação de co-assinaturas
@Override
@Deprecated
public boolean check(byte[] content, byte[] signedData) throws SignerException {
Security.addProvider(new BouncyCastleProvider());
CMSSignedData cmsSignedData = null;
try {
if (content == null) {
if (this.checkHash) {
cmsSignedData = new CMSSignedData(this.hashes, signedData);
this.checkHash = false;
} else {
cmsSignedData = new CMSSignedData(signedData);
}
} else {
cmsSignedData = new CMSSignedData(new CMSProcessableByteArray(content), signedData);
}
} catch (CMSException ex) {
throw new SignerException(cadesMessagesBundle.getString("error.invalid.bytes.pkcs7"), ex);
}
// Quantidade inicial de assinaturas validadas
int verified = 0;
Store<?> certStore = cmsSignedData.getCertificates();
SignerInformationStore signers = cmsSignedData.getSignerInfos();
Iterator<?> it = signers.getSigners().iterator();
// Realização da verificação básica de todas as assinaturas
while (it.hasNext()) {
try {
SignerInformation signer = (SignerInformation) it.next();
SignerInformationStore s = signer.getCounterSignatures();
SignatureInformations si = new SignatureInformations();
logger.info("Foi(ram) encontrada(s) " + s.size() + " contra-assinatura(s).");
Collection<?> certCollection = certStore.getMatches(signer.getSID());
Iterator<?> certIt = certCollection.iterator();
X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next();
X509Certificate varCert = new JcaX509CertificateConverter().getCertificate(certificateHolder);
PeriodValidator pV = new PeriodValidator();
try {
pV.validate(varCert);
} catch (CertificateValidatorException cve) {
si.getValidatorErrors().add(cve.getMessage());
}
CRLValidator cV = new CRLValidator();
try {
cV.validate(varCert);
} catch (CertificateValidatorCRLException cvce) {
si.getValidatorErrors().add(cvce.getMessage());
}
if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificateHolder))) {
verified++;
logger.info(cadesMessagesBundle.getString("info.signature.valid.seq", verified));
}
// Realiza a verificação dos atributos assinados
logger.info(cadesMessagesBundle.getString("info.signed.attribute"));
AttributeTable signedAttributes = signer.getSignedAttributes();
if ((signedAttributes == null) || (signedAttributes != null && signedAttributes.size() == 0)) {
throw new SignerException(cadesMessagesBundle.getString("error.signed.attribute.table.not.found"));
}
// Realiza a verificação dos atributos não assinados
logger.info(cadesMessagesBundle.getString("info.unsigned.attribute"));
AttributeTable unsignedAttributes = signer.getUnsignedAttributes();
if ((unsignedAttributes == null) || (unsignedAttributes != null && unsignedAttributes.size() == 0)) {
logger.info(cadesMessagesBundle.getString("error.unsigned.attribute.table.not.found"));
}
// Mostra data e hora da assinatura, não é carimbo de tempo
Attribute signingTime = signedAttributes.get(CMSAttributes.signingTime);
Date dataHora = null;
if (signingTime != null) {
dataHora = (((ASN1UTCTime) signingTime.getAttrValues().getObjectAt(0)).getDate());
logger.info(cadesMessagesBundle.getString("info.date.utc", dataHora));
} else {
logger.info(cadesMessagesBundle.getString("info.date.utc", "N/D"));
}
logger.info(cadesMessagesBundle.getString("info.attribute.validation"));
// Valida o atributo ContentType
Attribute attributeContentType = signedAttributes.get(CMSAttributes.contentType);
if (attributeContentType == null) {
throw new SignerException(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType"));
}
if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) {
throw new SignerException(cadesMessagesBundle.getString("error.content.not.data"));
}
// Validando o atributo MessageDigest
Attribute attributeMessageDigest = signedAttributes.get(CMSAttributes.messageDigest);
if (attributeMessageDigest == null) {
throw new SignerException(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "MessageDigest"));
}
// Validando o atributo MessageDigest
Attribute idSigningPolicy = null;
idSigningPolicy = signedAttributes.get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_sigPolicyId.getId()));
if (idSigningPolicy == null) {
throw new SignerException(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "idSigningPolicy"));
}
// Verificando timeStamp
try {
Attribute attributeTimeStamp = null;
attributeTimeStamp = unsignedAttributes.get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId()));
if (attributeTimeStamp != null) {
byte[] varSignature = signer.getSignature();
Timestamp varTimeStampSigner = validateTimestamp(attributeTimeStamp, varSignature);
si.setTimeStampSigner(varTimeStampSigner);
}
} catch (Exception ex) {
// nas assinaturas feitas na applet o unsignedAttributes.get gera exceção.
}
LinkedList<X509Certificate> varChain = (LinkedList<X509Certificate>) CAManager.getInstance().getCertificateChain(varCert);
si.setSignDate(dataHora);
si.setChain(varChain);
si.setSignaturePolicy(signaturePolicy);
this.getSignatureInfo().add(si);
} catch (OperatorCreationException | java.security.cert.CertificateException ex) {
throw new SignerException(ex);
} catch (CMSException ex) {
// When file is mismatch with sign
if (ex instanceof CMSSignerDigestMismatchException)
throw new SignerException(cadesMessagesBundle.getString("error.signature.mismatch"), ex);
else
throw new SignerException(cadesMessagesBundle.getString("error.signature.invalid"), ex);
} catch (ParseException e) {
throw new SignerException(e);
}
}
logger.info(cadesMessagesBundle.getString("info.signature.verified", verified));
// TODO Efetuar o parsing da estrutura CMS
return true;
}
use of org.bouncycastle.asn1.ocsp.Signature in project AndroidAsync by koush.
the class AsyncSSLSocketWrapper method selfSign.
private static Certificate selfSign(KeyPair keyPair, String subjectDN) throws Exception {
Provider bcProvider = new BouncyCastleProvider();
Security.addProvider(bcProvider);
long now = System.currentTimeMillis();
Date startDate = new Date(now);
X500Name dnName = new X500Name("CN=" + subjectDN);
// <-- Using the current timestamp as the certificate serial number
BigInteger certSerialNumber = new BigInteger(Long.toString(now));
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
// <-- 1 Yr validity
calendar.add(Calendar.YEAR, 1);
Date endDate = calendar.getTime();
// <-- Use appropriate signature algorithm based on your keyPair algorithm.
String signatureAlgorithm = "SHA256WithRSA";
ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate());
JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(dnName, certSerialNumber, startDate, endDate, dnName, keyPair.getPublic());
// Extensions --------------------------
// Basic Constraints
// <-- true for CA, false for EndEntity
BasicConstraints basicConstraints = new BasicConstraints(true);
// Basic Constraints is usually marked as critical.
certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints);
return new JcaX509CertificateConverter().setProvider(bcProvider).getCertificate(certBuilder.build(contentSigner));
}
use of org.bouncycastle.asn1.ocsp.Signature in project ddf by codice.
the class OcspChecker method logResponse.
private void logResponse(OCSPResp response) {
BasicOCSPResp basicOCSPResp;
BasicOCSPResponse basicOCSPResponse;
try {
basicOCSPResp = (BasicOCSPResp) response.getResponseObject();
basicOCSPResponse = BasicOCSPResponse.getInstance(((BasicOCSPResp) response.getResponseObject()).getEncoded());
StringBuilder logBuilder = new StringBuilder();
logBuilder.append("OCSP Response: \n");
logBuilder.append(" responseStatus: " + getValueOrDefault(response.getStatus(), "") + "\n");
logBuilder.append(" responseBytes:\n");
logBuilder.append(" responseType: " + getValueOrDefault(basicOCSPResponse, "").getClass().getSimpleName() + "\n");
logBuilder.append(" response:\n");
logBuilder.append(" tbsResponseData:\n");
if (basicOCSPResponse.getTbsResponseData() != null) {
logBuilder.append(" version: " + getValueOrDefault(basicOCSPResponse.getTbsResponseData().getVersion(), "").toString() + "\n");
logBuilder.append(" responderId:\n");
if (basicOCSPResponse.getTbsResponseData().getResponderID() != null) {
logBuilder.append(" byName: " + getValueOrDefault(basicOCSPResponse.getTbsResponseData().getResponderID().getName(), "").toString() + "\n");
logBuilder.append(" byKey: " + getValueOrDefault(Arrays.toString(basicOCSPResponse.getTbsResponseData().getResponderID().getKeyHash()), "") + "\n");
} else {
logBuilder.append(" byName:\n");
}
if (basicOCSPResponse.getTbsResponseData().getProducedAt() != null) {
logBuilder.append(" producedAt: " + getValueOrDefault(basicOCSPResponse.getTbsResponseData().getProducedAt().getTimeString(), "") + "\n");
} else {
logBuilder.append(" producedAt:\n");
}
}
logBuilder.append(" responses:\n");
if (basicOCSPResp.getResponses() != null) {
SingleResp[] singleResps = basicOCSPResp.getResponses();
for (int i = 0; i < singleResps.length; i++) {
CertificateID certificateID = singleResps[i].getCertID();
if (certificateID != null) {
logBuilder.append(" certID #: " + i + "\n");
logBuilder.append(" hashAlgorithm: " + getValueOrDefault(certificateID.getHashAlgOID(), "").toString() + "\n");
logBuilder.append(" issuerNameHash: " + getValueOrDefault(Arrays.toString(certificateID.getIssuerNameHash()), "") + "\n");
logBuilder.append(" issuerKeyHash: " + getValueOrDefault(Arrays.toString(certificateID.getIssuerKeyHash()), "") + "\n");
logBuilder.append(" cert serial number: " + getValueOrDefault(certificateID.getSerialNumber(), "") + "\n");
logBuilder.append(" certStatus: " + getValueOrDefault(singleResps[i].getCertStatus(), "good").getClass().getSimpleName() + "\n");
logBuilder.append(" thisUpdate: " + getValueOrDefault(singleResps[i].getThisUpdate(), "").toString() + "\n");
logBuilder.append(" nextUpdate: " + getValueOrDefault(singleResps[i].getNextUpdate(), "").toString() + "\n");
}
}
}
if (basicOCSPResp.getSignatureAlgorithmID() != null) {
logBuilder.append(" signatureAlgorithm: " + getValueOrDefault(basicOCSPResp.getSignatureAlgorithmID().getAlgorithm(), "").toString() + "\n");
}
logBuilder.append(" signature: " + getValueOrDefault(Arrays.toString(basicOCSPResp.getSignature()), "") + "\n");
logBuilder.append(" certs:\n");
if (basicOCSPResp.getCerts() != null) {
X509CertificateHolder[] x509CertificateHolders = basicOCSPResp.getCerts();
for (int i = 0; i < x509CertificateHolders.length; i++) {
logBuilder.append(" certificate: " + i + "\n");
logBuilder.append(" issuer: " + getValueOrDefault(x509CertificateHolders[i].getIssuer(), "").toString() + "\n");
logBuilder.append(" subject: " + getValueOrDefault(x509CertificateHolders[i].getSubject(), "").toString() + "\n");
if (basicOCSPResp.getSignatureAlgorithmID() != null) {
logBuilder.append(" signatureAlgorithm: " + getValueOrDefault(x509CertificateHolders[i].getSignatureAlgorithm().getAlgorithm(), "").toString() + "\n");
}
logBuilder.append(" start date: " + getValueOrDefault(x509CertificateHolders[i].toASN1Structure().getStartDate(), "").toString() + "\n");
logBuilder.append(" end date: " + getValueOrDefault(x509CertificateHolders[i].toASN1Structure().getEndDate(), "").toString() + "\n");
logBuilder.append(" cert serial number: " + getValueOrDefault(x509CertificateHolders[i].getSerialNumber(), "") + "\n");
}
}
LOGGER.trace(logBuilder.toString());
} catch (IOException | OCSPException e) {
LOGGER.trace("Could not log response, issue converting response to a BasicOcspResponse.", e);
}
}
use of org.bouncycastle.asn1.ocsp.Signature in project athenz by yahoo.
the class CryptoTest method testSignVerifyExtractedECKey.
@Test
public void testSignVerifyExtractedECKey() {
PrivateKey privateKey = Crypto.loadPrivateKey(ecPrivateKey);
assertNotNull(privateKey);
String signature = Crypto.sign(serviceToken, privateKey);
PublicKey publicKey = Crypto.extractPublicKey(privateKey);
assertNotNull(publicKey);
assertTrue(Crypto.verify(serviceToken, publicKey, signature));
}
use of org.bouncycastle.asn1.ocsp.Signature in project athenz by yahoo.
the class CryptoTest method testSignVerifyRSAKey.
@Test
public void testSignVerifyRSAKey() {
PrivateKey privateKey = Crypto.loadPrivateKey(rsaPrivateKey);
assertNotNull(privateKey);
String signature = Crypto.sign(serviceToken, privateKey);
assertEquals(signature, serviceRSASignature);
PublicKey publicKey = Crypto.loadPublicKey(rsaPublicKey);
assertNotNull(publicKey);
assertTrue(Crypto.verify(serviceToken, publicKey, signature));
}
Aggregations