Example usage for org.apache.commons.codec.binary Hex encodeHexString

List of usage examples for org.apache.commons.codec.binary Hex encodeHexString

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Hex encodeHexString.

Prototype

public static String encodeHexString(byte[] data) 

Source Link

Document

Converts an array of bytes into a String representing the hexadecimal values of each byte in order.

Usage

From source file:eu.europa.esig.dss.client.tsp.OnlineTSPSource.java

@Override
public TimeStampToken getTimeStampResponse(final DigestAlgorithm digestAlgorithm, final byte[] digest)
        throws DSSException {
    try {/*  ww  w  .j  av a2s .c o  m*/
        if (logger.isTraceEnabled()) {
            logger.trace("Timestamp digest algorithm: " + digestAlgorithm.getName());
            logger.trace("Timestamp digest value    : " + Hex.encodeHexString(digest));
        }

        // Setup the time stamp request
        final TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
        tsqGenerator.setCertReq(true);
        if (policyOid != null) {
            tsqGenerator.setReqPolicy(policyOid);
        }

        ASN1ObjectIdentifier asn1ObjectIdentifier = new ASN1ObjectIdentifier(digestAlgorithm.getOid());
        TimeStampRequest timeStampRequest = null;
        if (nonceSource == null) {
            timeStampRequest = tsqGenerator.generate(asn1ObjectIdentifier, digest);
        } else {
            timeStampRequest = tsqGenerator.generate(asn1ObjectIdentifier, digest, nonceSource.getNonce());
        }

        final byte[] requestBytes = timeStampRequest.getEncoded();

        // Call the communications layer
        if (dataLoader == null) {
            dataLoader = new NativeHTTPDataLoader();
        }
        byte[] respBytes = dataLoader.post(tspServer, requestBytes);

        // Handle the TSA response
        final TimeStampResponse timeStampResponse = new TimeStampResponse(respBytes);

        // Validates nonce, policy id, ... if present
        timeStampResponse.validate(timeStampRequest);

        String statusString = timeStampResponse.getStatusString();
        if (statusString != null) {
            logger.info("Status: " + statusString);
        }

        final TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();

        if (timeStampToken != null) {
            logger.info("TSP SID : SN " + timeStampToken.getSID().getSerialNumber() + ", Issuer "
                    + timeStampToken.getSID().getIssuer());
        }

        return timeStampToken;
    } catch (TSPException e) {
        throw new DSSException("Invalid TSP response", e);
    } catch (IOException e) {
        throw new DSSException(e);
    }
}

From source file:com.t3.guid.GUID.java

/** Returns a string for the GUID. */
@Override
public String toString() {
    return Hex.encodeHexString(baGUID);
}

From source file:de.resol.vbus.TelegramTest.java

@Test
public void testToLiveBuffer() throws Exception {
    String refValue1 = "aa2211443330772e000c1824303c48000354606c7804101c70472834404c5864707f6c";

    byte[] testData1 = new byte[3 * 7];
    for (int i = 0; i < testData1.length; i++) {
        testData1[i] = (byte) (i * 12);
    }/*  w w  w . ja v  a 2  s.  c o m*/

    Telegram testTgram1 = new Telegram(0, 0, 0x1122, 0x3344, 0x77, testData1);
    byte[] testBuffer1 = testTgram1.toLiveBuffer(null, 0, 0);
    assertEquals(refValue1, Hex.encodeHexString(testBuffer1));

    byte[] testBuffer2 = new byte[testBuffer1.length + 2];
    assertEquals(testBuffer2, testTgram1.toLiveBuffer(testBuffer2, 1, testBuffer2.length - 1));
    assertEquals("00" + refValue1 + "00", Hex.encodeHexString(testBuffer2));

    assertEquals(null, testTgram1.toLiveBuffer(testBuffer2, 3, testBuffer2.length - 3));
}

From source file:be.fedict.eid.applet.service.signer.SHA1WithRSAProxySignature.java

@Override
protected void engineUpdate(byte[] b, int off, int len) throws SignatureException {
    LOG.debug("engineUpdate(b,off,len): off=" + off + "; len=" + len);
    this.messageDigest.update(b, off, len);
    byte[] digestValue = this.messageDigest.digest();
    byte[] expectedDigestValue = SHA1WithRSAProxySignature.digestValues.get();
    if (null == expectedDigestValue) {
        SHA1WithRSAProxySignature.digestValues.set(digestValue);
    } else {/*from  ww w .j  ava2 s .c  o m*/
        if (false == Arrays.areEqual(expectedDigestValue, digestValue)) {
            throw new IllegalStateException("digest value has changed");
        }
    }
    LOG.debug("digest value: " + Hex.encodeHexString(digestValue));
}

From source file:com.netscape.cmstools.pkcs12.PKCS12KeyRemoveCLI.java

public void execute(String[] args) throws Exception {

    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("help")) {
        printHelp();//from ww  w .j a  va2s. c o m
        return;
    }

    if (cmd.hasOption("verbose")) {
        PKILogger.setLevel(PKILogger.Level.INFO);

    } else if (cmd.hasOption("debug")) {
        PKILogger.setLevel(PKILogger.Level.DEBUG);
    }

    String[] cmdArgs = cmd.getArgs();

    if (cmdArgs.length == 0) {
        throw new Exception("Missing key ID.");
    }

    byte[] keyID = Hex.decodeHex(cmdArgs[0].toCharArray());

    String filename = cmd.getOptionValue("pkcs12-file");

    if (filename == null) {
        throw new Exception("Missing PKCS #12 file.");
    }

    String passwordString = cmd.getOptionValue("pkcs12-password");

    if (passwordString == null) {

        String passwordFile = cmd.getOptionValue("pkcs12-password-file");
        if (passwordFile != null) {
            try (BufferedReader in = new BufferedReader(new FileReader(passwordFile))) {
                passwordString = in.readLine();
            }
        }
    }

    if (passwordString == null) {
        throw new Exception("Missing PKCS #12 password.");
    }

    Password password = new Password(passwordString.toCharArray());

    try {
        PKCS12Util util = new PKCS12Util();

        PKCS12 pkcs12 = util.loadFromFile(filename, password);
        pkcs12.removeKeyInfoByID(keyID);
        util.storeIntoFile(pkcs12, filename, password);

    } finally {
        password.clear();
    }

    MainCLI.printMessage("Deleted key \"" + Hex.encodeHexString(keyID) + "\"");
}

From source file:com.romeikat.datamessie.core.base.service.AuthenticationServiceTest.java

@Test
@Ignore//from  w w w. j av  a  2s .com
public void createSaltAndHash() {
    final String password = "test";
    final byte[] salt = authenticationService.createSalt();
    final byte[] hash = authenticationService.calculateHash(password, salt);

    LOG.info("Password: {}", password);
    LOG.info("Salt: {}", Hex.encodeHexString(salt));
    LOG.info("Hash: {}", Hex.encodeHexString(hash));
}

From source file:ai.serotonin.backup.Backup.java

private File encryptFile(final File file) throws Exception {
    final SecureRandom random = new SecureRandom();
    final byte[] salt = random.generateSeed(8);
    final String saltStr = Hex.encodeHexString(salt);

    final SecretKey secret = createSecretKey(salt);

    final Cipher cipher = createCipher();
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    final AlgorithmParameters params = cipher.getParameters();
    final byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
    final String ivStr = Hex.encodeHexString(iv);

    final File encryptedFile = new File(file.getParent(), saltStr + "_" + ivStr + "_" + file.getName());

    cipherizeFile(file, encryptedFile, cipher);

    file.delete();/* w w w.  j a v  a2 s.  co m*/

    LOG.info("Encrypted backup file to " + encryptedFile.getPath() + ", "
            + FileUtils.byteCountToDisplaySize(encryptedFile.length()));
    return encryptedFile;
}

From source file:fi.csc.idp.stepup.impl.DigestChallengeGenerator.java

@Override
public String generate(String target) throws Exception {

    String challenge = "";
    // to explicitly support generating empty challenge
    if (maxLength == 0) {

        return challenge;
    }//from   w  w  w . j  a v a  2 s.c om
    try {
        String time = "" + System.currentTimeMillis();
        MessageDigest md = MessageDigest.getInstance(digest);
        // to make challenge user specific
        if (target != null) {
            md.update(target.getBytes());
        }
        // to make challenge installation specific
        md.update(salt.getBytes());
        // to make challenge time specific
        md.update(time.getBytes());
        byte[] buffer = md.digest();
        if (useDecimal) {
            // output a decimal string
            for (byte data : buffer) {
                // operation reduces unpredictability a bit
                challenge += (int) data & 0xFF;
            }
        } else {
            // ouput a hexstring
            challenge = Hex.encodeHexString(buffer);
        }

    } catch (NoSuchAlgorithmException e) {
        log.error("Unable to generate challenge {}", e.getMessage());

        return null;
    }

    return challenge.substring(0, challenge.length() > maxLength ? maxLength : challenge.length());
}

From source file:com.thoughtworks.go.domain.AccessToken.java

static String digestToken(String originalToken, String salt) {
    try {//from   w w w .  j a va  2  s .  c o m
        ACCESS_TOKEN_LOGGER.debug(
                "Generating secret using algorithm: {} with spec: DEFAULT_ITERATIONS: {}, DESIRED_KEY_LENGTH: {}",
                KEY_ALGORITHM, DEFAULT_ITERATIONS, DESIRED_KEY_LENGTH);
        SecretKeyFactory factory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
        SecretKey key = factory.generateSecret(new PBEKeySpec(originalToken.toCharArray(), salt.getBytes(),
                DEFAULT_ITERATIONS, DESIRED_KEY_LENGTH));
        return Hex.encodeHexString(key.getEncoded());
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw new RuntimeException(e);
    }
}

From source file:gobblin.source.extractor.extract.kafka.KafkaAvroExtractor.java

@Override
protected GenericRecord decodeRecord(MessageAndOffset messageAndOffset)
        throws SchemaNotFoundException, IOException {
    byte[] payload = getBytes(messageAndOffset.message().payload());
    if (payload[0] != KafkaAvroSchemaRegistry.MAGIC_BYTE) {
        throw new RuntimeException(
                String.format("Unknown magic byte for partition %s", this.getCurrentPartition()));
    }/* w  w  w.  ja  v  a  2s.  c  o  m*/

    byte[] schemaIdByteArray = Arrays.copyOfRange(payload, 1,
            1 + KafkaAvroSchemaRegistry.SCHEMA_ID_LENGTH_BYTE);
    String schemaId = Hex.encodeHexString(schemaIdByteArray);
    Schema schema = null;
    schema = this.schemaRegistry.getSchemaById(schemaId);
    reader.get().setSchema(schema);
    Decoder binaryDecoder = DecoderFactory.get().binaryDecoder(payload,
            1 + KafkaAvroSchemaRegistry.SCHEMA_ID_LENGTH_BYTE,
            payload.length - 1 - KafkaAvroSchemaRegistry.SCHEMA_ID_LENGTH_BYTE, null);
    try {
        GenericRecord record = reader.get().read(null, binaryDecoder);
        if (!record.getSchema().equals(this.schema.get())) {
            record = AvroUtils.convertRecordSchema(record, this.schema.get());
        }
        return record;
    } catch (IOException e) {
        LOG.error(String.format("Error during decoding record for partition %s: ", this.getCurrentPartition()));
        throw e;
    }
}