List of usage examples for org.apache.commons.codec.binary Hex Hex
public Hex()
From source file:com.linuxbox.enkive.message.AbstractBaseContentData.java
protected void calculateHash() { // if there's no data then there's no hash if (data == null) { clearHash();//from w w w . jav a 2 s . c om return; } MessageDigest md = null; try { md = MessageDigest.getInstance(HASH_ALGORITHM); } catch (NoSuchAlgorithmException e) { throw new EnkiveRuntimeException(e.getMessage()); } md.update(data); hashBytes = md.digest(); hashString = new String((new Hex()).encode(hashBytes)); }
From source file:de.betterform.xml.xforms.xpath.saxon.function.Digest.java
/** * Evaluate in a general context//from ww w.j a va 2s .c om */ public Item evaluateItem(XPathContext xpathContext) throws XPathException { // XXX In some cases the xforms-compute-exception should be an xforms-bind-exception final String data = argument[0].evaluateAsString(xpathContext).toString(); final String algorithm = argument[1].evaluateAsString(xpathContext).toString(); final String encoding = argument != null && argument.length >= 3 ? argument[2].evaluateAsString(xpathContext).toString() : kBASE64; if (!kSUPPORTED_ALG.contains(algorithm)) { XPathFunctionContext functionContext = getFunctionContext(xpathContext); XFormsElement xformsElement = functionContext.getXFormsElement(); throw new XPathException(new XFormsComputeException("Unsupported algorithm '" + algorithm + "'", xformsElement.getTarget(), this)); } if (!kSUPPORTED_ENCODINGS.contains(encoding)) { XPathFunctionContext functionContext = getFunctionContext(xpathContext); XFormsElement xformsElement = functionContext.getXFormsElement(); throw new XPathException(new XFormsComputeException("Unsupported encoding '" + encoding + "'", xformsElement.getTarget(), this)); } MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance(algorithm); messageDigest.update(data.getBytes("utf-8")); byte[] digest = messageDigest.digest(); final BinaryEncoder encoder; if ("base64".equals(encoding)) { encoder = new Base64(digest.length, "".getBytes(), false); } else { encoder = new Hex(); } return new StringValue(new String(encoder.encode(digest), "ASCII")); } catch (NoSuchAlgorithmException e) { throw new XPathException(e); } catch (UnsupportedEncodingException e) { throw new XPathException(e); } catch (EncoderException e) { XPathFunctionContext functionContext = getFunctionContext(xpathContext); XFormsElement xformsElement = functionContext.getXFormsElement(); throw new XPathException( new XFormsComputeException("Encoder exception.", e, xformsElement.getTarget(), this)); } }
From source file:com.bringcommunications.etherpay.SendActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); overlay_frame_layout = new FrameLayout(getApplicationContext()); setContentView(overlay_frame_layout); ////from www . j a v a 2 s . c o m context = this; hex = new Hex(); preferences = getSharedPreferences("etherpay.bringcommunications.com", MODE_PRIVATE); private_key = preferences.getString("key", private_key); acct_addr = preferences.getString("acct_addr", acct_addr); long wei_balance = preferences.getLong("balance", 0); eth_balance = (float) wei_balance / Util.WEI_PER_ETH; price = preferences.getFloat("price", price); show_gas = preferences.getBoolean("show_gas", show_gas); show_data = preferences.getBoolean("show_data", show_data); boolean denomination_eth = preferences.getBoolean("denomination_eth", true); System.out.println("denomination_eth is " + denomination_eth); denomination = denomination_eth ? Denomination.ETH : Denomination.FINNEY; auto_pay = getIntent().getStringExtra("AUTO_PAY"); to_addr = getIntent().getStringExtra("TO_ADDR"); String size_str = getIntent().getStringExtra("SIZE"); eth_size = Float.valueOf(size_str); data = getIntent().getStringExtra("DATA"); send_is_done = false; // View activity_send_view = getLayoutInflater().inflate(R.layout.activity_send, overlay_frame_layout, false); setContentView(activity_send_view); // Spinner dropdown = (Spinner) findViewById(R.id.denomination); String[] items = new String[] { "ETH", "Finney" }; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items); dropdown.setSelection((denomination == Denomination.ETH) ? 0 : 1); dropdown.setOnItemSelectedListener(this); dropdown.setAdapter(adapter); // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); String app_name = getResources().getString(R.string.app_name); toolbar.setTitle(app_name); toolbar.setSubtitle("Send Payment"); toolbar.setBackgroundResource(R.color.color_toolbar); setSupportActionBar(toolbar); // TextView to_addr_view = (TextView) findViewById(R.id.to_addr); to_addr_view.setText(to_addr); // TextView size_view = (TextView) findViewById(R.id.size); size_str = (denomination == Denomination.ETH) ? String.format("%1.03f", eth_size) : String.format("%03d", (int) (eth_size * 1000 + 0.5)); size_view.setText(size_str); // LinearLayout gas_layout = (LinearLayout) findViewById(R.id.gas_layout); TextView gas_prompt_view = (TextView) findViewById(R.id.gas_prompt); TextView gas_view = (TextView) findViewById(R.id.gas); ImageButton gas_help_view = (ImageButton) findViewById(R.id.gas_help); if (show_gas) { String gas_str = String.format("%7d", gas_limit); gas_view.setText(gas_str); gas_layout.setVisibility(View.VISIBLE); gas_prompt_view.setVisibility(View.VISIBLE); gas_help_view.setVisibility(View.VISIBLE); gas_view.setVisibility(View.VISIBLE); } else { gas_layout.setVisibility(View.GONE); gas_prompt_view.setVisibility(View.GONE); gas_help_view.setVisibility(View.GONE); gas_view.setVisibility(View.GONE); } LinearLayout data_layout = (LinearLayout) findViewById(R.id.data_layout); TextView data_prompt_view = (TextView) findViewById(R.id.data_prompt); TextView data_view = (TextView) findViewById(R.id.data); ImageButton data_help_view = (ImageButton) findViewById(R.id.data_help); if (show_data) { data_view.setText(data); data_layout.setVisibility(View.VISIBLE); data_prompt_view.setVisibility(View.VISIBLE); data_help_view.setVisibility(View.VISIBLE); data_view.setVisibility(View.VISIBLE); } else { data = ""; data_layout.setVisibility(View.GONE); data_prompt_view.setVisibility(View.GONE); data_help_view.setVisibility(View.GONE); data_view.setVisibility(View.GONE); } // //sanity check if (to_addr.length() != 42) { this.finish(); } }
From source file:com.lightboxtechnologies.spectrum.KeyUtilsTest.java
@Test public void getHashLengthSHA1() throws Exception { final Hex hex = new Hex(); final byte[] hash = hex.decode("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef".getBytes()); final byte[] entryID = FsEntryUtils.makeFsEntryKey( hex.decode("baadf00dbaadf00dbaadf00dbaadf00d".getBytes()), "/etc/passwd".getBytes(), 17); final byte[] rowKey = KeyUtils.makeEntryKey(hash, KeyUtils.SHA1, entryID); assertEquals(KeyUtils.SHA1_LEN, KeyUtils.getHashLength(rowKey)); }
From source file:de.betterform.xml.xforms.xpath.saxon.function.Hmac.java
/** * Evaluate in a general context/*from w w w .j a v a 2 s . co m*/ */ public Item evaluateItem(XPathContext xpathContext) throws XPathException { final String key = argument[0].evaluateAsString(xpathContext).toString(); final String data = argument[1].evaluateAsString(xpathContext).toString(); final String originalAlgorithmString = argument[2].evaluateAsString(xpathContext).toString(); final String algorithm = "Hmac" + originalAlgorithmString.replaceAll("-", ""); final String encoding = argument != null && argument.length >= 4 ? argument[3].evaluateAsString(xpathContext).toString() : kBASE64; if (!kSUPPORTED_ALG.contains(originalAlgorithmString)) { XPathFunctionContext functionContext = getFunctionContext(xpathContext); XFormsElement xformsElement = functionContext.getXFormsElement(); throw new XPathException(new XFormsComputeException( "Unsupported algorithm '" + originalAlgorithmString + "'", xformsElement.getTarget(), this)); } if (!kSUPPORTED_ENCODINGS.contains(encoding)) { XPathFunctionContext functionContext = getFunctionContext(xpathContext); XFormsElement xformsElement = functionContext.getXFormsElement(); throw new XPathException(new XFormsComputeException("Unsupported encoding '" + encoding + "'", xformsElement.getTarget(), this)); } try { // Generate a key for the HMAC-MD5 keyed-hashing algorithm; see RFC 2104 // In practice, you would save this key. SecretKey secretKey = new SecretKeySpec(key.getBytes("utf-8"), algorithm); // Create a MAC object using HMAC-MD5 and initialize with kesaxoniay Mac mac = Mac.getInstance(secretKey.getAlgorithm()); mac.init(secretKey); mac.update(data.getBytes("utf-8")); byte[] digest = mac.doFinal(); final BinaryEncoder encoder; if ("base64".equals(encoding)) { encoder = new Base64(digest.length, "".getBytes(), false); } else { encoder = new Hex(); } return new StringValue(new String(encoder.encode(digest), "ASCII")); } catch (NoSuchAlgorithmException e) { throw new XPathException(e); } catch (UnsupportedEncodingException e) { throw new XPathException(e); } catch (EncoderException e) { XPathFunctionContext functionContext = getFunctionContext(xpathContext); XFormsElement xformsElement = functionContext.getXFormsElement(); throw new XPathException( new XFormsComputeException("Encoder exception.", e, xformsElement.getTarget(), this)); } catch (InvalidKeyException e) { throw new XPathException(e); } }
From source file:com.the_incognito.darry.incognitochatmessengertest.BouncyCastleImplementation.java
public static String hmacSha256(String key, String value) { try {//from w ww .ja v a 2s . com //System.out.println(Base64.getEncoder().encodeToString(keyBytes)); // Get an hmac_sha256 key from the raw key bytes System.out.println("First HMAC on = " + value); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256", new BouncyCastleProvider()); char password[] = key.toCharArray(); byte salt[] = "salt".getBytes(); KeySpec spec = new PBEKeySpec(password, salt, 65536, 256); SecretKey tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "HmacSHA256"); // Get an hmac_sha256 Mac instance and initialize with the signing key Mac mac = Mac.getInstance("HmacSHA256", new BouncyCastleProvider()); mac.init(secret); // Compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(value.getBytes()); // Convert raw bytes to Hex byte[] hexBytes = new Hex().encode(rawHmac); // Covert array of Hex bytes to a String return new String(hexBytes, "UTF-8"); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:hudson.plugins.sauce_ondemand.PluginImpl.java
/** * Creates a HMAC token which is used as part of the Javascript inclusion that embeds the Sauce results * * @param username the Sauce user id// www .j a v a 2 s .com * @param accessKey the Sauce access key * @param jobId the Sauce job id * @return the HMAC token * @throws java.security.NoSuchAlgorithmException * * @throws java.security.InvalidKeyException * * @throws java.io.UnsupportedEncodingException * */ public String calcHMAC(String username, String accessKey, String jobId) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { Calendar calendar = Calendar.getInstance(); SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); format.setTimeZone(TimeZone.getTimeZone("UTC")); String key = username + ":" + accessKey + ":" + format.format(calendar.getTime()); byte[] keyBytes = key.getBytes(); SecretKeySpec sks = new SecretKeySpec(keyBytes, HMAC_KEY); Mac mac = Mac.getInstance(sks.getAlgorithm()); mac.init(sks); byte[] hmacBytes = mac.doFinal(jobId.getBytes()); byte[] hexBytes = new Hex().encode(hmacBytes); return new String(hexBytes, "ISO-8859-1"); }
From source file:com.sap.dirigible.runtime.scripting.AbstractScriptExecutor.java
protected void registerDefaultVariables(HttpServletRequest request, HttpServletResponse response, Object input, Map<Object, Object> executionContext, IRepository repository, Object scope) { // put the execution context registerDefaultVariable(scope, "context", executionContext); //$NON-NLS-1$ // put the system out registerDefaultVariable(scope, "out", System.out); //$NON-NLS-1$ // put the default data source DataSource dataSource = null; if (repository instanceof DBRepository) { dataSource = ((DBRepository) repository).getDataSource(); } else {//from w w w .ja v a 2 s . c o m dataSource = RepositoryFacade.getInstance().getDataSource(); } registerDefaultVariable(scope, "datasource", dataSource); //$NON-NLS-1$ // put request registerDefaultVariable(scope, "request", request); //$NON-NLS-1$ // put response registerDefaultVariable(scope, "response", response); //$NON-NLS-1$ // put repository registerDefaultVariable(scope, "repository", repository); //$NON-NLS-1$ // put mail sender MailSender mailSender = new MailSender(); registerDefaultVariable(scope, "mail", mailSender); //$NON-NLS-1$ // put Apache Commons IOUtils IOUtils ioUtils = new IOUtils(); registerDefaultVariable(scope, "io", ioUtils); //$NON-NLS-1$ // put Apache Commons HttpClient and related classes wrapped with a // factory like HttpUtils HttpUtils httpUtils = new HttpUtils(); registerDefaultVariable(scope, "http", httpUtils); //$NON-NLS-1$ // put Apache Commons Codecs Base64 base64Codec = new Base64(); registerDefaultVariable(scope, "base64", base64Codec); //$NON-NLS-1$ Hex hexCodec = new Hex(); registerDefaultVariable(scope, "hex", hexCodec); //$NON-NLS-1$ DigestUtils digestUtils = new DigestUtils(); registerDefaultVariable(scope, "digest", digestUtils); //$NON-NLS-1$ // standard URLEncoder and URLDecoder functionality URLUtils urlUtils = new URLUtils(); registerDefaultVariable(scope, "url", urlUtils); //$NON-NLS-1$ // user name registerDefaultVariable(scope, "user", RepositoryFacade.getUser(request)); //$NON-NLS-1$ // file upload ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory()); registerDefaultVariable(scope, "upload", fileUpload); //$NON-NLS-1$ // UUID UUID uuid = new UUID(0, 0); registerDefaultVariable(scope, "uuid", uuid); //$NON-NLS-1$ // the input from the execution chain if any registerDefaultVariable(scope, "input", input); //$NON-NLS-1$ // DbUtils DbUtils dbUtils = new DbUtils(dataSource); registerDefaultVariable(scope, "db", dbUtils); //$NON-NLS-1$ // EscapeUtils StringEscapeUtils stringEscapeUtils = new StringEscapeUtils(); registerDefaultVariable(scope, "xss", stringEscapeUtils); //$NON-NLS-1$ // Extension Manager ExtensionManager extensionManager = new ExtensionManager(repository, dataSource); registerDefaultVariable(scope, "extensionManager", extensionManager); //$NON-NLS-1$ // Apache Lucene Indexer IndexerUtils indexerUtils = new IndexerUtils(); registerDefaultVariable(scope, "indexer", indexerUtils); //$NON-NLS-1$ // Mylyn Confluence Format WikiUtils wikiUtils = new WikiUtils(); registerDefaultVariable(scope, "wiki", wikiUtils); //$NON-NLS-1$ // Simple binary storage StorageUtils storageUtils = new StorageUtils(dataSource); registerDefaultVariable(scope, "storage", storageUtils); //$NON-NLS-1$ // Simple file storage FileStorageUtils fileStorageUtils = new FileStorageUtils(dataSource); registerDefaultVariable(scope, "fileStorage", fileStorageUtils); //$NON-NLS-1$ // Simple binary storage ConfigStorageUtils configStorageUtils = new ConfigStorageUtils(dataSource); registerDefaultVariable(scope, "config", configStorageUtils); //$NON-NLS-1$ // XML to JSON and vice-versa XMLUtils xmlUtils = new XMLUtils(); registerDefaultVariable(scope, "xml", xmlUtils); //$NON-NLS-1$ }
From source file:com.lightboxtechnologies.spectrum.KeyUtilsTest.java
@Test public void retrieveFsEntryID() throws Exception { final Hex hex = new Hex(); final byte[] hash = hex.decode("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef".getBytes()); final byte[] entryID = FsEntryUtils.makeFsEntryKey( hex.decode("baadf00dbaadf00dbaadf00dbaadf00d".getBytes()), "/etc/passwd".getBytes(), 17); final byte[] rowKey = KeyUtils.makeEntryKey(hash, KeyUtils.SHA1, entryID); assertArrayEquals(entryID, KeyUtils.getFsEntryID(rowKey)); }
From source file:com.rsmart.rfabric.jasperreports.auth.Signature.java
/** * Calculate an RFC2104 compliant HMAC (Hash-based Message Authentication * Code)/*w w w .ja v a 2 s .com*/ * * @param data * The data to be signed. This data is pushed through a hex * converter in this method, so there is no need to do this * before generating the HMAC. * @param key * The signing key. * @param urlSafe * true if the token needs to be URL safe. * @return The Base64-encoded RFC 2104-compliant HMAC signature. * @throws InvalidKeyException * This is the exception for invalid Keys (invalid encoding, * wrong length, uninitialized, etc). */ @SuppressWarnings("PMD.DataflowAnomalyAnalysis") public String calculateRFC2104HMACWithEncoding(final String data, final String key, final boolean urlSafe) throws InvalidKeyException { if (data == null) { throw new IllegalArgumentException("String data == null"); } if (key == null) { throw new IllegalArgumentException("String key == null"); } String result = null; try { // Get an hmac_sha1 key from the raw key bytes final byte[] keyBytes = key.getBytes("UTF-8"); final SecretKeySpec signingKey = new SecretKeySpec(keyBytes, hmacSha1Algorithm); // initialize with the signing key mac.init(signingKey); // Compute the hmac on input data bytes final byte[] rawHmac = mac.doFinal(data.getBytes()); // Convert raw bytes to Hex byte[] hexBytes = new Hex().encode(rawHmac); // Convert raw bytes to encoding final byte[] base64Bytes = Base64.encodeBase64(hexBytes, false, urlSafe); result = new String(base64Bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { LOG.error(e.getMessage(), e); } return result; }