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

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

Introduction

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

Prototype

public static byte[] decodeHex(char[] data) throws IllegalArgumentException 

Source Link

Document

Converts an array of characters representing hexadecimal values into an array of bytes of those same values.

Usage

From source file:com.intellij.ide.passwordSafe.impl.providers.masterKey.PasswordDatabase.java

/**
 * Covert hex to bytes// w  w  w. java  2s  .  c o  m
 *
 * @param hex string to convert
 * @return bytes representation
 * @throws DecoderException if invalid data encountered
 */
@Nullable
private static byte[] fromHex(String hex) throws DecoderException {
    return hex == null ? null : Hex.decodeHex(hex.toCharArray());
}

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

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

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

    if (cmd.hasOption("help")) {
        printHelp();// w w w  .  ja  v  a2 s.  com
        return;
    }

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

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

    String[] cmdArgs = cmd.getArgs();
    String id = cmd.getOptionValue("cert-id");

    if (cmdArgs.length < 1 && id == null) {
        throw new Exception("Missing certificate nickname or ID.");
    }

    if (cmdArgs.length >= 1 && id != null) {
        throw new Exception("Certificate nickname and ID are mutually exclusive.");
    }

    String nickname = null;
    byte[] certID = null;

    if (cmdArgs.length >= 1) {
        nickname = cmdArgs[0];
    } else {
        certID = Hex.decodeHex(id.toCharArray());
    }

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

    if (pkcs12File == 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());

    String certFile = cmd.getOptionValue("cert-file");

    if (certFile == null) {
        throw new Exception("Missing certificate file.");
    }

    try {
        PKCS12Util util = new PKCS12Util();
        PKCS12 pkcs12 = util.loadFromFile(pkcs12File, password);

        Collection<PKCS12CertInfo> certInfos = new ArrayList<PKCS12CertInfo>();

        if (nickname != null) {
            certInfos.addAll(pkcs12.getCertInfosByFriendlyName(nickname));

        } else {
            PKCS12CertInfo certInfo = pkcs12.getCertInfoByID(certID);
            if (certInfo != null) {
                certInfos.add(certInfo);
            }
        }

        if (certInfos.isEmpty()) {
            throw new Exception("Certificate not found.");
        }

        try (PrintStream os = new PrintStream(new FileOutputStream(certFile))) {
            for (PKCS12CertInfo certInfo : certInfos) {
                X509CertImpl cert = certInfo.getCert();
                os.println(Cert.HEADER);
                os.print(Utils.base64encode(cert.getEncoded(), true));
                os.println(Cert.FOOTER);
            }
        }

    } finally {
        password.clear();
    }
}

From source file:com.cliqset.magicsig.algorithm.test.RSASHA256MagicSignatureAlgorithmTest.java

@Test
public void testExceptionVerifyNullKey() {
    try {//from   w  w  w .  j  a  va2  s . c om
        RSASHA256MagicSigAlgorithm alg = new RSASHA256MagicSigAlgorithm();
        alg.verify(stringData.substring(1).getBytes("UTF-8"), Hex.decodeHex(hexSig.toCharArray()), null);
        Assert.fail();
    } catch (IllegalArgumentException iae) {
        Assert.assertTrue(true);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }
}

From source file:com.predic8.membrane.balancer.client.LBNotificationClient.java

private void parseArguments(CommandLine cl) throws Exception {
    if (!new File(propertiesFile).exists())
        log.warn("no properties file found at: " + new File(propertiesFile).getAbsolutePath());

    cmd = getArgument(cl, 0, '-', null, null, "No command up, down or takeout specified!");
    host = getArgument(cl, 1, 'H', null, null, "No host name specified!");
    port = getArgument(cl, 2, 'p', null, "80", "");
    balancer = getArgument(cl, -1, 'b', null, Balancer.DEFAULT_NAME, "");
    cluster = getArgument(cl, -1, 'c', null, Cluster.DEFAULT_NAME, "");
    cmURL = getArgument(cl, -1, 'u', "clusterManager", null, "No cluster manager location found!");
    String key = getArgument(cl, -1, '-', "key", "", null);
    if (!"".equals(key)) {
        skeySpec = new SecretKeySpec(Hex.decodeHex(key.toCharArray()), "AES");
    }//from   w  w w  . jav a2s .  co  m
}

From source file:com.bitbreeds.webrtc.common.SignalUtilTest.java

@Test
public void findIntegrity() throws DecoderException {

    String bytes = "000100502112a442e9dec49e8038338d00f9a79c0006001162323064306166343a623230643061663400000000250000002400046e7f00ff802a00081eb6ff2cf7589cd700080014020b27ff78fbd931427c9f4518b9f40d5415562e8028000473cf7c86";

    String noFinger2 = "000100482112a442e9dec49e8038338d00f9a79c0006001162323064306166343a623230643061663400000000250000002400046e7f00ff802a00081eb6ff2cf7589cd7";

    byte[] msg = Hex.decodeHex(noFinger2.toCharArray());

    byte[] mac = Hex.decodeHex("020b27ff78fbd931427c9f4518b9f40d5415562e".toCharArray());

    String password = "230f754083a9070aff5bd1ced7654a9c";

    byte[] compMac = SignalUtil.hmacSha1(msg, password.getBytes());

    System.out.println(Hex.encodeHexString(mac) + "  " + Hex.encodeHexString(compMac));
    assertTrue(Arrays.equals(mac, compMac));
}

From source file:epgtools.dumpservicefromnit.Main.java

public void start(String[] args)
        throws org.apache.commons.cli.ParseException, FileNotFoundException, IOException {
    final byte[] sectionByte;
    final SERVICE_TYPE serviceType;
    final Option sectionDumpOption = Option.builder("s").required().longOpt("section")
            .desc("?hex").hasArg().type(String.class).build();

    final Option serviceTypeOption = Option.builder("t").required(false).longOpt("servicetype")
            .desc("?").hasArg().type(Integer.class).build();

    Options opts = new Options();
    opts.addOption(sectionDumpOption);// w w w  . ja v  a  2  s .com
    opts.addOption(serviceTypeOption);
    CommandLineParser parser = new DefaultParser();
    CommandLine cl;
    HelpFormatter help = new HelpFormatter();

    try {

        // parse options
        cl = parser.parse(opts, args);

        try {
            sectionByte = Hex.decodeHex(cl.getOptionValue(sectionDumpOption.getOpt()).toCharArray());
        } catch (DecoderException ex) {
            LOG.error(ex);
            throw new ParseException("hex??????");
        }

        serviceType = SERVICE_TYPE
                .reverseLookUp(Integer.parseInt(cl.getOptionValue(serviceTypeOption.getOpt()), 16));

    } catch (ParseException e) {
        // print usage.
        help.printHelp("My Java Application", opts);
        throw e;
    }

    LOG.info("Starting application...");
    LOG.info("section           : " + Hex.encodeHexString(sectionByte));
    LOG.info("service type      : " + serviceType);

    Section section = new Section(sectionByte);

    if (section.checkCRC() != CRC_STATUS.NO_CRC_ERROR) {
        LOG.error("CRC??");
    }

    if (section.getTable_id_const() != TABLE_ID.NIT_THIS_NETWORK
            && section.getTable_id_const() != TABLE_ID.NIT_OTHER_NETWORK) {
        LOG.error("NIT?????");
    }

    NetworkInformationTableBody nitbody = (NetworkInformationTableBody) section.getSectionBody();

    final int networkId = nitbody.getNetwork_id();
    LOG.info("networkId = " + Integer.toHexString(networkId));

    for (Descriptor d1 : nitbody.getDescriptors_loop().getDescriptors_loopList()) {
        final String networkName;
        if (d1.getDescriptor_tag_const() == DESCRIPTOR_TAG.NETWORK_NAME_DESCRIPTOR) {
            final NetworkNameDescriptor nnd = (NetworkNameDescriptor) d1;
            networkName = nnd.getChar_String();
            LOG.info("networkName = " + networkName);
        }
    }

    final List<TransportStreamLoop> tsLoopList = nitbody.getTransport_streams_loop();

    for (TransportStreamLoop tsLoop : tsLoopList) {
        final int transportStreamId = tsLoop.getTransport_stream_id();
        LOG.info("transportStreamId = " + Integer.toHexString(transportStreamId));
        final int originalNetworkId = tsLoop.getOriginal_network_id();
        LOG.info("originalNetworkId = " + Integer.toHexString(originalNetworkId));
        final DescriptorsLoop dloop = tsLoop.getDescriptors_loop();
        final List<Descriptor> dList = dloop.getDescriptors_loopList();
        for (Descriptor desc : dList) {

            if (desc.getDescriptor_tag_const() == DESCRIPTOR_TAG.SERVICE_LIST_DESCRIPTOR) {
                ServiceListDescriptor sd = (ServiceListDescriptor) desc;
                List<Service> svList = sd.getServiceList();
                for (Service service : svList) {
                    if (service.getService_type_Enum() == serviceType) {
                        final int serviceId = service.getService_id();
                        LOG.info("serviceId = " + Integer.toHexString(serviceId));
                    }
                }
            }
        }
    }

}

From source file:libepg.epg.section.descriptor.contentdescriptor.ContentDescriptorTest.java

/**
 * Test of toString method, of class ContentDescriptor.
 *
 * @throws java.lang.reflect.InvocationTargetException
 * @throws org.apache.commons.codec.DecoderException
 *///from  w w w  .  j  ava2s.co m
@Test
public void testToString2() throws InvocationTargetException, DecoderException {
    LOG.debug("toString2");
    ContentDescriptor instance = new ContentDescriptor(
            Descriptors.init(Hex.decodeHex("540260ff".toCharArray())));
    LOG.debug(instance);

}

From source file:be.fedict.eid.idp.model.CryptoUtil.java

public static SecretKey getSecretKey(SecretKeyAlgorithm secretKeyAlgorithm, String encodedSecretKey)
        throws DecoderException {

    byte[] secretKeyBytes = Hex.decodeHex(encodedSecretKey.toCharArray());

    String algorithm = null;//  w w  w . ja va2 s . com
    switch (secretKeyAlgorithm) {

    case NONE:
        return null;
    case AES_128:
        algorithm = "AES";
        break;
    }

    return new SecretKeySpec(secretKeyBytes, algorithm);
}

From source file:mitm.common.security.crl.GenerateTestCRLs.java

private PrivateKey decodePrivateKey(String encoded) throws Exception {
    byte[] rawKey = Hex.decodeHex(encoded.toCharArray());

    KeySpec keySpec = new PKCS8EncodedKeySpec(rawKey);

    KeyFactory keyFactory = securityFactory.createKeyFactory("RSA");

    return keyFactory.generatePrivate(keySpec);
}

From source file:io.manasobi.utils.CryptoUtils.java

/**
 * ? ??  , ? ?? ./*from w ww. j  a  v  a2  s  .com*/
 *
 * @param keyHex   generateHexKey ? ? ?? Hex ? ? 
 * @param data      ? ?
 * @param encoding ? ?
 * 
 * @return ? ?
 */
public static String decryptByDES(String keyHex, String data, String encoding) {

    String decryptedString = null;
    try {

        byte[] unhexedData = Hex.decodeHex(data.toCharArray());

        byte[] decryptedData = decryptByDES(keyHex, unhexedData);

        decryptedString = new String(decryptedData, encoding);

    } catch (Exception e) {

        throw new CryptoUtilsException(e.getMessage());
    }

    return decryptedString;
}