public static byte[] publicKeyToAddress(String string) { byte[] publicKeyBytes = null; try { publicKeyBytes = org.apache.commons.codec.binary.Hex.decodeHex(string.toCharArray()); } catch (DecoderException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // System.out.println(Utils.toHex(publicKeyBytes)); // System.out.println(publicKeyBytes.length); byte[] out = new byte[20]; byte[] hash = new byte[256]; byte[] hash2 = new byte[256]; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); hash = digest.digest(publicKeyBytes); hash2 = digest.digest(hash); RIPEMD160Digest digest160 = new RIPEMD160Digest(); digest160.update(hash, 0, hash.length); digest160.doFinal(out, 0); } catch (Exception e) { // TODO: handle exception } byte[] ripemd_bytes = null; byte[] checksum = new byte[4]; try { ripemd_bytes = org.apache.commons.codec.binary.Hex.decodeHex( ("00" + Utils.toHex(out).toUpperCase()).toCharArray()); } catch (DecoderException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); hash = digest.digest(ripemd_bytes); hash2 = digest.digest(hash); } catch (Exception e) { // TODO: handle exception } System.arraycopy(hash2, 0, checksum, 0, checksum.length); byte[] combined = new byte[1 + out.length + checksum.length]; for (int i = 0; i < combined.length; ++i) { combined[i] = i < ripemd_bytes.length ? ripemd_bytes[i] : checksum[i - ripemd_bytes.length]; } // System.out.println(Utils.toHex(combined)); return (combined); }
public String decrypt(String valor, String chave, String vetor) throws Exception { byte[] v = Hex.decodeHex(valor.toCharArray()); byte[] c = Hex.decodeHex(chave.toCharArray()); byte[] iv = Hex.decodeHex(vetor.toCharArray()); SecretKeySpec k = new SecretKeySpec(c, "AES"); AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv); Cipher dcipher = Cipher.getInstance("AES/CBC/NoPadding"); dcipher.init(Cipher.DECRYPT_MODE, k, paramSpec); return new String(dcipher.doFinal(v)).replaceAll("\0", ""); }
private static void bcDES() throws Exception { Security.addProvider(new BouncyCastleProvider()); // Key convert DESKeySpec desKeySpec = new DESKeySpec(bytesKey); SecretKeyFactory factory = SecretKeyFactory.getInstance("DES", "BC"); SecretKey desKey = factory.generateSecret(desKeySpec); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, desKey); System.out.println("BC" + cipher.getProvider()); byte[] result = cipher.doFinal("ABC".getBytes()); String hexResult = Hex.encodeHexString(result); System.out.println(hexResult); cipher.init(Cipher.DECRYPT_MODE, desKey); result = cipher.doFinal( Hex.decodeHex(hexResult.toCharArray()) // result ); System.out.println(new String(result)); }
/** Hex解码. */ public static byte[] hexDecode(String input) { try { return Hex.decodeHex(input.toCharArray()); } catch (DecoderException e) { throw new IllegalStateException("Hex Decoder exception", e); } }
/** Hex解码. */ public static byte[] decodeHex(String input) { try { return Hex.decodeHex(input.toCharArray()); } catch (DecoderException e) { throw new HeheRuntimeException(e); } }
public static byte[] addrHashToScriptPubKey(String string) throws DecoderException { // TODO Auto-generated method stub // return b'76a914' + codecs.encode(utils.base58CheckDecode(b58str),'hex') + b'88ac' return org.apache.commons.codec.binary.Hex.decodeHex( ("76a914" + Utils.toHex(Base58Check.decode(string)) + "88ac").toCharArray()); }
public static byte[] privateKeyToWif(String string, boolean testnet) { string = testnet ? "EF" + string : "80" + string; byte[] privateKeyBytes = new byte[string.length()]; byte[] checksum = new byte[4]; try { privateKeyBytes = org.apache.commons.codec.binary.Hex.decodeHex(string.toCharArray()); } catch (DecoderException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } byte[] hash = new byte[256]; byte[] hash2 = new byte[256]; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); hash = digest.digest(privateKeyBytes); hash2 = digest.digest(hash); } catch (Exception e) { // TODO: handle exception } System.arraycopy(hash2, 0, checksum, 0, checksum.length); byte[] combined = new byte[privateKeyBytes.length + checksum.length]; for (int i = 0; i < combined.length; ++i) { combined[i] = i < privateKeyBytes.length ? privateKeyBytes[i] : checksum[i - privateKeyBytes.length]; } return (combined); }
/** Hex解码. */ public static byte[] decodeHex(String input) { try { return Hex.decodeHex(input.toCharArray()); } catch (DecoderException e) { throw Exceptions.unchecked(e); } }
/** * Create the application. * * @throws DecoderException * @throws SocketException */ public VideoSubscriberGUI() throws DecoderException, SocketException { initialize(); // Setup the Blackadder environment. String sharedObjPath = ProjectPropertiesSingleton.getInstance().getProperty("BAWrapperPath"); BlackadderWrapper.configureObjectFile(sharedObjPath); client = BlackAdderClient.getInstance(); channelID = 1; // Initialise the rootscope // publish the root scope where all videos will be published String rootScopeStr = "1111111111111111"; ByteIdentifier rootId = new ByteIdentifier(Hex.decodeHex(rootScopeStr.toCharArray())); rootScope = new ScopeID(rootId); // immediately subscribe to the catalog videoSubscriber = new VideoSubscriber(client, rootScope, strategy); // initialise ridMappings ridMappings = new HashMap<String, String>(); // Start the event handler SubscriberEventHandler handler = new SubscriberEventHandler(this); handler.start(); }
public static void jdkHMacMD5() { KeyGenerator keyGenerator; try { // 生成密钥 // keyGenerator = KeyGenerator.getInstance("HmacMD5"); // SecretKey secretKey = keyGenerator.generateKey(); // byte[] key = secretKey.getEncoded(); byte[] key = Hex.decodeHex(new char[] {'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'}); // 还原密钥 SecretKey restoreSecretKey = new SecretKeySpec(key, "HmacMD5"); // 实例和初始化Mac Mac mac = Mac.getInstance(restoreSecretKey.getAlgorithm()); mac.init(restoreSecretKey); // 执行摘要 byte[] hmacMD5Bytes = mac.doFinal(src.getBytes()); System.out.println("jdk hmacMD5:" + Hex.encodeHexString(hmacMD5Bytes)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (DecoderException e) { e.printStackTrace(); } }
public static Group fromStringinHex(String string) { try { byte[] decodeHex = Hex.decodeHex(string.toCharArray()); return fromString(new String(decodeHex)); } catch (DecoderException e) { throw new Error(e); } }
public static byte[] hexDecode(String s) { try { return Hex.decodeHex(s.toCharArray()); } catch (DecoderException e) { throw new ClientProblemException( "Hex content is not valid hex: " + e.getMessage() + ": " + s); } }
public static byte[] hexString2Bytes(String src) { try { return Hex.decodeHex(src.toCharArray()); } catch (DecoderException e) { LOGGER.error("Decode byte[] error:{}", e); return ArrayUtils.EMPTY_BYTE_ARRAY; } }
public static String decode(String bytes) { try { return new String(Hex.decodeHex(bytes.toCharArray()), Charset.defaultCharset()); } catch (DecoderException e) { LOGGER.error("Decode String error:{}", e); return StringUtils.EMPTY; } }
public static Authorization fromToken(SecretKeySpec key, String token) throws AuthenticationException { if (token == null) { throw new IllegalArgumentException("Token required"); } try { int hashSizeBytes = 16; Cipher decodingCipher = Cipher.getInstance("AES"); decodingCipher.init(Cipher.DECRYPT_MODE, key); ByteBuffer buffer = ByteBuffer.wrap(decodingCipher.doFinal(Hex.decodeHex(token.toCharArray()))); MessageDigest messageDigest = MessageDigest.getInstance("MD5"); byte[] foundHash = new byte[hashSizeBytes]; buffer.get(foundHash, 0, hashSizeBytes); byte[] hashInput = new byte[buffer.capacity() - hashSizeBytes]; buffer.get(hashInput); buffer.position(hashSizeBytes); byte[] calculatedHash = messageDigest.digest(hashInput); if (Arrays.equals(foundHash, calculatedHash)) { byte type = buffer.get(); Authorization authorization = null; long expires = buffer.getLong(); long uoid = buffer.getLong(); switch (type) { case ExplicitRightsAuthorization.ID: authorization = ExplicitRightsAuthorization.fromBuffer(buffer); break; case UserAuthorization.ID: authorization = UserAuthorization.fromBuffer(buffer); break; case SystemAuthorization.ID: authorization = SystemAuthorization.fromBuffer(buffer); break; case AnonymousAuthorization.ID: authorization = AnonymousAuthorization.fromBuffer(buffer); break; case AdminAuthorization.ID: authorization = AdminAuthorization.fromBuffer(buffer); break; default: throw new AuthenticationException("Unknown authorization type: " + type); } authorization.setUoid(uoid); authorization.setExpires(expires); if (authorization.getExpires().getTimeInMillis() < new GregorianCalendar().getTimeInMillis()) { throw new AuthenticationException("This token has expired"); } return authorization; } else { throw new AuthenticationException("Given token is corrupt"); } } catch (GeneralSecurityException e) { throw new AuthenticationException("Invalid token", e); } catch (DecoderException e) { throw new AuthenticationException(e); } }
// TODO 这里应该可以自动去掉中间的空白字符 public NotificationBuilder setToken(String token) { try { byte[] hex = Hex.decodeHex(token.toCharArray()); setToken(hex); } catch (DecoderException e) { throw new RuntimeException(e); } return this; }
/** * @Title: decryptAES @Description: AES解密 * * @author: psk * @date:2013-1-8 下午2:28:12 * @param input * @return * @return String 返回类型 * @throws */ public String decryptAES(String input) { try { Cipher cipher = Cipher.getInstance(DECRYPT_MODE); cipher.init(Cipher.DECRYPT_MODE, aesKeySpc, ivSpec); byte[] result = cipher.doFinal(Hex.decodeHex(input.toCharArray())); return new String(result); } catch (Exception e) { e.printStackTrace(); } return null; }
@Test public void scryptRuby() { int N = 1024; int r = 8; int p = 1; String hashed = SCryptUtil.scryptRuby(passwd, N, r, p); String[] parts = hashed.split("\\$"); assertEquals(5, parts.length); try { assertEquals(8, Hex.decodeHex(parts[3].toCharArray()).length); assertEquals(32, Hex.decodeHex(parts[4].toCharArray()).length); } catch (DecoderException e) { fail("There was an exception decoding the hashed value: \n" + e.getMessage()); } assertEquals(N, Integer.parseInt(parts[0], 16)); assertEquals(r, Integer.parseInt(parts[1], 16)); assertEquals(p, Integer.parseInt(parts[2], 16)); }
public byte[] decodeHash(String encodedHash) { if (!getEncodeHashAsBase64()) { try { return Hex.decodeHex(encodedHash.toCharArray()); } catch (DecoderException e) { throw new RuntimeException("Unable to decode password hash"); } } else { return Base64.decodeBase64(encodedHash.getBytes()); } }
/** * Get the shared secret for the currently running application. This method assumes that some * other process has {@link #sendTo(CloudFoundryClient, SharedSecret, CloudApplication) sent} the * {@link SharedSecret} to the running application. * * @param required * @return the shared secret * @throw IllegalStateException if the secret cannot be obtained */ public SharedSecret getForSelf(boolean required) throws IllegalStateException { try { String secret = getEnv(ENV_KEY); if (!StringUtils.hasLength(secret) && !required) { return null; } Assert.state(StringUtils.hasLength(secret), "No shared secret has been propagated"); return SharedSecret.fromBytes(Hex.decodeHex(secret.toCharArray())); } catch (DecoderException e) { throw new IllegalStateException("Unable to decode shared secret key", e); } }
@Test public void testVerifyCode() throws Exception { for (String algorithm : algs) { for (String key : keys) { for (int i = 0; i < testStrings.length; ++i) { InputStream in = IOUtils.toInputStream(testStrings[i]); InputStream keyStream = IOUtils.toInputStream(key); InputStream code = new ByteArrayInputStream( Hex.decodeHex(codes.get(algorithm).get(key)[i].toCharArray())); assert (MessageAuthenticator.verifyCode(algorithm, in, keyStream, code)); in = IOUtils.toInputStream(testStrings[i]); keyStream = IOUtils.toInputStream(key); code = new ByteArrayInputStream( Hex.decodeHex( codes.get(algorithm).get(key)[(i + 1) % testStrings.length].toCharArray())); assertFalse(MessageAuthenticator.verifyCode(algorithm, in, keyStream, code)); } } } }
/** * converts a long counter value to the hex binary representation * * @param counter the counter to convert * @return the binary hex representation of the counter */ private byte[] generateCounterHex(long counter) { LOGGER.trace("generateCounterHex(long)"); LOGGER.debug("Counter: {}", counter); byte[] result = null; try { String hex = Long.toHexString(counter); while (hex.length() < 16) { hex = "0" + hex; } result = Hex.decodeHex(hex.toCharArray()); } catch (Exception e) { LOGGER.error("Error: {}", e.getMessage()); } return result; }
/** * Method to determine whether a String is hex encoded * * @param hexEncodedString The String to verify * @return boolean denoting the hex encoded status of the String */ public static boolean isHexEncoded(String hexEncodedString) { boolean rc; rc = false; try { Hex.decodeHex(hexEncodedString.toCharArray()); rc = true; } catch (DecoderException de) { // No action required - allow code to return false } return rc; }
private VectorClock readVersion(String key) { try { File versionFile = new File(getVersionDirectory(), key); if (!versionFile.exists()) { // bootstrap file save default clock as version. VectorClock clock = new VectorClock(); writeVersion(key, clock); return clock; } else { // read the version file and return version. String hexCode = FileUtils.readFileToString(versionFile, "UTF-8"); return new VectorClock(Hex.decodeHex(hexCode.toCharArray())); } } catch (Exception e) { throw new VoldemortException("Failed to read Version for Key:" + key, e); } }
public InputStream getInputStream() throws IOException { try { if (source != null) { return new FileInputStream(source); } if (SchemaUtils.isInstanceOf(schemaType, XmlHexBinary.type)) { return new ByteArrayInputStream(Hex.decodeHex(content.toCharArray())); } else if (SchemaUtils.isInstanceOf(schemaType, XmlBase64Binary.type)) { return new ByteArrayInputStream(Base64.decodeBase64(content.getBytes())); } else if (SchemaUtils.isAnyType(schemaType)) { return new ByteArrayInputStream(content.getBytes()); } else throw new IOException("Invalid type for XOPPartDataSource; " + schemaType.getName()); } catch (Exception e) { SoapUI.logError(e); throw new IOException(e.toString()); } }
public static byte[] privateKeyToPublicKey(String private_key, boolean compressed) { byte[] privateKeyBytes = null; try { privateKeyBytes = org.apache.commons.codec.binary.Hex.decodeHex(private_key.toCharArray()); } catch (DecoderException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } X9ECParameters ecp = SECNamedCurves.getByName("secp256k1"); ECDomainParameters domainParams = new ECDomainParameters(ecp.getCurve(), ecp.getG(), ecp.getN(), ecp.getH(), ecp.getSeed()); ECPrivateKeyParameters privateKey = new ECPrivateKeyParameters(new BigInteger(1, privateKeyBytes), domainParams); System.out.println(privateKey.getD()); byte[] publicKeyBIBytes = privateKey.getD().toByteArray(); ECPoint Q = domainParams.getG().multiply(new BigInteger(publicKeyBIBytes)); byte[] publicKeyBytes = Q.getEncoded(compressed); return publicKeyBytes; }
private void start() { byte[] key = new byte[16]; new Random().nextBytes(key); SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); String toEncrypt = "1"; try { Cipher encodingCipher = Cipher.getInstance("AES"); encodingCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); byte[] encodedBytes = encodingCipher.doFinal(toEncrypt.getBytes(Charsets.UTF_8)); System.out.println("Encoded size: " + encodedBytes.length); String encodedHexString = new String(Hex.encodeHex(encodedBytes)); System.out.println("Encoded hex: " + encodedHexString); Cipher decodingCipher = Cipher.getInstance("AES"); decodingCipher.init(Cipher.DECRYPT_MODE, secretKeySpec); ByteBuffer wrap = ByteBuffer.wrap(decodingCipher.doFinal(Hex.decodeHex(encodedHexString.toCharArray()))); String result = new String(wrap.array(), Charsets.UTF_8); System.out.println(result); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (DecoderException e) { e.printStackTrace(); } }
/** * Decodes the encoded hex string byte array back as byte array. * * @param hexString * @return * @throws DecoderException */ public static byte[] decodeHexString(String hexString) throws DecoderException { return Hex.decodeHex(hexString.toCharArray()); }
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta = (SymmetricCryptoTransMeta) smi; data = (SymmetricCryptoTransData) sdi; Object[] r = getRow(); // Get row from input rowset & set row busy! if (r == null) // no more input to be expected... { setOutputDone(); return false; } if (first) { first = false; data.outputRowMeta = getInputRowMeta().clone(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this); // Let's check that Result Field is given if (Const.isEmpty(meta.getResultfieldname())) { // Result field is missing ! throw new KettleStepException( BaseMessages.getString( PKG, "SymmetricCryptoTrans.Exception.ErrorResultFieldMissing")); //$NON-NLS-1$ // //$NON-NLS-2$ } // Check if The message field is given if (Const.isEmpty(meta.getMessageFied())) { // Message Field is missing ! throw new KettleStepException( BaseMessages.getString(PKG, "SymmetricCryptoTrans.Exception.MissingMessageField")); } // Try to get Field index data.indexOfMessage = getInputRowMeta().indexOfValue(meta.getMessageFied()); // Let's check the Field if (data.indexOfMessage < 0) { // The field is unreachable ! throw new KettleStepException( BaseMessages.getString( PKG, "SymmetricCryptoTrans.Exception.CouldnotFindField", meta.getMessageFied())); // $NON-NLS-1$ //$NON-NLS-2$ } if (!meta.isSecretKeyInField()) { String realSecretKey = Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(meta.getSecretKey())); if (Const.isEmpty(realSecretKey)) { throw new KettleStepException( BaseMessages.getString(PKG, "SymmetricCryptoTrans.Exception.SecretKeyMissing")); } // We have a static secret key // Set secrete key setSecretKey(realSecretKey); } else { // dynamic secret key if (Const.isEmpty(meta.getSecretKeyField())) { throw new KettleStepException( BaseMessages.getString(PKG, "SymmetricCryptoTrans.Exception.SecretKeyFieldMissing")); } // Try to get secret key field index data.indexOfSecretkeyField = getInputRowMeta().indexOfValue(meta.getSecretKeyField()); // Let's check the Field if (data.indexOfSecretkeyField < 0) { // The field is unreachable ! throw new KettleStepException( BaseMessages.getString( PKG, "SymmetricCryptoTrans.Exception.CouldnotFindField", meta.getSecretKeyField())); // $NON-NLS-1$ //$NON-NLS-2$ } } } try { // handle dynamic secret key Object realSecretKey; if (meta.isSecretKeyInField()) { if (meta.isReadKeyAsBinary()) { realSecretKey = getInputRowMeta().getBinary(r, data.indexOfSecretkeyField); if (realSecretKey == null) { throw new KettleStepException( BaseMessages.getString(PKG, "SymmetricCryptoTrans.Exception.SecretKeyMissing")); } } else { realSecretKey = Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( (String) getInputRowMeta().getString(r, data.indexOfSecretkeyField))); if (Const.isEmpty((String) realSecretKey)) { throw new KettleStepException( BaseMessages.getString(PKG, "SymmetricCryptoTrans.Exception.SecretKeyMissing")); } } // Set secrete key setSecretKey(realSecretKey); } // Get the field value Object result = null; if (meta.getOperationType() == SymmetricCryptoTransMeta.OPERATION_TYPE_ENCRYPT) { // encrypt plain text byte[] encrBytes = data.Crypt.encrDecryptData(getInputRowMeta().getBinary(r, data.indexOfMessage)); // return encrypted value if (meta.isOutputResultAsBinary()) result = encrBytes; else result = new String(Hex.encodeHex((encrBytes))); } else { // Get encrypted value String s = getInputRowMeta().getString(r, data.indexOfMessage); byte[] dataBytes = Hex.decodeHex(s.toCharArray()); // encrypt or decrypt message and return result byte[] encrBytes = data.Crypt.encrDecryptData(dataBytes); // we have decrypted value if (meta.isOutputResultAsBinary()) result = encrBytes; else result = new String(encrBytes); } Object[] outputRowData = RowDataUtil.addValueData(r, getInputRowMeta().size(), result); putRow(data.outputRowMeta, outputRowData); // copy row to output rowset(s); } catch (Exception e) { boolean sendToErrorRow = false; String errorMessage; if (getStepMeta().isDoingErrorHandling()) { sendToErrorRow = true; errorMessage = e.toString(); } else { logError( BaseMessages.getString(PKG, "SymmetricCryptoTrans.Log.ErrorInStepRunning"), e); //$NON-NLS-1$ logError(Const.getStackTracker(e)); setErrors(1); stopAll(); setOutputDone(); // signal end to receiver(s) return false; } if (sendToErrorRow) { // Simply add this row to the error row putError(getInputRowMeta(), r, 1, errorMessage, null, "EncDecr001"); } } return true; }
/** * Decodes the encoded hex string byte array back as byte array. * * @param sourceChars * @return * @throws DecoderException */ public static byte[] decodeHexString(char[] sourceChars) throws DecoderException { return Hex.decodeHex(sourceChars); }