Example usage for javax.xml.bind DatatypeConverter printHexBinary

List of usage examples for javax.xml.bind DatatypeConverter printHexBinary

Introduction

In this page you can find the example usage for javax.xml.bind DatatypeConverter printHexBinary.

Prototype

public static String printHexBinary(byte[] val) 

Source Link

Document

Converts an array of bytes into a string.

Usage

From source file:org.egov.collection.integration.pgi.AxisAdaptor.java

private String hashAllFields(final LinkedHashMap<String, String> fields) {

    final String axisSecureSecret = collectionApplicationProperties.axisSecureSecret();
    byte[] decodedKey;
    byte[] hashValue = null;
    // Sort list with field names ascending order
    final List<String> fieldNames = new ArrayList<>(fields.keySet());
    Collections.sort(fieldNames);

    // iterate through field name list and generate message for hashing. Format: fieldname1=fieldvale1?fieldname2=fieldvalue2
    final Iterator<String> itr = fieldNames.iterator();
    final StringBuilder hashingMessage = new StringBuilder();
    int i = 0;//w  w w .  j ava  2 s  .  com
    while (itr.hasNext()) {
        final String fieldName = itr.next();
        final String fieldValue = fields.get(fieldName);
        if (fieldValue != null && fieldValue.length() > 0) {
            if (i != 0)
                hashingMessage.append("&");
            hashingMessage.append(fieldName).append("=").append(fieldValue);
            i++;
        }
    }
    try {
        decodedKey = Hex.decodeHex(axisSecureSecret.toCharArray());
        SecretKeySpec keySpec = new SecretKeySpec(decodedKey, "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(keySpec);
        byte[] hashingMessageBytes = hashingMessage.toString().getBytes(UTF8);
        hashValue = mac.doFinal(hashingMessageBytes);
    } catch (DecoderException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return DatatypeConverter.printHexBinary(hashValue);
}

From source file:org.forgerock.openidm.script.impl.ScriptRegistryService.java

@Override
public ScriptEntry takeScript(JsonValue script) throws ScriptException {
    JsonValue scriptConfig = script.clone();
    if (scriptConfig.get(SourceUnit.ATTR_NAME).isNull()) {
        JsonValue file = scriptConfig.get(SOURCE_FILE);
        JsonValue source = scriptConfig.get(SourceUnit.ATTR_SOURCE);

        if (!file.isNull()) {
            // If we do not have a name use the file.
            scriptConfig.put(SourceUnit.ATTR_NAME, file.asString());
        } else if (!source.isNull()) {
            /*//from  ww w  .ja v a 2 s  .  c o  m
             * We assign a name here otherwise ScriptRegistryImpl.takeScript() assigns a random UUID.
             * This results in a newly created and cached class on every invocation.
             */
            try {
                MessageDigest md = MessageDigest.getInstance("SHA-1");

                // digest source AND type as we could have identical source for different types
                String type = scriptConfig.get(SourceUnit.ATTR_TYPE).asString();
                byte[] nameAndType = (source.asString() + type).getBytes();
                byte[] digest = md.digest(nameAndType);
                String name = DatatypeConverter.printHexBinary(digest);

                scriptConfig.put(SourceUnit.ATTR_NAME, name);
            } catch (NoSuchAlgorithmException e) {
                // SHA-1 is a required implementation. This should never happen.
                logger.error(
                        "Could not get SHA-1 MessageDigest instance. This should be implemented on any standard JVM.",
                        e);
            }
        }
    }

    // Get and remove any defined globals
    JsonValue globals = scriptConfig.get(SOURCE_GLOBALS);
    scriptConfig.remove(SOURCE_GLOBALS);

    // Create the script entry
    ScriptEntry scriptEntry = super.takeScript(scriptConfig);

    // Add the globals (if any) to the script bindings
    if (!globals.isNull() && globals.isMap()) {
        for (String key : globals.keys()) {
            scriptEntry.put(key, globals.get(key));
        }
    }
    return scriptEntry;
}

From source file:org.hyperledger.fabric.sdk.EventHub.java

private void blockListen(TransactionContext transactionContext)
        throws CryptoException, InvalidArgumentException {

    this.transactionContext = transactionContext;

    PeerEvents.Register register = PeerEvents.Register.newBuilder()
            .addEvents(PeerEvents.Interest.newBuilder().setEventType(PeerEvents.EventType.BLOCK).build())
            .build();//  ww w.ja v a2s .co m
    PeerEvents.Event.Builder blockEventBuilder = PeerEvents.Event.newBuilder().setRegister(register)
            .setCreator(transactionContext.getIdentity().toByteString())
            .setTimestamp(ProtoUtils.getCurrentFabricTimestamp());

    if (null != clientTLSCertificateDigest) {
        logger.trace("Setting clientTLSCertificate digest for event registration to "
                + DatatypeConverter.printHexBinary(clientTLSCertificateDigest));
        blockEventBuilder.setTlsCertHash(ByteString.copyFrom(clientTLSCertificateDigest));

    }

    ByteString blockEventByteString = blockEventBuilder.build().toByteString();

    PeerEvents.SignedEvent signedBlockEvent = PeerEvents.SignedEvent.newBuilder()
            .setEventBytes(blockEventByteString)
            .setSignature(transactionContext.signByteString(blockEventByteString.toByteArray())).build();
    sender.onNext(signedBlockEvent);
}

From source file:org.hyperledger.fabric.sdk.ProposalResponse.java

boolean verify(CryptoSuite crypto) {
    logger.trace(format("%s verifying transaction: %s endorsement.", peer, getTransactionID()));

    if (hasBeenVerified) { // check if this proposalResponse was already verified   by client code
        logger.trace(format("%s transaction: %s was already verified returned %b", peer, getTransactionID(),
                isVerified));/*from  w w w .  j  a  v a 2s  .  c  o m*/
        return this.isVerified;
    }

    try {
        if (isInvalid()) {
            this.isVerified = false;
            logger.debug(format("%s for transaction %s returned invalid. Setting verify to false", peer,
                    getTransactionID()));
            return false;
        }

        FabricProposalResponse.Endorsement endorsement = this.proposalResponse.getEndorsement();
        ByteString sig = endorsement.getSignature();
        byte[] endorserCertifcate = null;
        byte[] signature = null;
        byte[] data = null;

        try {
            Identities.SerializedIdentity endorser = Identities.SerializedIdentity
                    .parseFrom(endorsement.getEndorser());
            ByteString plainText = proposalResponse.getPayload().concat(endorsement.getEndorser());

            if (config.extraLogLevel(10)) {

                if (null != diagnosticFileDumper) {
                    StringBuilder sb = new StringBuilder(10000);
                    sb.append("payload TransactionBuilderbytes in hex: "
                            + DatatypeConverter.printHexBinary(proposalResponse.getPayload().toByteArray()));
                    sb.append("\n");
                    sb.append("endorser bytes in hex: "
                            + DatatypeConverter.printHexBinary(endorsement.getEndorser().toByteArray()));
                    sb.append("\n");
                    sb.append("plainText bytes in hex: "
                            + DatatypeConverter.printHexBinary(plainText.toByteArray()));

                    logger.trace("payload TransactionBuilderbytes:  "
                            + diagnosticFileDumper.createDiagnosticFile(sb.toString()));
                }

            }

            if (sig == null || sig.isEmpty()) { // we shouldn't get here ...
                logger.warn(format("%s %s returned signature is empty verify set to false.", peer,
                        getTransactionID()));
                this.isVerified = false;
            } else {

                endorserCertifcate = endorser.getIdBytes().toByteArray();
                signature = sig.toByteArray();
                data = plainText.toByteArray();

                this.isVerified = crypto.verify(endorserCertifcate, config.getSignatureAlgorithm(), signature,
                        data);
                if (!this.isVerified) {
                    logger.warn(format(
                            "%s transaction: %s verify: Failed to verify. Endorsers certificate: %s, "
                                    + "signature: %s, signing algorithm: %s, signed data: %s.",
                            peer, getTransactionID(), toHexString(endorserCertifcate), toHexString(signature),
                            config.getSignatureAlgorithm(), toHexString(data)));
                }
            }

        } catch (InvalidProtocolBufferException | CryptoException e) {
            logger.error(format(
                    "%s transaction: %s verify: Failed to verify. Endorsers certificate: %s, "
                            + "signature: %s, signing algorithm: %s, signed data: %s.",
                    peer, getTransactionID(), toHexString(endorserCertifcate), toHexString(signature),
                    config.getSignatureAlgorithm(), toHexString(data)), e);

            logger.error(format(
                    "%s transaction: %s verify: Cannot retrieve peer identity from ProposalResponse. Error is: %s",
                    peer, getTransactionID(), e.getMessage()), e);
            this.isVerified = false;
        }

        logger.debug(format("%s finished verify for transaction %s returning %b", peer, getTransactionID(),
                this.isVerified));

        return this.isVerified;
    } finally {
        hasBeenVerified = true;
    }
}

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java

@Override
public boolean verify(byte[] pemCertificate, String signatureAlgorithm, byte[] signature, byte[] plainText)
        throws CryptoException {
    boolean isVerified = false;

    if (plainText == null || signature == null || pemCertificate == null) {
        return false;
    }//from  w ww .  j a va  2s  .c  o  m

    if (config.extraLogLevel(10)) {
        if (null != diagnosticFileDumper) {
            StringBuilder sb = new StringBuilder(10000);
            sb.append("plaintext in hex: ").append(DatatypeConverter.printHexBinary(plainText)).append("\n")
                    .append("signature in hex: " + DatatypeConverter.printHexBinary(signature)).append("\n")
                    .append("PEM cert in hex: " + DatatypeConverter.printHexBinary(pemCertificate));
            logger.trace("verify :  " + diagnosticFileDumper.createDiagnosticFile(sb.toString()));
        }
    }

    try {

        X509Certificate certificate = getX509Certificate(pemCertificate);

        if (certificate != null) {

            isVerified = validateCertificate(certificate);
            if (isVerified) { // only proceed if cert is trusted

                Signature sig = Signature.getInstance(signatureAlgorithm);
                sig.initVerify(certificate);
                sig.update(plainText);
                isVerified = sig.verify(signature);
            }
        }
    } catch (InvalidKeyException e) {
        CryptoException ex = new CryptoException("Cannot verify signature. Error is: " + e.getMessage()
                + "\r\nCertificate: " + DatatypeConverter.printHexBinary(pemCertificate), e);
        logger.error(ex.getMessage(), ex);
        throw ex;
    } catch (NoSuchAlgorithmException | SignatureException e) {
        CryptoException ex = new CryptoException(
                "Cannot verify. Signature algorithm is invalid. Error is: " + e.getMessage(), e);
        logger.error(ex.getMessage(), ex);
        throw ex;
    }

    return isVerified;
}

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java

/**
 * validateCertificate checks whether the given certificate is trusted. It
 * checks if the certificate is signed by one of the trusted certs in the
 * trust store./*  w w  w . j a v a2 s  .c  o  m*/
 *
 * @param certPEM the certificate in PEM format
 * @return true if the certificate is trusted
 */
boolean validateCertificate(byte[] certPEM) {

    if (certPEM == null) {
        return false;
    }

    try {

        X509Certificate certificate = getX509Certificate(certPEM);
        if (null == certificate) {
            throw new Exception("Certificate transformation returned null");
        }

        return validateCertificate(certificate);
    } catch (Exception e) {
        logger.error("Cannot validate certificate. Error is: " + e.getMessage() + "\r\nCertificate (PEM, hex): "
                + DatatypeConverter.printHexBinary(certPEM));
        return false;
    }
}

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java

/**
 * Decodes an ECDSA signature and returns a two element BigInteger array.
 *
 * @param signature ECDSA signature bytes.
 * @return BigInteger array for the signature's r and s values
 * @throws Exception/*from   ww w. ja v a  2s .  c  o  m*/
 */
private static BigInteger[] decodeECDSASignature(byte[] signature) throws Exception {

    try (ByteArrayInputStream inStream = new ByteArrayInputStream(signature)) {
        ASN1InputStream asnInputStream = new ASN1InputStream(inStream);
        ASN1Primitive asn1 = asnInputStream.readObject();

        BigInteger[] sigs = new BigInteger[2];
        int count = 0;
        if (asn1 instanceof ASN1Sequence) {
            ASN1Sequence asn1Sequence = (ASN1Sequence) asn1;
            ASN1Encodable[] asn1Encodables = asn1Sequence.toArray();
            for (ASN1Encodable asn1Encodable : asn1Encodables) {
                ASN1Primitive asn1Primitive = asn1Encodable.toASN1Primitive();
                if (asn1Primitive instanceof ASN1Integer) {
                    ASN1Integer asn1Integer = (ASN1Integer) asn1Primitive;
                    BigInteger integer = asn1Integer.getValue();
                    if (count < 2) {
                        sigs[count] = integer;
                    }
                    count++;
                }
            }
        }
        if (count != 2) {
            throw new CryptoException(
                    format("Invalid ECDSA signature. Expected count of 2 but got: %d. Signature is: %s", count,
                            DatatypeConverter.printHexBinary(signature)));
        }
        return sigs;
    }

}

From source file:org.hyperledger.fabric.sdk.transaction.ProtoUtils.java

public static ChannelHeader createChannelHeader(HeaderType type, String txID, String channelID, long epoch,
        Timestamp timeStamp, ChaincodeHeaderExtension chaincodeHeaderExtension, byte[] tlsCertHash) {

    if (isDebugLevel) {
        String tlschs = "";
        if (tlsCertHash != null) {
            tlschs = DatatypeConverter.printHexBinary(tlsCertHash);

        }//from w  w  w  . j ava 2 s . c om
        logger.debug(format(
                "ChannelHeader: type: %s, version: 1, Txid: %s, channelId: %s, epoch %d, clientTLSCertificate digest: %s",
                type.name(), txID, channelID, epoch, tlschs));

    }

    ChannelHeader.Builder ret = ChannelHeader.newBuilder().setType(type.getNumber()).setVersion(1).setTxId(txID)
            .setChannelId(channelID).setTimestamp(timeStamp).setEpoch(epoch);
    if (null != chaincodeHeaderExtension) {
        ret.setExtension(chaincodeHeaderExtension.toByteString());
    }

    if (tlsCertHash != null) {
        ret.setTlsCertHash(ByteString.copyFrom(tlsCertHash));
    }

    return ret.build();

}

From source file:org.iso.mpeg.dash.crypto.ContentProtectionMpegDashSea.java

/**
 * FIXME once sea schema is frozen, remove this abomination and generate JAXB objects
 * @return/*  w  w  w .ja v a  2s. c om*/
 * @throws DashCryptoException 
 * @deprecated Serialization to be done via JAXB in the near future
 */
private DescriptorType generateContentProtectionDescriptor() throws DashCryptoException {
    DescriptorType desc = new DescriptorType();
    desc.setSchemeIdUri(schemeIdUri);

    // xml motions
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new DashCryptoException(e);
    }
    Document document = builder.newDocument();

    // SegmentEncryption element
    Element segmentEncryptionXml = (Element) document.createElement(XML_ELEMENT_NAME_SEGMENT_ENCRYPTION);
    segmentEncryptionXml.setAttribute(XML_ATTR_NAME_ENCRYPTION_SYSTEM_URI,
            segmentEncryption.getEncryptionSystemUri());
    if (segmentEncryption.isIvEncryptionFlagBoolean() != null) {
        segmentEncryptionXml.setAttribute(XML_ATTR_NAME_IV_ENCRYPTION_FLAG,
                segmentEncryption.isIvEncryptionFlagBoolean().toString());
    }
    if (segmentEncryption.getEarlyAvailabilityDouble() != null) {
        segmentEncryptionXml.setAttribute(XML_ATTR_NAME_EARLY_AVAILABILITY,
                segmentEncryption.getEarlyAvailabilityDouble().toString());
    }
    if (segmentEncryption.getKeyLengthInteger() != null) {
        segmentEncryptionXml.setAttribute(XML_ATTR_NAME_KEY_LENGTH,
                segmentEncryption.getKeyLengthInteger().toString());
    }
    desc.getAnies().add(segmentEncryptionXml);

    // KeySystem elements
    for (Iterator<KeySystem> it = keySystems.iterator(); it.hasNext();) {
        KeySystem keySystem = it.next();
        Element keySystemXml = (Element) document.createElement(XML_ELEMENT_NAME_KEY_SYSTEM);
        keySystemXml.setAttribute(XML_ATTR_NAME_KEY_SYSTEM_URI, keySystem.getKeySystemUri());
        if (keySystem.getKeyLicenseUrlTemplate() != null)
            keySystemXml.setAttribute(XML_ATTR_NAME_KEY_LIC_URL_TEMPLATE, keySystem.getKeyLicenseUrlTemplate());
        desc.getAnies().add(keySystemXml);
    }

    // sole CryptoTimeline created by local encryption
    for (Iterator<CryptoPeriod> it = cryptoPeriods.iterator(); it.hasNext();) {
        CryptoPeriod cryptoPeriod = it.next();
        Element cryptoPeriodXml;

        switch (cryptoPeriod.type) {
        case CRYPTO_PERIOD: // add CryptoPeriod-specific attrs
            cryptoPeriodXml = (Element) document.createElement(XML_ELEMENT_NAME_CRYPTO_PERIOD);
            if (cryptoPeriod.getOffset() != null)
                cryptoPeriodXml.setAttribute(XML_ATTR_NAME_OFFSET, cryptoPeriod.getOffset().toString());
            break;
        case CRYPTO_TIMELINE: // add CryptoTimeline-specific attrs
            cryptoPeriodXml = (Element) document.createElement(XML_ELEMENT_NAME_CRYPTO_TIMELINE);
            CryptoTimeline cryptoTimeline = (CryptoTimeline) cryptoPeriod;
            if (cryptoTimeline.getNumCryptoPeriods() != null) {
                cryptoPeriodXml.setAttribute(XML_ATTR_NAME_NUM_CRYPTO_PERIODS,
                        Integer.toString(cryptoTimeline.getNumCryptoPeriods()));
            }
            if (cryptoTimeline.getFirstOffset() != null) {
                cryptoPeriodXml.setAttribute(XML_ATTR_NAME_FIRST_OFFSET,
                        Integer.toString(cryptoTimeline.getFirstOffset()));
            }
            break;
        default:
            throw new DashCryptoExceptionUnsupported("Unsupported CryptoPeriod type");
        }

        // add common fields
        cryptoPeriodXml.setAttribute(XML_ATTR_NAME_KEY_URI_TEMPLATE, cryptoPeriod.getKeyUriTemplate());
        if (cryptoPeriod.getNumSegments() != null)
            cryptoPeriodXml.setAttribute(XML_ATTR_NAME_NUM_SEGMENTS, cryptoPeriod.getNumSegments().toString());
        if (cryptoPeriod.getKeyLicenseUrlTemplate() != null)
            cryptoPeriodXml.setAttribute(XML_ATTR_NAME_KEY_LIC_URL_TEMPLATE,
                    cryptoPeriod.getKeyLicenseUrlTemplate());
        if (cryptoPeriod.getIvUriTemplate() != null)
            cryptoPeriodXml.setAttribute(XML_ATTR_NAME_IV_URI_TEMPLATE, cryptoPeriod.getIvUriTemplate());
        if (cryptoPeriod.getIV() != null)
            cryptoPeriodXml.setAttribute(XML_ATTR_NAME_IV,
                    DatatypeConverter.printHexBinary(cryptoPeriod.getIV()));

        desc.getAnies().add(cryptoPeriodXml);
    }

    return desc;
}

From source file:org.jivesoftware.util.StringUtils.java

/**
 * Turns an array of bytes into a String representing each byte as an
 * unsigned hex number.//from www . j  a v a2 s  . c o m
 *
 * @param bytes an array of bytes to convert to a hex-string
 * @return generated hex string
 */
public static String encodeHex(byte[] bytes) {
    return DatatypeConverter.printHexBinary(bytes).toLowerCase();
}