Example usage for java.security.cert X509Certificate getPublicKey

List of usage examples for java.security.cert X509Certificate getPublicKey

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getPublicKey.

Prototype

public abstract PublicKey getPublicKey();

Source Link

Document

Gets the public key from this certificate.

Usage

From source file:org.keycloak.adapters.saml.rotation.SamlDescriptorPublicKeyLocator.java

private synchronized PublicKey refreshCertificateCacheAndGet(String kid) {
    if (this.descriptorUrl == null) {
        return null;
    }/*from  w  w w  . j  ava  2s .co m*/

    this.lastRequestTime = Time.currentTime();

    LOG.debugf("Refreshing public key cache from %s", this.descriptorUrl);
    List<KeyInfo> signingCerts;
    try {
        MultivaluedHashMap<String, KeyInfo> certs = HttpAdapterUtils.downloadKeysFromSamlDescriptor(client,
                this.descriptorUrl);
        signingCerts = certs.get(KeyTypes.SIGNING.value());
    } catch (HttpClientAdapterException ex) {
        LOG.error("Could not refresh certificates from the server", ex);
        return null;
    }

    if (signingCerts == null) {
        return null;
    }

    LOG.debugf("Certificates retrieved from server, filling public key cache");

    // Only clear cache after it is certain that the SAML descriptor has been read successfully
    this.publicKeyCache.clear();

    for (KeyInfo ki : signingCerts) {
        KeyName keyName = KeyInfoTools.getKeyName(ki);
        X509Certificate x509certificate = KeyInfoTools.getX509Certificate(ki);
        try {
            x509certificate.checkValidity();
        } catch (CertificateException ex) {
            x509certificate = null;
        }
        if (x509certificate != null && keyName != null) {
            LOG.tracef("Registering signing certificate %s", keyName.getName());
            this.publicKeyCache.put(keyName.getName(), x509certificate.getPublicKey());
        } else {
            LOG.tracef("Ignoring certificate %s: %s", keyName, x509certificate);
        }

    }

    return (kid == null ? null : this.publicKeyCache.get(kid));
}

From source file:com.xwiki.authentication.sts.STSTokenValidator.java

/**
  * validateToken(SignableSAMLObject samlToken)
  * Validates Token from SAMLlObject - returns boolen
  * Validates Token - exitracting sertificate from samlToken.
  * And validates it. Returning true or false according on validation results.
  * @param samlToken SignableSAMLObject/*from   w ww . ja v a  2  s.c  o  m*/
  * @return boolean valid => true, not valid => false
  */
private static boolean validateToken(SignableSAMLObject samlToken)
        throws SecurityException, ValidationException, ConfigurationException, UnmarshallingException,
        CertificateException, KeyException {

    // Validate XML structure
    samlToken.validate(true);

    Signature signature = samlToken.getSignature();
    X509Certificate certificate = certFromToken(samlToken);

    // Certificate data
    log.debug("certificate issuerDN: " + certificate.getIssuerDN());
    log.debug("certificate issuerUniqueID: " + certificate.getIssuerUniqueID());
    log.debug("certificate issuerX500Principal: " + certificate.getIssuerX500Principal());
    log.debug("certificate notBefore: " + certificate.getNotBefore());
    log.debug("certificate notAfter: " + certificate.getNotAfter());
    log.debug("certificate serialNumber: " + certificate.getSerialNumber());
    log.debug("certificate sigAlgName: " + certificate.getSigAlgName());
    log.debug("certificate sigAlgOID: " + certificate.getSigAlgOID());
    log.debug("certificate signature: " + new String(certificate.getSignature()));
    log.debug("certificate issuerX500Principal: " + certificate.getIssuerX500Principal().toString());
    log.debug("certificate publicKey: " + certificate.getPublicKey());
    log.debug("certificate subjectDN: " + certificate.getSubjectDN());
    log.debug("certificate sigAlgOID: " + certificate.getSigAlgOID());
    log.debug("certificate version: " + certificate.getVersion());

    BasicX509Credential cred = new BasicX509Credential();
    cred.setEntityCertificate(certificate);

    // Credential data
    cred.setEntityId(entityId);
    log.debug("cred entityId: " + cred.getEntityId());
    log.debug("cred usageType: " + cred.getUsageType());
    log.debug("cred credentalContextSet: " + cred.getCredentalContextSet());
    log.debug("cred hashCode: " + cred.hashCode());
    log.debug("cred privateKey: " + cred.getPrivateKey());
    log.debug("cred publicKey: " + cred.getPublicKey());
    log.debug("cred secretKey: " + cred.getSecretKey());
    log.debug("cred entityCertificateChain: " + cred.getEntityCertificateChain());

    ArrayList<Credential> trustedCredentials = new ArrayList<Credential>();
    trustedCredentials.add(cred);

    CollectionCredentialResolver credResolver = new CollectionCredentialResolver(trustedCredentials);
    KeyInfoCredentialResolver kiResolver = SecurityTestHelper.buildBasicInlineKeyInfoResolver();
    ExplicitKeySignatureTrustEngine engine = new ExplicitKeySignatureTrustEngine(credResolver, kiResolver);

    CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.add(new EntityIDCriteria(entityId));

    Base64 decoder = new Base64();
    // In trace mode write certificate in the file
    if (log.isTraceEnabled()) {
        String certEncoded = new String(decoder.encode(certificate.getEncoded()));
        try {
            FileUtils.writeStringToFile(new File("/tmp/Certificate.cer"),
                    "-----BEGIN CERTIFICATE-----\n" + certEncoded + "\n-----END CERTIFICATE-----");
            log.trace("Certificate file was saved in: /tmp/Certificate.cer");
        } catch (IOException e1) {
            log.error(e1);
        }
    }
    return engine.validate(signature, criteriaSet);
}

From source file:com.vmware.demo.SamlService.java

public String validateSAMLResponse(String samlResponse, String samlCert) throws Exception {
    String decodedString = "";
    try {//from  w ww.  ja v  a 2s  . co m
        decodedString = decodeSAMLResponse(samlResponse);
        InputStream inputStream = new ByteArrayInputStream(decodedString.getBytes("UTF-8"));

        // Parse XML
        BasicParserPool parserPoolManager = new BasicParserPool();
        parserPoolManager.setNamespaceAware(true);
        parserPoolManager.setIgnoreElementContentWhitespace(true);
        Document document = parserPoolManager.parse(inputStream);
        Element metadataRoot = document.getDocumentElement();

        QName qName = new QName(metadataRoot.getNamespaceURI(), metadataRoot.getLocalName(),
                metadataRoot.getPrefix());

        // Unmarshall document
        Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(qName);
        Response response = (Response) unmarshaller.unmarshall(metadataRoot);
        Issuer issuer = response.getIssuer();
        logger.info("Parsed response.  Issued:" + response.getIssueInstant().toString() + ", issuer: "
                + issuer.getValue());

        java.security.cert.X509Certificate jX509Cert = SamlUtils.parsePemCertificate(samlCert);
        if (null == jX509Cert) {
            logger.info("Failed to parse cert. " + samlCert);
            return "";
        }

        PublicKey publicCert = jX509Cert.getPublicKey();
        logger.info("Extracted cert.  Cert:" + publicCert);
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicCert.getEncoded());

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
        logger.debug("Key created by provider: " + keyFactory.getProvider().toString());

        // Setup validation
        BasicX509Credential publicCredential = new BasicX509Credential();
        publicCredential.setPublicKey(publicKey);
        SignatureValidator signatureValidator = new SignatureValidator(publicCredential);
        Signature signature = response.getSignature();

        // Validate
        try {
            signatureValidator.validate(signature);
            logger.info("Assertion signature validated.");
        } catch (ValidationException e) {
            logger.error("Failed to validate signature of assertion", e);
            throw e;
        }

        // Get decryption key
        RSAPrivateKey privateKey = null;
        BasicX509Credential decryptionCredential = new BasicX509Credential();
        decryptionCredential.setPrivateKey(privateKey);
        StaticKeyInfoCredentialResolver skicr = new StaticKeyInfoCredentialResolver(decryptionCredential);

        // Decrypt assertion
        Decrypter decrypter = new Decrypter(null, skicr, new InlineEncryptedKeyResolver());
        if (response.getEncryptedAssertions().isEmpty()) {
            logger.info("Nothing to decrypt in assertion.");
        } else {
            Assertion decryptedAssertion;
            try {
                decryptedAssertion = decrypter.decrypt(response.getEncryptedAssertions().get(0));
                logger.info("Assertion decryption succeeded.");
            } catch (DecryptionException e) {
                logger.error("Failed to decrypt assertion", e);
                throw e;
            }

            // Extract attributes, log in output
            List<AttributeStatement> attributeStatements = decryptedAssertion.getAttributeStatements();
            for (int i = 0; i < attributeStatements.size(); i++) {
                List<Attribute> attributes = attributeStatements.get(i).getAttributes();
                for (int x = 0; x < attributes.size(); x++) {
                    String strAttributeName = attributes.get(x).getDOM().getAttribute("Name");

                    List<XMLObject> attributeValues = attributes.get(x).getAttributeValues();
                    for (int y = 0; y < attributeValues.size(); y++) {
                        String strAttributeValue = attributeValues.get(y).getDOM().getTextContent();
                        logger.info(strAttributeName + " = " + strAttributeValue);
                    }
                }
            }
        }
    } catch (Exception ex) {
        logger.error("Failed to validate assertion", ex);
        throw ex;
    }
    return decodedString;
}

From source file:mitm.application.djigzo.relay.RelayHandler.java

private void verifySignature(SignerInfo signer, X509Certificate signingCertificate) throws RelayException {
    try {//  ww w  .  ja va  2  s  . c om
        /* 
         * check if the message can be verified using the public key of the signer. 
         */
        if (!signer.verify(signingCertificate.getPublicKey())) {
            throw new SignerInfoException("Message content cannot be verified with the signers public key.");
        }
    } catch (SignerInfoException e) {
        throw new RelayException(RelayStep.INVALID_SIGNATURE, INVALID_SIGNATURE, e);
    }
}

From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java

private Boolean isValidSignature(String tokenString, byte[] signature) {

    Boolean isValid = false;//  www .  j a  va2s  . c o  m

    File lterCert = ConfigurationListener.getLterCertificate();

    try {

        FileInputStream certFis = new FileInputStream(lterCert);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(certFis);

        PublicKey pubKey = cert.getPublicKey();

        Signature sig = Signature.getInstance("MD5withRSA");
        sig.initVerify(pubKey);

        sig.update(tokenString.getBytes());
        isValid = sig.verify(signature);

    } catch (FileNotFoundException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    } catch (CertificateException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    } catch (SignatureException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    }

    return isValid;

}

From source file:com.amazonaws.ipnreturnurlvalidation.SignatureUtilsForOutbound.java

/**
 * Verifies the signature using PKI.// w  w  w .  j  a va2 s. c  om
 */
private boolean validateSignatureV2(Map<String, String> parameters, String urlEndPoint, String httpMethod)
        throws SignatureException {

    // 1. input validation.
    String signature = parameters.get(SIGNATURE_KEYNAME);
    if (signature == null) {
        throw new SignatureException("'signature' is missing from the parameters.");
    }

    String signatureMethod = parameters.get(SIGNATURE_METHOD_KEYNAME);
    if (signatureMethod == null) {
        throw new SignatureException("'signatureMethod' is missing from the parameters.");
    }

    String signatureAlgorithm = getSignatureAlgorithm(signatureMethod);
    if (signatureAlgorithm == null) {
        throw new SignatureException("'signatureMethod' present in parameters is invalid. "
                + "Valid signatureMethods are : 'RSA-SHA1'");
    }

    String certificateUrl = parameters.get(CERTIFICATE_URL_KEYNAME);
    if (certificateUrl == null) {
        throw new SignatureException("'certificateUrl' is missing from the parameters.");
    }

    String certificate = getPublicKeyCertificateAsString(certificateUrl);
    if (certificate == null) {
        throw new SignatureException("public key certificate could not fetched from url: " + certificateUrl);
    }

    // 2. calculating the string to sign
    String stringToSign = EMPTY_STRING;
    try {
        URL url = new URL(urlEndPoint);
        String hostHeader = getHostHeader(url);
        String requestURI = getRequestURI(url);
        stringToSign = calculateStringToSignV2(parameters, httpMethod, hostHeader, requestURI);
    } catch (MalformedURLException e) {
        throw new SignatureException(e);
    }

    // 3. verify signature
    try {
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        X509Certificate x509Certificate = (X509Certificate) factory
                .generateCertificate(new ByteArrayInputStream(certificate.getBytes()));
        Signature signatureInstance = Signature.getInstance(signatureAlgorithm);
        signatureInstance.initVerify(x509Certificate.getPublicKey());
        signatureInstance.update(stringToSign.getBytes(UTF_8_Encoding));
        return signatureInstance.verify(Base64.decodeBase64(signature.getBytes()));
    } catch (CertificateException e) {
        throw new SignatureException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new SignatureException(e);
    } catch (InvalidKeyException e) {
        throw new SignatureException(e);
    } catch (UnsupportedEncodingException e) {
        throw new SignatureException(e);
    }
}

From source file:edu.ucsb.eucalyptus.transport.query.WalrusQuerySecurityHandler.java

public UserInfo handle(String addr, String verb, Map<String, String> parameters, Map<String, String> headers)
        throws QuerySecurityException {
    CaseInsensitiveMap hdrs = new CaseInsensitiveMap(headers);

    //this.checkParameters( hdrs );
    //:: check the signature :://

    if (hdrs.containsKey(StorageQuerySecurityHandler.StorageSecurityParameters.EucaSignature)) {
        //possible internal request -- perform authentication using internal credentials
        String date = (String) hdrs.remove(SecurityParameter.Date);
        String eucaCert = (String) hdrs.remove(StorageQuerySecurityHandler.StorageSecurityParameters.EucaCert);
        String signature = (String) hdrs
                .remove(StorageQuerySecurityHandler.StorageSecurityParameters.EucaSignature);
        String data = verb + "\n" + date + "\n" + addr + "\n";

        Signature sig;//from   w  w w  .j  a v  a2s.c om
        boolean valid = false;
        try {
            byte[] bytes = Base64.decode(eucaCert);
            String certString = new String(bytes);
            PEMReader pemReader = new PEMReader(new StringReader(certString));
            X509Certificate cert = (X509Certificate) pemReader.readObject();
            AbstractKeyStore keyStore = ServiceKeyStore.getInstance();
            if (keyStore.getCertificateAlias(cert) != null) {
                //cert found in keystore
                PublicKey publicKey = cert.getPublicKey();
                sig = Signature.getInstance("SHA1withRSA");

                sig.initVerify(publicKey);
                sig.update(data.getBytes());
                valid = sig.verify(Base64.decode(signature));
            } else {
                LOG.warn("WalrusQuerySecurityHandler(): certificate not found in keystore");
            }
        } catch (Exception ex) {
            LOG.warn("Authentication exception: " + ex.getMessage());
            ex.printStackTrace();
        }

        if (!valid) {
            throw new QuerySecurityException("User authentication failed.");
        }
        //run as admin
        UserInfo admin = new UserInfo(EucalyptusProperties.NAME);
        admin.setIsAdministrator(Boolean.TRUE);
        return admin;
    } else if (hdrs.containsKey(WalrusProperties.FormField.FormUploadPolicyData)) {
        String data = (String) hdrs.remove(WalrusProperties.FormField.FormUploadPolicyData);
        String auth_part = (String) hdrs.remove(SecurityParameter.Authorization);

        if (auth_part != null) {
            String sigString[] = getSigInfo(auth_part);
            String signature = sigString[1];
            return getUserInfo(sigString[0], signature, data, false);
        }
        throw new QuerySecurityException("User authentication failed.");
    } else {
        //external user request
        String date;
        String verifyDate;
        if (hdrs.containsKey("x-amz-date")) {
            date = "";
            verifyDate = (String) hdrs.get("x-amz-date");
        } else {
            date = (String) hdrs.remove(SecurityParameter.Date);
            verifyDate = date;
            if (date == null || date.length() <= 0)
                throw new QuerySecurityException("User authentication failed. Date must be specified.");
        }

        try {
            Date dateToVerify = DateUtil.parseDate(verifyDate);
            Date currentDate = new Date();
            if (Math.abs(currentDate.getTime() - dateToVerify.getTime()) > EXPIRATION_LIMIT)
                throw new QuerySecurityException("Message expired. Sorry.");
        } catch (Exception ex) {
            throw new QuerySecurityException("Unable to parse date.");
        }
        String content_md5 = (String) hdrs.remove("Content-MD5");
        content_md5 = content_md5 == null ? "" : content_md5;
        String content_type = (String) hdrs.remove("Content-Type");
        content_type = content_type == null ? "" : content_type;

        String[] addrStrings = addr.split("\\?");
        String addrString = addrStrings[0];

        if (addrStrings.length > 1) {
            for (SubResource subResource : SubResource.values()) {
                if (addr.endsWith(subResource.toString())) {
                    addrString += "?" + subResource.toString();
                    break;
                }
            }
        }

        String data = verb + "\n" + content_md5 + "\n" + content_type + "\n" + date + "\n"
                + getCanonicalizedAmzHeaders(hdrs) + addrString;

        String auth_part = hdrs.remove(SecurityParameter.Authorization);

        if (auth_part != null) {
            String sigString[] = getSigInfo(auth_part);
            String signature = sigString[1];
            return getUserInfo(sigString[0], signature, data, false);
        } else if (parameters.containsKey(SecurityParameter.AWSAccessKeyId.toString())) {
            //query string authentication
            String accesskeyid = parameters.remove(SecurityParameter.AWSAccessKeyId.toString());
            try {
                String signature = URLDecoder.decode(parameters.remove(SecurityParameter.Signature.toString()),
                        "UTF-8");
                if (signature == null) {
                    throw new QuerySecurityException("User authentication failed. Null signature.");
                }
                String expires = parameters.remove(SecurityParameter.Expires.toString());
                if (expires == null) {
                    throw new QuerySecurityException("Authentication failed. Expires must be specified.");
                }
                if (checkExpires(expires)) {
                    String stringToSign = verb + "\n" + content_md5 + "\n" + content_type + "\n"
                            + Long.parseLong(expires) + "\n" + getCanonicalizedAmzHeaders(hdrs) + addrString;
                    return getUserInfo(accesskeyid, signature, stringToSign, true);
                } else {
                    throw new QuerySecurityException("Cannot process request. Expired.");
                }
            } catch (Exception ex) {
                throw new QuerySecurityException("Could not verify request " + ex.getMessage());
            }
        } else {
            //anonymous request
            return null;
        }
    }
}

From source file:org.guanxi.idp.service.SSOBase.java

/**
 * Adds encrypted assertions to a SAML2 Response
 *
 * @param encryptionCert the X509 certificate to use for encrypting the assertions
 * @param assertionDoc the assertions to encrypt
 * @param responseDoc the SAML2 Response to add the encrypted assertions to
 * @throws GuanxiException if an error occurs
 *///from ww  w. j  ava2 s . co m
protected void addEncryptedAssertionsToResponse(X509Certificate encryptionCert, AssertionDocument assertionDoc,
        ResponseDocument responseDoc) throws GuanxiException {
    try {
        PublicKey keyEncryptKey = encryptionCert.getPublicKey();

        // Generate a secret key
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        SecretKey secretKey = keyGenerator.generateKey();

        XMLCipher keyCipher = XMLCipher.getInstance(XMLCipher.RSA_OAEP);
        keyCipher.init(XMLCipher.WRAP_MODE, keyEncryptKey);

        Document domAssertionDoc = (Document) assertionDoc.newDomNode(xmlOptions);
        EncryptedKey encryptedKey = keyCipher.encryptKey(domAssertionDoc, secretKey);

        Element elementToEncrypt = domAssertionDoc.getDocumentElement();

        XMLCipher xmlCipher = XMLCipher.getInstance(XMLCipher.AES_128);
        xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);

        // Add KeyInfo to the EncryptedData element
        EncryptedData encryptedDataElement = xmlCipher.getEncryptedData();
        KeyInfo keyInfo = new KeyInfo(domAssertionDoc);
        keyInfo.add(encryptedKey);
        encryptedDataElement.setKeyInfo(keyInfo);

        // Encrypt the assertion
        xmlCipher.doFinal(domAssertionDoc, elementToEncrypt, false);

        // Go back into XMLBeans land...
        EncryptedDataDocument encryptedDataDoc = EncryptedDataDocument.Factory.parse(domAssertionDoc);
        // ...and add the encrypted assertion to the response
        responseDoc.getResponse().addNewEncryptedAssertion()
                .setEncryptedData(encryptedDataDoc.getEncryptedData());

        // Look for the Response/EncryptedAssertion/EncryptedData/KeyInfo/EncryptedKey node...
        EncryptedDataType encryptedData = responseDoc.getResponse().getEncryptedAssertionArray(0)
                .getEncryptedData();
        NodeList nodes = encryptedData.getKeyInfo().getDomNode().getChildNodes();
        Node encryptedKeyNode = null;
        for (int c = 0; c < nodes.getLength(); c++) {
            encryptedKeyNode = nodes.item(c);
            if (encryptedKeyNode.getLocalName() != null) {
                if (encryptedKeyNode.getLocalName().equals("EncryptedKey"))
                    break;
            }
        }

        // ...get a new KeyInfo ready...
        KeyInfoDocument keyInfoDoc = KeyInfoDocument.Factory.newInstance();
        X509DataType x509Data = keyInfoDoc.addNewKeyInfo().addNewX509Data();

        // ...and a useable version of the SP's encryption certificate...
        StringWriter sw = new StringWriter();
        PEMWriter pemWriter = new PEMWriter(sw);
        pemWriter.writeObject(encryptionCert);
        pemWriter.close();
        String x509 = sw.toString();
        x509 = x509.replaceAll("-----BEGIN CERTIFICATE-----", "");
        x509 = x509.replaceAll("-----END CERTIFICATE-----", "");

        // ...add the encryption cert to the new KeyInfo...
        x509Data.addNewX509Certificate().setStringValue(x509);

        // ...and insert it into Response/EncryptedAssertion/EncryptedData/KeyInfo/EncryptedKey
        encryptedKeyNode.appendChild(
                encryptedKeyNode.getOwnerDocument().importNode(keyInfoDoc.getKeyInfo().getDomNode(), true));
    } catch (NoSuchAlgorithmException nsae) {
        logger.error("AES encryption not available");
        throw new GuanxiException(nsae);
    } catch (XMLEncryptionException xea) {
        logger.error("RSA_OAEP error with WRAP_MODE");
        throw new GuanxiException(xea);
    } catch (Exception e) {
        logger.error("Error encyrpting the assertion");
        throw new GuanxiException(e);
    }
}

From source file:eu.europa.esig.dss.pades.InfiniteLoopDSS621Test.java

/**
 * These signatures are invalid because of non ordered  signed attributes
 *///from  w  ww.  j av a 2  s  . c  om
@Test
public void manualTest() throws Exception {

    File pdfFile = new File(FILE_PATH);

    FileInputStream fis = new FileInputStream(pdfFile);
    byte[] pdfBytes = IOUtils.toByteArray(fis);

    PDDocument document = PDDocument.load(pdfFile);
    List<PDSignature> signatures = document.getSignatureDictionaries();
    assertEquals(6, signatures.size());

    int idx = 0;
    for (PDSignature pdSignature : signatures) {
        byte[] contents = pdSignature.getContents(pdfBytes);
        byte[] signedContent = pdSignature.getSignedContent(pdfBytes);

        logger.info("Byte range : " + Arrays.toString(pdSignature.getByteRange()));

        IOUtils.write(contents, new FileOutputStream("target/sig" + (idx++) + ".p7s"));

        ASN1InputStream asn1sInput = new ASN1InputStream(contents);
        ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

        logger.info("SEQ : " + asn1Seq.toString());

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
        assertEquals(PKCSObjectIdentifiers.signedData, oid);

        SignedData signedData = SignedData
                .getInstance(DERTaggedObject.getInstance(asn1Seq.getObjectAt(1)).getObject());

        ASN1Set digestAlgorithmSet = signedData.getDigestAlgorithms();
        ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier
                .getInstance(ASN1Sequence.getInstance(digestAlgorithmSet.getObjectAt(0)).getObjectAt(0));
        DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(oidDigestAlgo.getId());
        logger.info("DIGEST ALGO : " + digestAlgorithm);

        ContentInfo encapContentInfo = signedData.getEncapContentInfo();
        ASN1ObjectIdentifier contentTypeOID = encapContentInfo.getContentType();
        logger.info("ENCAPSULATED CONTENT INFO TYPE : " + contentTypeOID);

        if (!PKCSObjectIdentifiers.id_ct_TSTInfo.equals(contentTypeOID)) { // If not timestamp
            assertEquals(PKCSObjectIdentifiers.data, contentTypeOID);

            ASN1Encodable content = encapContentInfo.getContent();
            logger.info("ENCAPSULATED CONTENT INFO CONTENT : " + content);
            assertNull(content);

            List<X509Certificate> certificates = extractCertificates(signedData);

            ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
            logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
            SignerInfo signedInfo = SignerInfo
                    .getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)));

            ASN1Set authenticatedAttributeSet = signedInfo.getAuthenticatedAttributes();
            logger.info("AUTHENTICATED ATTR : " + authenticatedAttributeSet);

            Attribute attributeDigest = null;
            for (int i = 0; i < authenticatedAttributeSet.size(); i++) {
                Attribute attribute = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(i));
                if (PKCSObjectIdentifiers.pkcs_9_at_messageDigest.equals(attribute.getAttrType())) {
                    attributeDigest = attribute;
                    break;
                }
            }

            assertNotNull(attributeDigest);

            ASN1OctetString asn1ObjString = ASN1OctetString
                    .getInstance(attributeDigest.getAttrValues().getObjectAt(0));
            String embeddedDigest = Base64.encode(asn1ObjString.getOctets());
            logger.info("MESSAGE DIGEST : " + embeddedDigest);

            byte[] digestSignedContent = DSSUtils.digest(digestAlgorithm, signedContent);
            String computedDigestSignedContentEncodeBase64 = Base64.encode(digestSignedContent);
            logger.info("COMPUTED DIGEST SIGNED CONTENT BASE64 : " + computedDigestSignedContentEncodeBase64);
            assertEquals(embeddedDigest, computedDigestSignedContentEncodeBase64);

            SignerIdentifier sid = signedInfo.getSID();
            logger.info("SIGNER IDENTIFIER : " + sid.getId());

            IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber
                    .getInstance(signedInfo.getSID());
            ASN1Integer signerSerialNumber = issuerAndSerialNumber.getSerialNumber();
            logger.info("ISSUER AND SN : " + issuerAndSerialNumber.getName() + " " + signerSerialNumber);

            BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();
            X509Certificate signerCertificate = null;
            for (X509Certificate x509Certificate : certificates) {
                if (serial.equals(x509Certificate.getSerialNumber())) {
                    signerCertificate = x509Certificate;
                }
            }
            assertNotNull(signerCertificate);

            String algorithm = signerCertificate.getPublicKey().getAlgorithm();
            EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(algorithm);

            ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest();
            String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets());

            logger.info("SIGNATURE VALUE : " + signatureValue);

            Cipher cipher = Cipher.getInstance(encryptionAlgorithm.getName());
            cipher.init(Cipher.DECRYPT_MODE, signerCertificate);
            byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets());

            ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted);

            ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject();
            logger.info("DECRYPTED : " + seqDecrypt);

            DigestInfo digestInfo = new DigestInfo(seqDecrypt);
            assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm());

            String decryptedDigestEncodeBase64 = Base64.encode(digestInfo.getDigest());
            logger.info("DECRYPTED BASE64 : " + decryptedDigestEncodeBase64);

            byte[] encoded = authenticatedAttributeSet.getEncoded();
            byte[] digest = DSSUtils.digest(digestAlgorithm, encoded);
            String computedDigestFromSignatureEncodeBase64 = Base64.encode(digest);
            logger.info("COMPUTED DIGEST FROM SIGNATURE BASE64 : " + computedDigestFromSignatureEncodeBase64);

            assertEquals(decryptedDigestEncodeBase64, computedDigestFromSignatureEncodeBase64);

            IOUtils.closeQuietly(inputDecrypted);

        }

        IOUtils.closeQuietly(asn1sInput);
    }

    IOUtils.closeQuietly(fis);
    document.close();
}

From source file:eu.europa.esig.dss.pades.signature.PAdESLevelBTest.java

@Override
protected void onDocumentSigned(byte[] byteArray) {
    try {/*  w w w. ja  v a  2s .com*/
        InputStream inputStream = new ByteArrayInputStream(byteArray);

        PDDocument document = PDDocument.load(inputStream);
        List<PDSignature> signatures = document.getSignatureDictionaries();
        assertEquals(1, signatures.size());

        for (PDSignature pdSignature : signatures) {
            byte[] contents = pdSignature.getContents(byteArray);
            byte[] signedContent = pdSignature.getSignedContent(byteArray);

            logger.info("Byte range : " + Arrays.toString(pdSignature.getByteRange()));

            //IOUtils.write(contents, new FileOutputStream("sig.p7s"));

            ASN1InputStream asn1sInput = new ASN1InputStream(contents);
            ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

            logger.info("SEQ : " + asn1Seq.toString());

            ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
            assertEquals(PKCSObjectIdentifiers.signedData, oid);

            SignedData signedData = SignedData
                    .getInstance(DERTaggedObject.getInstance(asn1Seq.getObjectAt(1)).getObject());

            ASN1Set digestAlgorithmSet = signedData.getDigestAlgorithms();
            ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier
                    .getInstance(ASN1Sequence.getInstance(digestAlgorithmSet.getObjectAt(0)).getObjectAt(0));
            DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(oidDigestAlgo.getId());
            logger.info("DIGEST ALGO : " + digestAlgorithm);

            ContentInfo encapContentInfo = signedData.getEncapContentInfo();
            ASN1ObjectIdentifier contentTypeOID = encapContentInfo.getContentType();
            logger.info("ENCAPSULATED CONTENT INFO TYPE : " + contentTypeOID);
            assertEquals(PKCSObjectIdentifiers.data, contentTypeOID);

            ASN1Encodable content = encapContentInfo.getContent();
            logger.info("ENCAPSULATED CONTENT INFO CONTENT : " + content);
            assertNull(content);

            List<X509Certificate> certificates = extractCertificates(signedData);

            ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
            logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
            SignerInfo signedInfo = SignerInfo
                    .getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)));

            ASN1Set authenticatedAttributeSet = signedInfo.getAuthenticatedAttributes();
            logger.info("AUTHENTICATED ATTR : " + authenticatedAttributeSet);

            List<ASN1ObjectIdentifier> attributeOids = new ArrayList<ASN1ObjectIdentifier>();
            for (int i = 0; i < authenticatedAttributeSet.size(); i++) {
                Attribute attribute = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(i));
                attributeOids.add(attribute.getAttrType());
            }
            logger.info("List of OID for Auth Attrb : " + attributeOids);

            Attribute attributeDigest = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(1));
            assertEquals(PKCSObjectIdentifiers.pkcs_9_at_messageDigest, attributeDigest.getAttrType());

            ASN1OctetString asn1ObjString = ASN1OctetString
                    .getInstance(attributeDigest.getAttrValues().getObjectAt(0));
            String embeddedDigest = Base64.encode(asn1ObjString.getOctets());
            logger.info("MESSAGE DIGEST : " + embeddedDigest);

            byte[] digestSignedContent = DSSUtils.digest(digestAlgorithm, signedContent);
            String computedDigestSignedContentEncodeBase64 = Base64.encode(digestSignedContent);
            logger.info("COMPUTED DIGEST SIGNED CONTENT BASE64 : " + computedDigestSignedContentEncodeBase64);
            assertEquals(embeddedDigest, computedDigestSignedContentEncodeBase64);

            SignerIdentifier sid = signedInfo.getSID();
            logger.info("SIGNER IDENTIFIER : " + sid.getId());

            IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber
                    .getInstance(signedInfo.getSID());
            ASN1Integer signerSerialNumber = issuerAndSerialNumber.getSerialNumber();
            logger.info("ISSUER AND SN : " + issuerAndSerialNumber.getName() + " " + signerSerialNumber);

            BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();
            X509Certificate signerCertificate = null;
            for (X509Certificate x509Certificate : certificates) {
                if (serial.equals(x509Certificate.getSerialNumber())) {
                    signerCertificate = x509Certificate;
                }
            }
            assertNotNull(signerCertificate);

            String algorithm = signerCertificate.getPublicKey().getAlgorithm();
            EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(algorithm);

            ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest();
            String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets());

            logger.info("SIGNATURE VALUE : " + signatureValue);

            Cipher cipher = Cipher.getInstance(encryptionAlgorithm.getName());
            cipher.init(Cipher.DECRYPT_MODE, signerCertificate);
            byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets());

            ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted);

            ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject();
            logger.info("DECRYPTED : " + seqDecrypt);

            DigestInfo digestInfo = new DigestInfo(seqDecrypt);
            assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm());

            String decryptedDigestEncodeBase64 = Base64.encode(digestInfo.getDigest());
            logger.info("DECRYPTED BASE64 : " + decryptedDigestEncodeBase64);

            byte[] encoded = authenticatedAttributeSet.getEncoded();
            byte[] digest = DSSUtils.digest(digestAlgorithm, encoded);
            String computedDigestFromSignatureEncodeBase64 = Base64.encode(digest);
            logger.info("COMPUTED DIGEST FROM SIGNATURE BASE64 : " + computedDigestFromSignatureEncodeBase64);

            assertEquals(decryptedDigestEncodeBase64, computedDigestFromSignatureEncodeBase64);

            IOUtils.closeQuietly(inputDecrypted);
            IOUtils.closeQuietly(asn1sInput);
        }

        IOUtils.closeQuietly(inputStream);
        document.close();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        fail(e.getMessage());
    }
}