Example usage for org.bouncycastle.asn1.x509 DigestInfo getDigest

List of usage examples for org.bouncycastle.asn1.x509 DigestInfo getDigest

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 DigestInfo getDigest.

Prototype

public byte[] getDigest() 

Source Link

Usage

From source file:be.fedict.commons.eid.consumer.BeIDIntegrity.java

License:Open Source License

private boolean __verifyNonRepSignature(final byte[] expectedDigestValue, final byte[] signatureValue,
        final X509Certificate certificate) throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException {
    final PublicKey publicKey = certificate.getPublicKey();

    final Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, publicKey);
    final byte[] actualSignatureDigestInfoValue = cipher.doFinal(signatureValue);

    final ASN1InputStream asnInputStream = new ASN1InputStream(actualSignatureDigestInfoValue);
    final DigestInfo actualSignatureDigestInfo = new DigestInfo((ASN1Sequence) asnInputStream.readObject());
    asnInputStream.close();/*w ww .  j av  a  2 s  .  c  o m*/

    final byte[] actualDigestValue = actualSignatureDigestInfo.getDigest();
    return Arrays.equals(expectedDigestValue, actualDigestValue);
}

From source file:be.fedict.eid.applet.service.impl.handler.AuthenticationDataMessageHandler.java

License:Open Source License

public Object handleMessage(AuthenticationDataMessage message, Map<String, String> httpHeaders,
        HttpServletRequest request, HttpSession session) throws ServletException {
    LOG.debug("authentication data message received");

    if (null == message.authnCert) {
        /*//from  ww w  .j a v a 2s.  co  m
         * Can be the case for future (Kids) eID cards that have some
         * certificates missing.
         */
        String msg = "authentication certificate not present";
        LOG.warn(msg);
        throw new ServletException(msg);
    }
    byte[] signatureValue = message.signatureValue;
    LOG.debug("authn signing certificate subject: " + message.authnCert.getSubjectX500Principal());
    PublicKey signingKey = message.authnCert.getPublicKey();

    if (this.sessionIdChannelBinding) {
        checkSessionIdChannelBinding(message, request);
        if (null == this.serverCertificate) {
            LOG.warn("adviced to use in combination with server certificate channel binding");
        }
    }

    ChannelBindingService channelBindingService = this.channelBindingServiceLocator.locateService();
    if (null != this.serverCertificate || null != channelBindingService) {
        LOG.debug("using server certificate channel binding");
    }

    if (false == this.sessionIdChannelBinding && null == this.serverCertificate
            && null == channelBindingService) {
        LOG.warn("not using any secure channel binding");
    }

    byte[] challenge;
    try {
        challenge = AuthenticationChallenge.getAuthnChallenge(session, this.maxMaturity);
    } catch (SecurityException e) {
        AuditService auditService = this.auditServiceLocator.locateService();
        if (null != auditService) {
            String remoteAddress = request.getRemoteAddr();
            auditService.authenticationError(remoteAddress, message.authnCert);
        }
        throw new ServletException("security error: " + e.getMessage(), e);
    }

    byte[] serverCertificateClientPOV = null;
    try {
        if (null != message.serverCertificate) {
            serverCertificateClientPOV = message.serverCertificate.getEncoded();
        }
    } catch (CertificateEncodingException e) {
        throw new ServletException("server cert decoding error: " + e.getMessage(), e);
    }
    /*
     * We validate the authentication contract using the client-side
     * communicated server SSL certificate in case of secure channel
     * binding.
     */
    AuthenticationContract authenticationContract = new AuthenticationContract(message.saltValue, this.hostname,
            this.inetAddress, message.sessionId, serverCertificateClientPOV, challenge);
    byte[] toBeSigned;
    try {
        toBeSigned = authenticationContract.calculateToBeSigned();
    } catch (IOException e) {
        throw new ServletException("IO error: " + e.getMessage(), e);
    }

    try {
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initVerify(signingKey);
        signature.update(toBeSigned);
        boolean result = signature.verify(signatureValue);
        if (false == result) {
            AuditService auditService = this.auditServiceLocator.locateService();
            if (null != auditService) {
                String remoteAddress = request.getRemoteAddr();
                auditService.authenticationError(remoteAddress, message.authnCert);
            }
            throw new SecurityException("authn signature incorrect");
        }
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException("algo error");
    } catch (InvalidKeyException e) {
        throw new SecurityException("authn key error");
    } catch (SignatureException e) {
        throw new SecurityException("signature error");
    }

    RequestContext requestContext = new RequestContext(session);
    String transactionMessage = requestContext.getTransactionMessage();
    if (null != transactionMessage) {
        LOG.debug("verifying TransactionMessage signature");
        byte[] transactionMessageSignature = message.transactionMessageSignature;
        if (null == transactionMessageSignature) {
            throw new SecurityException("missing TransactionMessage signature");
        }
        try {
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, signingKey);
            byte[] signatureDigestInfoValue = cipher.doFinal(transactionMessageSignature);
            ASN1InputStream aIn = new ASN1InputStream(signatureDigestInfoValue);
            DigestInfo signatureDigestInfo = new DigestInfo((ASN1Sequence) aIn.readObject());
            if (false == PLAIN_TEXT_DIGEST_ALGO_OID
                    .equals(signatureDigestInfo.getAlgorithmId().getObjectId().getId())) {
                throw new SecurityException("TransactionMessage signature algo OID incorrect");
            }
            if (false == Arrays.equals(transactionMessage.getBytes(), signatureDigestInfo.getDigest())) {
                throw new SecurityException("signed TransactionMessage incorrect");
            }
            LOG.debug("TransactionMessage signature validated");
        } catch (Exception e) {
            LOG.error("error verifying TransactionMessage signature", e);
            AuditService auditService = this.auditServiceLocator.locateService();
            if (null != auditService) {
                String remoteAddress = request.getRemoteAddr();
                auditService.authenticationError(remoteAddress, message.authnCert);
            }
            throw new SecurityException("error verifying TransactionMessage signature: " + e.getMessage());
        }
    }

    /*
     * Secure channel binding verification.
     */
    if (null != channelBindingService) {
        X509Certificate serverCertificate = channelBindingService.getServerCertificate();
        if (null == serverCertificate) {
            LOG.warn("could not verify secure channel binding as the server does not know its identity yet");
        } else {
            if (false == serverCertificate.equals(message.serverCertificate)) {
                AuditService auditService = this.auditServiceLocator.locateService();
                if (null != auditService) {
                    String remoteAddress = request.getRemoteAddr();
                    auditService.authenticationError(remoteAddress, message.authnCert);
                }
                throw new SecurityException("secure channel binding identity mismatch");
            }
            LOG.debug("secure channel binding verified");
        }
    } else {
        if (null != this.serverCertificate) {
            if (false == this.serverCertificate.equals(message.serverCertificate)) {
                AuditService auditService = this.auditServiceLocator.locateService();
                if (null != auditService) {
                    String remoteAddress = request.getRemoteAddr();
                    auditService.authenticationError(remoteAddress, message.authnCert);
                }
                throw new SecurityException("secure channel binding identity mismatch");
            }
            LOG.debug("secure channel binding verified");
        }
    }

    AuthenticationService authenticationService = this.authenticationServiceLocator.locateService();
    List<X509Certificate> certificateChain = new LinkedList<X509Certificate>();
    certificateChain.add(message.authnCert);
    certificateChain.add(message.citizenCaCert);
    certificateChain.add(message.rootCaCert);
    try {
        authenticationService.validateCertificateChain(certificateChain);
    } catch (ExpiredCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
    } catch (RevokedCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
    } catch (TrustCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
    } catch (CertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE);
    } catch (Exception e) {
        /*
         * We don't want to depend on the full JavaEE profile in this
         * artifact.
         */
        if ("javax.ejb.EJBException".equals(e.getClass().getName())) {
            Exception exception;
            try {
                Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException",
                        new Class[] {});
                exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {});
            } catch (Exception e2) {
                LOG.debug("error: " + e.getMessage(), e);
                throw new SecurityException("error retrieving the root cause: " + e2.getMessage());
            }
            if (exception instanceof ExpiredCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
            }
            if (exception instanceof RevokedCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
            }
            if (exception instanceof TrustCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
            }
            if (exception instanceof CertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE);
            }
        }
        throw new SecurityException("authn service error: " + e.getMessage());
    }

    String userId = UserIdentifierUtil.getUserId(message.authnCert);
    LOG.info("authenticated: " + userId + " @ " + request.getRemoteAddr());
    if (null != this.nrcidSecret) {
        userId = UserIdentifierUtil.getNonReversibleCitizenIdentifier(userId, this.nrcidOrgId, this.nrcidAppId,
                this.nrcidSecret);
    }
    /*
     * Some people state that you cannot use the national register number
     * without hashing. Problem is that hashing introduces hash collision
     * problems. The probability is very low, but what if it's your leg
     * they're cutting of because of a patient mismatch based on the SHA1 of
     * your national register number?
     */

    /*
     * Push authenticated used Id into the HTTP session.
     */
    session.setAttribute(AUTHENTICATED_USER_IDENTIFIER_SESSION_ATTRIBUTE, userId);

    EIdData eidData = (EIdData) session.getAttribute(IdentityDataMessageHandler.EID_SESSION_ATTRIBUTE);
    if (null == eidData) {
        eidData = new EIdData();
        session.setAttribute(IdentityDataMessageHandler.EID_SESSION_ATTRIBUTE, eidData);
    }
    eidData.identifier = userId;

    AuditService auditService = this.auditServiceLocator.locateService();
    if (null != auditService) {
        auditService.authenticated(userId);
    }

    boolean includeIdentity = requestContext.includeIdentity();
    boolean includeAddress = requestContext.includeAddress();
    boolean includeCertificates = requestContext.includeCertificates();
    boolean includePhoto = requestContext.includePhoto();

    /*
     * Also process the identity data in case it was requested.
     */
    if (includeIdentity) {
        if (null == message.identityData) {
            throw new ServletException("identity data not included while requested");
        }
    }
    if (includeAddress) {
        if (null == message.addressData) {
            throw new ServletException("address data not included while requested");
        }
    }
    if (includePhoto) {
        if (null == message.photoData) {
            throw new ServletException("photo data not included while requested");
        }
    }
    IdentityIntegrityService identityIntegrityService = this.identityIntegrityServiceLocator.locateService();
    if (null != identityIntegrityService) {
        if (null == message.rrnCertificate) {
            throw new ServletException("national registry certificate not included while requested");
        }
        List<X509Certificate> rrnCertificateChain = new LinkedList<X509Certificate>();
        rrnCertificateChain.add(message.rrnCertificate);
        rrnCertificateChain.add(message.rootCaCert);

        try {
            identityIntegrityService.checkNationalRegistrationCertificate(rrnCertificateChain);
        } catch (ExpiredCertificateSecurityException e) {
            return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
        } catch (RevokedCertificateSecurityException e) {
            return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
        } catch (TrustCertificateSecurityException e) {
            return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
        } catch (CertificateSecurityException e) {
            return new FinishedMessage(ErrorCode.CERTIFICATE);
        } catch (Exception e) {
            if ("javax.ejb.EJBException".equals(e.getClass().getName())) {
                Exception exception;
                try {
                    Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException",
                            new Class[] {});
                    exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {});
                } catch (Exception e2) {
                    LOG.debug("error: " + e.getMessage(), e);
                    throw new SecurityException("error retrieving the root cause: " + e2.getMessage());
                }
                if (exception instanceof ExpiredCertificateSecurityException) {
                    return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
                }
                if (exception instanceof RevokedCertificateSecurityException) {
                    return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
                }
                if (exception instanceof TrustCertificateSecurityException) {
                    return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
                }
                if (exception instanceof CertificateSecurityException) {
                    return new FinishedMessage(ErrorCode.CERTIFICATE);
                }
            }
            throw new SecurityException("error checking the NRN certificate: " + e.getMessage(), e);
        }

        PublicKey rrnPublicKey = message.rrnCertificate.getPublicKey();
        if (includeIdentity) {
            if (null == message.identitySignatureData) {
                throw new ServletException("identity signature data not included while requested");
            }
            verifySignature(message.rrnCertificate.getSigAlgName(), message.identitySignatureData, rrnPublicKey,
                    request, message.identityData);
        }
        if (includeAddress) {
            if (null == message.addressSignatureData) {
                throw new ServletException("address signature data not included while requested");
            }
            byte[] addressFile = trimRight(message.addressData);
            verifySignature(message.rrnCertificate.getSigAlgName(), message.addressSignatureData, rrnPublicKey,
                    request, addressFile, message.identitySignatureData);
        }
    }
    if (includeIdentity) {
        Identity identity = TlvParser.parse(message.identityData, Identity.class);
        if (false == UserIdentifierUtil.getUserId(message.authnCert).equals(identity.nationalNumber)) {
            throw new ServletException("national number mismatch");
        }
        session.setAttribute(IdentityDataMessageHandler.IDENTITY_SESSION_ATTRIBUTE, identity);
        eidData.identity = identity;
        auditService = this.auditServiceLocator.locateService();
        if (null != auditService) {
            auditService.identified(identity.nationalNumber);
        }
    }
    if (includeAddress) {
        Address address = TlvParser.parse(message.addressData, Address.class);
        session.setAttribute(IdentityDataMessageHandler.ADDRESS_SESSION_ATTRIBUTE, address);
        eidData.address = address;
    }
    if (includePhoto) {
        if (includeIdentity) {
            byte[] expectedPhotoDigest = eidData.identity.photoDigest;
            byte[] actualPhotoDigest = digestPhoto(getDigestAlgo(expectedPhotoDigest.length),
                    message.photoData);
            if (false == Arrays.equals(expectedPhotoDigest, actualPhotoDigest)) {
                throw new ServletException("photo digest incorrect");
            }
        }
        session.setAttribute(IdentityDataMessageHandler.PHOTO_SESSION_ATTRIBUTE, message.photoData);
        eidData.photo = message.photoData;
    }
    if (includeCertificates) {
        if (includeIdentity) {
            eidData.certs = new EIdCertsData();
            eidData.certs.authn = message.authnCert;
            eidData.certs.ca = message.citizenCaCert;
            eidData.certs.root = message.rootCaCert;
            eidData.certs.sign = message.signCert;
        }
        session.setAttribute(IdentityDataMessageHandler.AUTHN_CERT_SESSION_ATTRIBUTE, message.authnCert);
        session.setAttribute(IdentityDataMessageHandler.CA_CERT_SESSION_ATTRIBUTE, message.citizenCaCert);
        session.setAttribute(IdentityDataMessageHandler.ROOT_CERT_SESSION_ATTRIBTUE, message.rootCaCert);
        session.setAttribute(IdentityDataMessageHandler.SIGN_CERT_SESSION_ATTRIBUTE, message.signCert);
    }

    if (this.includeDataFiles) {
        session.setAttribute(IdentityDataMessageHandler.EID_DATA_IDENTITY_SESSION_ATTRIBUTE,
                message.identityData);
        session.setAttribute(IdentityDataMessageHandler.EID_DATA_ADDRESS_SESSION_ATTRIBUTE,
                message.addressData);
    }

    AuthenticationSignatureService authenticationSignatureService = this.authenticationSignatureServiceLocator
            .locateService();
    if (null != authenticationSignatureService) {
        List<X509Certificate> authnCertificateChain;
        if (null != message.authnCert) {
            authnCertificateChain = new LinkedList<X509Certificate>();
            authnCertificateChain.add(message.authnCert);
            authnCertificateChain.add(message.citizenCaCert);
            authnCertificateChain.add(message.rootCaCert);
        } else {
            authnCertificateChain = null;
        }
        AuthenticationSignatureContext authenticationSignatureContext = new AuthenticationSignatureContextImpl(
                session);
        PreSignResult preSignResult = authenticationSignatureService.preSign(authnCertificateChain,
                authenticationSignatureContext);
        if (null == preSignResult) {
            return new FinishedMessage();
        }
        boolean logoff = preSignResult.getLogoff();
        byte[] computedDigestValue = preSignResult.getDigestInfo().digestValue;
        String digestAlgo = preSignResult.getDigestInfo().digestAlgo;
        String authnMessage = preSignResult.getDigestInfo().description;
        AuthSignRequestMessage authSignRequestMessage = new AuthSignRequestMessage(computedDigestValue,
                digestAlgo, authnMessage, logoff);
        return authSignRequestMessage;
    }
    return new FinishedMessage();
}

From source file:eu.europa.esig.dss.cades.signature.CAdESLevelBETSITS101733Test.java

License:Open Source License

@Override
protected void onDocumentSigned(byte[] byteArray) {
    try {//  www .  ja va2s . c  om

        CAdESSignature signature = new CAdESSignature(byteArray);
        assertNotNull(signature.getCmsSignedData());

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

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

        assertEquals(2, asn1Seq.size());

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
        assertEquals(PKCSObjectIdentifiers.signedData, oid);
        logger.info("OID : " + oid.toString());

        ASN1TaggedObject taggedObj = DERTaggedObject.getInstance(asn1Seq.getObjectAt(1));

        logger.info("TAGGED OBJ : " + taggedObj.toString());

        ASN1Primitive object = taggedObj.getObject();
        logger.info("OBJ : " + object.toString());

        SignedData signedData = SignedData.getInstance(object);
        logger.info("SIGNED DATA : " + signedData.toString());

        ASN1Set digestAlgorithms = signedData.getDigestAlgorithms();
        logger.info("DIGEST ALGOS : " + digestAlgorithms.toString());

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

        ASN1Set certificates = signedData.getCertificates();
        logger.info("CERTIFICATES (" + certificates.size() + ") : " + certificates);

        List<X509Certificate> foundCertificates = new ArrayList<X509Certificate>();
        for (int i = 0; i < certificates.size(); i++) {
            ASN1Sequence seqCertif = ASN1Sequence.getInstance(certificates.getObjectAt(i));
            logger.info("SEQ cert " + i + " : " + seqCertif);

            X509CertificateHolder certificateHolder = new X509CertificateHolder(seqCertif.getEncoded());
            CertificateToken certificate = DSSASN1Utils.getCertificate(certificateHolder);
            X509Certificate x509Certificate = certificate.getCertificate();
            x509Certificate.checkValidity();

            logger.info("Cert " + i + " : " + certificate);

            foundCertificates.add(x509Certificate);
        }

        ASN1Set crLs = signedData.getCRLs();
        logger.info("CRLs : " + crLs);

        ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
        logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
        assertEquals(1, signerInfosAsn1.size());

        ASN1Sequence seqSignedInfo = ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0));

        SignerInfo signedInfo = SignerInfo.getInstance(seqSignedInfo);
        logger.info("SIGNER INFO : " + signedInfo.toString());

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

        IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber.getInstance(signedInfo.getSID());
        logger.info("ISSUER AND SN : " + issuerAndSerialNumber.toString());

        BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();

        X509Certificate signerCertificate = null;
        for (X509Certificate x509Certificate : foundCertificates) {
            // TODO check issuer name
            if (serial.equals(x509Certificate.getSerialNumber())) {
                signerCertificate = x509Certificate;
            }
        }
        assertNotNull(signerCertificate);

        ASN1OctetString encryptedDigest = signedInfo.getEncryptedDigest();
        logger.info("ENCRYPT DIGEST : " + encryptedDigest.toString());

        ASN1Sequence seq = ASN1Sequence.getInstance(object);

        ASN1Integer version = ASN1Integer.getInstance(seq.getObjectAt(0));
        logger.info("VERSION : " + version.toString());

        ASN1Set digestManualSet = ASN1Set.getInstance(seq.getObjectAt(1));
        logger.info("DIGEST SET : " + digestManualSet.toString());
        assertEquals(digestAlgorithms, digestManualSet);

        ASN1Sequence seqDigest = ASN1Sequence.getInstance(digestManualSet.getObjectAt(0));
        // assertEquals(1, seqDigest.size());

        ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier.getInstance(seqDigest.getObjectAt(0));
        assertEquals(new ASN1ObjectIdentifier(DigestAlgorithm.SHA256.getOid()), oidDigestAlgo);

        ASN1Sequence seqEncapsulatedInfo = ASN1Sequence.getInstance(seq.getObjectAt(2));
        logger.info("ENCAPSULATED INFO : " + seqEncapsulatedInfo.toString());

        ASN1ObjectIdentifier oidContentType = ASN1ObjectIdentifier
                .getInstance(seqEncapsulatedInfo.getObjectAt(0));
        logger.info("OID CONTENT TYPE : " + oidContentType.toString());

        ASN1TaggedObject taggedContent = DERTaggedObject.getInstance(seqEncapsulatedInfo.getObjectAt(1));

        ASN1OctetString contentOctetString = ASN1OctetString.getInstance(taggedContent.getObject());
        String content = new String(contentOctetString.getOctets());
        assertEquals(HELLO_WORLD, content);
        logger.info("CONTENT : " + content);

        byte[] digest = DSSUtils.digest(DigestAlgorithm.SHA256, HELLO_WORLD.getBytes());
        String encodeHexDigest = Hex.toHexString(digest);
        logger.info("CONTENT DIGEST COMPUTED : " + encodeHexDigest);

        ASN1Set authenticatedAttributes = signedInfo.getAuthenticatedAttributes();
        logger.info("AUTHENTICATED ATTRIBUTES : " + authenticatedAttributes.toString());

        // ASN1Sequence seqAuthAttrib = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(0));

        logger.info("Nb Auth Attributes : " + authenticatedAttributes.size());

        String embeddedDigest = "";
        for (int i = 0; i < authenticatedAttributes.size(); i++) {
            ASN1Sequence authAttrSeq = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(i));
            logger.info(authAttrSeq.toString());
            ASN1ObjectIdentifier attrOid = ASN1ObjectIdentifier.getInstance(authAttrSeq.getObjectAt(0));
            if (PKCSObjectIdentifiers.pkcs_9_at_messageDigest.equals(attrOid)) {
                ASN1Set setMessageDigest = ASN1Set.getInstance(authAttrSeq.getObjectAt(1));
                ASN1OctetString asn1ObjString = ASN1OctetString.getInstance(setMessageDigest.getObjectAt(0));
                embeddedDigest = Hex.toHexString(asn1ObjString.getOctets());
            }
        }
        assertEquals(encodeHexDigest, embeddedDigest);

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

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

        Cipher cipher = Cipher.getInstance("RSA");
        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 = Utils.toBase64(digestInfo.getDigest());
        logger.info("Decrypted Base64 : " + decryptedDigestEncodeBase64);

        byte[] encoded = signedInfo.getAuthenticatedAttributes().getEncoded();
        MessageDigest messageDigest = MessageDigest.getInstance(DigestAlgorithm.SHA256.getName());
        byte[] digestOfAuthenticatedAttributes = messageDigest.digest(encoded);

        String computedDigestEncodeBase64 = Utils.toBase64(digestOfAuthenticatedAttributes);
        logger.info("Computed Base64 : " + computedDigestEncodeBase64);

        assertEquals(decryptedDigestEncodeBase64, computedDigestEncodeBase64);

        Utils.closeQuietly(asn1sInput);
        Utils.closeQuietly(inputDecrypted);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        fail(e.getMessage());
    }
}

From source file:eu.europa.esig.dss.cades.signature.CAdESLevelBTest.java

License:Open Source License

@Override
protected void onDocumentSigned(byte[] byteArray) {
    try {/*  w  ww  . j  a  v a 2  s .c om*/

        CAdESSignature signature = new CAdESSignature(byteArray);
        assertNotNull(signature.getCmsSignedData());

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

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

        assertEquals(2, asn1Seq.size());

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
        assertEquals(PKCSObjectIdentifiers.signedData, oid);
        logger.info("OID : " + oid.toString());

        ASN1TaggedObject taggedObj = DERTaggedObject.getInstance(asn1Seq.getObjectAt(1));

        logger.info("TAGGED OBJ : " + taggedObj.toString());

        ASN1Primitive object = taggedObj.getObject();
        logger.info("OBJ : " + object.toString());

        SignedData signedData = SignedData.getInstance(object);
        logger.info("SIGNED DATA : " + signedData.toString());

        ASN1Set digestAlgorithms = signedData.getDigestAlgorithms();
        logger.info("DIGEST ALGOS : " + digestAlgorithms.toString());

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

        ASN1Set certificates = signedData.getCertificates();
        logger.info("CERTIFICATES (" + certificates.size() + ") : " + certificates);

        List<X509Certificate> foundCertificates = new ArrayList<X509Certificate>();
        for (int i = 0; i < certificates.size(); i++) {
            ASN1Sequence seqCertif = ASN1Sequence.getInstance(certificates.getObjectAt(i));
            logger.info("SEQ cert " + i + " : " + seqCertif);

            X509CertificateHolder certificateHolder = new X509CertificateHolder(seqCertif.getEncoded());
            X509Certificate certificate = new JcaX509CertificateConverter()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);

            certificate.checkValidity();

            logger.info("Cert " + i + " : " + certificate);

            foundCertificates.add(certificate);
        }

        ASN1Set crLs = signedData.getCRLs();
        logger.info("CRLs : " + crLs);

        ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
        logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
        assertEquals(1, signerInfosAsn1.size());

        ASN1Sequence seqSignedInfo = ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0));

        SignerInfo signedInfo = SignerInfo.getInstance(seqSignedInfo);
        logger.info("SIGNER INFO : " + signedInfo.toString());

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

        IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber.getInstance(signedInfo.getSID());
        logger.info("ISSUER AND SN : " + issuerAndSerialNumber.toString());

        BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();

        X509Certificate signerCertificate = null;
        for (X509Certificate x509Certificate : foundCertificates) {
            // TODO check issuer name
            if (serial.equals(x509Certificate.getSerialNumber())) {
                signerCertificate = x509Certificate;
            }
        }
        assertNotNull(signerCertificate);

        ASN1OctetString encryptedDigest = signedInfo.getEncryptedDigest();
        logger.info("ENCRYPT DIGEST : " + encryptedDigest.toString());

        ASN1Sequence seq = ASN1Sequence.getInstance(object);

        ASN1Integer version = ASN1Integer.getInstance(seq.getObjectAt(0));
        logger.info("VERSION : " + version.toString());

        ASN1Set digestManualSet = ASN1Set.getInstance(seq.getObjectAt(1));
        logger.info("DIGEST SET : " + digestManualSet.toString());
        assertEquals(digestAlgorithms, digestManualSet);

        ASN1Sequence seqDigest = ASN1Sequence.getInstance(digestManualSet.getObjectAt(0));
        // assertEquals(1, seqDigest.size());

        ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier.getInstance(seqDigest.getObjectAt(0));
        assertEquals(new ASN1ObjectIdentifier(DigestAlgorithm.SHA256.getOid()), oidDigestAlgo);

        ASN1Sequence seqEncapsulatedInfo = ASN1Sequence.getInstance(seq.getObjectAt(2));
        logger.info("ENCAPSULATED INFO : " + seqEncapsulatedInfo.toString());

        ASN1ObjectIdentifier oidContentType = ASN1ObjectIdentifier
                .getInstance(seqEncapsulatedInfo.getObjectAt(0));
        logger.info("OID CONTENT TYPE : " + oidContentType.toString());

        ASN1TaggedObject taggedContent = DERTaggedObject.getInstance(seqEncapsulatedInfo.getObjectAt(1));

        ASN1OctetString contentOctetString = ASN1OctetString.getInstance(taggedContent.getObject());
        String content = new String(contentOctetString.getOctets());
        assertEquals(HELLO_WORLD, content);
        logger.info("CONTENT : " + content);

        byte[] digest = DSSUtils.digest(DigestAlgorithm.SHA256, HELLO_WORLD.getBytes());
        String encodeHexDigest = Hex.toHexString(digest);
        logger.info("CONTENT DIGEST COMPUTED : " + encodeHexDigest);

        ASN1Set authenticatedAttributes = signedInfo.getAuthenticatedAttributes();
        logger.info("AUTHENTICATED ATTRIBUTES : " + authenticatedAttributes.toString());

        // ASN1Sequence seqAuthAttrib = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(0));

        logger.info("Nb Auth Attributes : " + authenticatedAttributes.size());

        String embeddedDigest = StringUtils.EMPTY;
        for (int i = 0; i < authenticatedAttributes.size(); i++) {
            ASN1Sequence authAttrSeq = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(i));
            logger.info(authAttrSeq.toString());
            ASN1ObjectIdentifier attrOid = ASN1ObjectIdentifier.getInstance(authAttrSeq.getObjectAt(0));
            if (PKCSObjectIdentifiers.pkcs_9_at_messageDigest.equals(attrOid)) {
                ASN1Set setMessageDigest = ASN1Set.getInstance(authAttrSeq.getObjectAt(1));
                ASN1OctetString asn1ObjString = ASN1OctetString.getInstance(setMessageDigest.getObjectAt(0));
                embeddedDigest = Hex.toHexString(asn1ObjString.getOctets());
            }
        }
        assertEquals(encodeHexDigest, embeddedDigest);

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

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

        Cipher cipher = Cipher.getInstance("RSA");
        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.encodeBase64String(digestInfo.getDigest());
        logger.info("Decrypted Base64 : " + decryptedDigestEncodeBase64);

        byte[] encoded = signedInfo.getAuthenticatedAttributes().getEncoded();
        MessageDigest messageDigest = MessageDigest.getInstance(DigestAlgorithm.SHA256.getName());
        byte[] digestOfAuthenticatedAttributes = messageDigest.digest(encoded);

        String computedDigestEncodeBase64 = Base64.encodeBase64String(digestOfAuthenticatedAttributes);
        logger.info("Computed Base64 : " + computedDigestEncodeBase64);

        assertEquals(decryptedDigestEncodeBase64, computedDigestEncodeBase64);

        IOUtils.closeQuietly(asn1sInput);
        IOUtils.closeQuietly(inputDecrypted);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        fail(e.getMessage());
    }
}

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

License:Open Source License

/**
 * These signatures are invalid because of non ordered signed attributes
 *//* w  w w  . j a v  a2s  .  co m*/
@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.encodeBase64String(asn1ObjString.getOctets());
            logger.info("MESSAGE DIGEST : " + embeddedDigest);

            byte[] digestSignedContent = DSSUtils.digest(digestAlgorithm, signedContent);
            String computedDigestSignedContentEncodeBase64 = Base64.encodeBase64String(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.encodeBase64String(digestInfo.getDigest());
            logger.info("DECRYPTED BASE64 : " + decryptedDigestEncodeBase64);

            byte[] encoded = authenticatedAttributeSet.getEncoded();
            byte[] digest = DSSUtils.digest(digestAlgorithm, encoded);
            String computedDigestFromSignatureEncodeBase64 = Base64.encodeBase64String(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

License:Open Source License

@Override
protected void onDocumentSigned(byte[] byteArray) {

    try {/*from   w w w . jav  a 2  s . c o  m*/
        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>();
            int previousSize = 0;
            for (int i = 0; i < authenticatedAttributeSet.size(); i++) {
                Attribute attribute = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(i));
                ASN1ObjectIdentifier attrTypeOid = attribute.getAttrType();
                attributeOids.add(attrTypeOid);
                int size = attrTypeOid.getEncoded().length + attribute.getEncoded().length;
                assertTrue(size >= previousSize);

                previousSize = size;
            }
            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.encodeBase64String(asn1ObjString.getOctets());
            logger.info("MESSAGE DIGEST : " + embeddedDigest);

            byte[] digestSignedContent = DSSUtils.digest(digestAlgorithm, signedContent);
            String computedDigestSignedContentEncodeBase64 = Base64.encodeBase64String(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.encodeBase64String(digestInfo.getDigest());
            logger.info("DECRYPTED BASE64 : " + decryptedDigestEncodeBase64);

            byte[] encoded = authenticatedAttributeSet.getEncoded();
            byte[] digest = DSSUtils.digest(digestAlgorithm, encoded);
            String computedDigestFromSignatureEncodeBase64 = Base64.encodeBase64String(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());
    }
}

From source file:org.ccnx.ccn.protocol.Signature.java

License:Open Source License

/**
 * Compute the content proxy for a given node. This should likely move somewhere else
 * @param nodeContent the content stored at this node
 * @param isDigest is the content already digested
 * @return the proxy digest (for example, the computed root of the Merkle hash tree) for this node
 * @throws CertificateEncodingException if we cannot decode the witness
 *//*from  ww  w  .j av a  2  s.  c o  m*/
public byte[] computeProxy(byte[] nodeContent, boolean isDigest) throws CertificateEncodingException {
    if (null == witness())
        return null;

    DigestInfo info = CCNDigestHelper.digestDecoder(witness());

    byte[] proxy = null;

    if (MerklePath.isMerklePath(info)) {
        MerklePath mp = new MerklePath(info.getDigest());
        proxy = mp.root(nodeContent, isDigest);
    } else {
        Log.warning("Unexpected witness type: " + info.getAlgorithmId().toString());
    }
    return proxy;
}

From source file:org.ccnx.ccn.security.crypto.MerkleTreeTest.java

License:Open Source License

public static void testTree(byte[][] content, int count, boolean digest) {
    // Generate a merkle tree. Verify each path for the content.
    MerkleTree tree = new MerkleTree(content, digest, count, 0,
            ((count - 1) >= 0) && ((count - 1) < content.length) ? content[count - 1].length : 0);

    MerklePath[] paths = new MerklePath[count];
    for (int i = 0; i < count; ++i) {
        paths[i] = tree.path(i);// ww  w  .j ava  2 s.c om
        //checkPath(tree, paths[i]);
        byte[] root = paths[i].root(content[i], digest);
        boolean result = Arrays.equals(root, tree.root());
        if (!result) {
            System.out.println("Constructed tree of " + count + " blocks (of " + content.length
                    + "), numleaves: " + tree.numLeaves() + " max pathlength: " + tree.maxDepth());
            System.out.println("Path " + i + " verified for leaf " + paths[i].leafNodeIndex() + "? " + result);
        }
        Assert.assertTrue("Path " + i + " failed to verify.", result);

        try {
            byte[] encodedPath = paths[i].derEncodedPath();
            DigestInfo info = CCNDigestHelper.digestDecoder(encodedPath);
            MerklePath decoded = new MerklePath(info.getDigest());
            if (!decoded.equals(paths[i])) {
                System.out.println("Path " + i + " failed to encode and decode.");
                Assert.fail("Path " + i + " failed to encode and decode.");
            }
        } catch (Exception e) {
            System.out.println(
                    "Exception encoding path " + i + " :" + e.getClass().getName() + ": " + e.getMessage());
            e.printStackTrace();
            Assert.fail("Exception encoding path " + i + " :" + e.getClass().getName() + ": " + e.getMessage());
        }
    }
}

From source file:org.ndnx.ndn.protocol.Signature.java

License:Open Source License

/**
 * Compute the content proxy for a given node. This should likely move somewhere else
 * @param nodeContent the content stored at this node
 * @param isDigest is the content already digested
 * @return the proxy digest (for example, the computed root of the Merkle hash tree) for this node
 * @throws CertificateEncodingException if we cannot decode the witness
 *//*from www .ja v  a 2s . c  om*/
public byte[] computeProxy(byte[] nodeContent, boolean isDigest) throws CertificateEncodingException {
    if (null == witness())
        return null;

    DigestInfo info = NDNDigestHelper.digestDecoder(witness());

    byte[] proxy = null;

    if (MerklePath.isMerklePath(info)) {
        MerklePath mp = new MerklePath(info.getDigest());
        proxy = mp.root(nodeContent, isDigest);
    } else {
        Log.warning("Unexpected witness type: " + info.getAlgorithmId().toString());
    }
    return proxy;
}

From source file:org.ndnx.ndn.security.crypto.MerkleTreeTest.java

License:Open Source License

public static void testTree(byte[][] content, int count, boolean digest) {
    // Generate a merkle tree. Verify each path for the content.
    MerkleTree tree = new MerkleTree(content, digest, count, 0,
            ((count - 1) >= 0) && ((count - 1) < content.length) ? content[count - 1].length : 0);

    MerklePath[] paths = new MerklePath[count];
    for (int i = 0; i < count; ++i) {
        paths[i] = tree.path(i);//w ww  .j  a  va  2s  .c o m
        //checkPath(tree, paths[i]);
        byte[] root = paths[i].root(content[i], digest);
        boolean result = Arrays.equals(root, tree.root());
        if (!result) {
            System.out.println("Constructed tree of " + count + " blocks (of " + content.length
                    + "), numleaves: " + tree.numLeaves() + " max pathlength: " + tree.maxDepth());
            System.out.println("Path " + i + " verified for leaf " + paths[i].leafNodeIndex() + "? " + result);
        }
        Assert.assertTrue("Path " + i + " failed to verify.", result);

        try {
            byte[] encodedPath = paths[i].derEncodedPath();
            DigestInfo info = NDNDigestHelper.digestDecoder(encodedPath);
            MerklePath decoded = new MerklePath(info.getDigest());
            if (!decoded.equals(paths[i])) {
                System.out.println("Path " + i + " failed to encode and decode.");
                Assert.fail("Path " + i + " failed to encode and decode.");
            }
        } catch (Exception e) {
            System.out.println(
                    "Exception encoding path " + i + " :" + e.getClass().getName() + ": " + e.getMessage());
            e.printStackTrace();
            Assert.fail("Exception encoding path " + i + " :" + e.getClass().getName() + ": " + e.getMessage());
        }
    }
}