Java Code Examples for org.bouncycastle.util.encoders.Hex#toHexString()

The following examples show how to use org.bouncycastle.util.encoders.Hex#toHexString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BinanceDexApiNodeClientImpl.java    From java-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public Account getCommittedAccount(String address) {
    String encodedAddress = "0x" + ARG_ACCOUNT_PREFIX + Hex.toHexString(Crypto.decodeAddress(address));
    try {
        JsonRpcResponse<AccountResult> response = BinanceDexApiClientGenerator.executeSync(binanceDexNodeApi.getCommittedAccount(encodedAddress));
        checkRpcResult(response);
        byte[] value = response.getResult().getResponse().getValue();
        if(value != null && value.length > 0){
            byte[] array = new byte[value.length - 4];
            System.arraycopy(value, 4, array, 0, array.length);
            AppAccount account = AppAccount.parseFrom(array);
            return convert(account);
        }
        return null;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 2
Source File: SCID.java    From julongchain with Apache License 2.0 6 votes vote down vote up
public String getName() throws JulongChainException {
	if (this.smartContractSpec == null) {
		throw new JulongChainException("nil smart contract spec");
	}

	String name = this.smartContractSpec.getSmartContractId().getName();
	if (StringUtils.isNotEmpty(this.version)) {
		name = name + "-" + this.version;
	}

	if (StringUtils.isNotEmpty(this.chainID)) {
		byte[] hash = new SM3().hash(this.chainID.getBytes());
		String hexStr = Hex.toHexString(hash);
		name = name + "-" + hexStr;
	}

	return name;
}
 
Example 3
Source File: BinanceDexApiNodeClientImpl.java    From java-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public AtomicSwap getSwapByID(String swapID){
    try {
        Map.Entry swapIdEntry = Maps.immutableEntry("SwapID", swapID);
        String requestData = "0x" + Hex.toHexString(EncodeUtils.toJsonStringSortKeys(swapIdEntry).getBytes());
        JsonRpcResponse<ABCIQueryResult> rpcResponse = BinanceDexApiClientGenerator.executeSync(binanceDexNodeApi.getSwapByID(requestData));
        checkRpcResult(rpcResponse);
        ABCIQueryResult.Response response = rpcResponse.getResult().getResponse();
        if (response.getCode() != null) {
            BinanceDexApiError binanceDexApiError = new BinanceDexApiError();
            binanceDexApiError.setCode(response.getCode());
            binanceDexApiError.setMessage(response.getLog());
            throw new BinanceDexApiException(binanceDexApiError);
        }
        String swapJson = new String(response.getValue());
        return EncodeUtils.toObjectFromJsonString(swapJson, AtomicSwap.class);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: VersionedCouchDB.java    From julongchain with Apache License 2.0 5 votes vote down vote up
/**
 * For namespaceDBName form groupName_namespace$$collection
 * The final namespaceDBName is	50 chars of groupName
 * 								"_"
 * 								50 chars of namespace
 * 								"$$"
 * 								50chars of collection
 * 								hash of groupName_namespace$$collection
 *
 * For namespaceDBName form groupName_namespace
 * The final namespaceDBName is	50 chars of groupName
 * 								"_"
 * 								50 chars of namespace
 * 								hash of groupName_namespace
 */
private String constructNamespaceName(String groupName, String nsName) throws LedgerException {
	String escapeNamespace = escapeUpperCase(nsName);
	String namespaceDBName = groupName + "_" + escapeNamespace;
	if (namespaceDBName.length() > MAX_DBNAME_LENGTH) {
		String hashOfNamespaceDBName = Hex.toHexString(Util.getHashBytes((groupName + "_" + nsName).getBytes()));
		if (groupName.length() > GROUP_NAME_ALLOWED_LENGTH) {
			groupName = groupName.substring(0, GROUP_NAME_ALLOWED_LENGTH);
		}
		String[] names = escapeNamespace.split("\\$\\$");
		String namespace = names[0];
		if (namespace.length() > NAMESPACE_NAME_ALLOWED_LENGTH) {
			namespace = namespace.substring(0, NAMESPACE_NAME_ALLOWED_LENGTH);
		}
		escapeNamespace = namespace;

		if (names.length == 2) {
			String collection = names[1];
			if (collection.length() > COLLECTION_NAME_ALLOWED_LENGTH) {
				collection = collection.substring(0, COLLECTION_NAME_ALLOWED_LENGTH);
			}
			escapeNamespace = escapeNamespace + "$$" + collection;
		}
		return groupName + "_" + escapeNamespace + "(" + hashOfNamespaceDBName + ")";
	}
	return namespaceDBName;
}
 
Example 5
Source File: SecurityUtils.java    From sctalk with Apache License 2.0 5 votes vote down vote up
public String EncryptPass(String strPass) {
    MessageDigest md5 = null;
    try {
        md5 = MessageDigest.getInstance("MD5");
    } catch (Exception e) {
        e.printStackTrace();
        return "";
    }
    byte[] md5md5Bytes = md5.digest(strPass.getBytes());
    return Hex.toHexString(md5md5Bytes);
}
 
Example 6
Source File: MspHelper.java    From julongchain with Apache License 2.0 5 votes vote down vote up
private static void keyExport(String keystore, String output, IKey key) throws JulongChainException {
    String id = Hex.toHexString(key.ski());
    String keyPath = Paths.get(keystore, id + "_sk").toString();

    try {
        Files.move(Paths.get(keyPath), Paths.get(output));
    } catch (IOException e) {
        throw new JulongChainException("renamed unsuccessfully on keyExport");
    }
}
 
Example 7
Source File: Transaction.java    From javasdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * get transaction hash.
 *
 * @param gasLimit gas limit
 * @return transaction hash
 */
public String getTransactionHash(long gasLimit) {
    TransactionValueProto.TransactionValue.Builder input = TransactionValueProto.TransactionValue.newBuilder();
    int defaultGasPrice = 10000; // default
    input.setPrice(defaultGasPrice);
    input.setGasLimit(gasLimit);
    input.setAmount(this.value);
    if (!"".equals(payload)) {
        input.setPayload(ByteString.copyFrom(ByteUtil.fromHex(payload)));
    }
    input.setOpValue(opCode);
    input.setExtra(ByteString.copyFromUtf8(extra));

    if (vmType == VMType.EVM) {
        input.setVmTypeValue(TransactionValueProto.TransactionValue.VmType.EVM_VALUE);
    } else if (vmType == VMType.HVM) {
        input.setVmTypeValue(TransactionValueProto.TransactionValue.VmType.HVM_VALUE);
    } else if (vmType == VMType.TRANSFER) {
        input.setVmTypeValue(TransactionValueProto.TransactionValue.VmType.TRANSFER_VALUE);
    } else {
        throw new RuntimeException("unKnow vmType");
    }

    byte[] valueBytes = input.build().toByteArray();
    Object[] transactionHash = new Object[6];
    transactionHash[0] = ByteUtil.hex2Base64(from);
    if (!"0x0".equals(to)) {
        transactionHash[1] = ByteUtil.hex2Base64(to);
    }
    transactionHash[2] = ByteUtil.base64(valueBytes);
    transactionHash[3] = timestamp;
    transactionHash[4] = nonce;
    transactionHash[5] = ByteUtil.hex2Base64(signature);
    String hashJson = gson.toJson(transactionHash);
    return "0x" + Hex.toHexString(HashUtil.sha3(hashJson.getBytes()));
}
 
Example 8
Source File: EOSFormatterTest.java    From eosio-java with MIT License 5 votes vote down vote up
/**
 * Validate positive test for PrepareSerializedTransactionForSigning
 */
@Test
public void validatePrepareSerializedTransactionForSigning() {
    String chainId = "687fa513e18843ad3e820744f4ffcf93b1354036d80737db8dc444fe4b15ad17";
    String serializedTransaction = "8BC2A35CF56E6CC25F7F000000000100A6823403EA3055000000572D3CCDCD01000000000000C03400000000A8ED32322A000000000000C034000000000000A682A08601000000000004454F530000000009536F6D657468696E6700";
    String expectedSignableTransaction = chainId + serializedTransaction + Hex.toHexString(new byte[32]);

    try {
        String signableTransaction = EOSFormatter.prepareSerializedTransactionForSigning(serializedTransaction, chainId);
        assertEquals(expectedSignableTransaction, signableTransaction);
    } catch (EOSFormatterError eosFormatterError) {
        eosFormatterError.printStackTrace();
        fail("Should not throw exception here");
    }
}
 
Example 9
Source File: Utils.java    From nuls-v2 with MIT License 5 votes vote down vote up
/**
 * @param addr length should be 20
 * @return short string represent 1f21c...
 */
public static String getAddressShortString(byte[] addr) {

    if (!isValidAddress(addr)) {
        throw new Error("not an address");
    }

    String addrShort = Hex.toHexString(addr, 0, 3);

    StringBuffer sb = new StringBuffer();
    sb.append(addrShort);
    sb.append("...");

    return sb.toString();
}
 
Example 10
Source File: Hash.java    From staffjoy with MIT License 5 votes vote down vote up
public static String encode(String key, String data) throws Exception {
    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
    sha256_HMAC.init(secret_key);

    return Hex.toHexString(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
}
 
Example 11
Source File: Util.java    From julongchain with Apache License 2.0 4 votes vote down vote up
/**
 * 群组区块检查,检查群组区块链文件夹下的区块链文件
 * 根据区块链区块构建原则对区块链文件进行检查
 * 检查失败将会停止程序,等待查验原因
 */
public static void checkGroupBlockFiles(String groupDir) throws LedgerException{
	BlockFileStream stream = new BlockFileStream(groupDir, 0, 0);
	//前一区块头部hash
	MerkleTree headerTree = new MerkleTree(32);
	//当前区块previous hash
	MerkleTree previousHashTree = new MerkleTree(32);
	//区块data hash
	MerkleTree dataHashTree = new MerkleTree(32);
	//区块头部data hash
	MerkleTree dataHashInHeaderTree = new MerkleTree(32);
	Common.Block block = null;
	long totalBlockNum = 0;
	try {
		while (true) {
			byte[] blockBytes = stream.nextBlockBytes();
			if (blockBytes != null) {
				//读取block
				block = Common.Block.parseFrom(blockBytes);
				//更新区块头部hash
				headerTree.update(Util.getHashBytes(block.getHeader().toByteArray()));
				//更新区块previousHash
				if (totalBlockNum > 0) {
					previousHashTree.update(block.getHeader().getPreviousHash().toByteArray());
				}
				//更新区块data hash
				dataHashTree.update(Util.getHashBytes(block.getData().toByteArray()));
				//更新区块头部中data hash
				dataHashInHeaderTree.update(block.getHeader().getDataHash().toByteArray());
				totalBlockNum++;
			} else {
				//由于不存在以最后一个区块header hash为previous hash的区块,所以直接将最后一个区块的header hash加入
				if (block != null) {
					previousHashTree.update(Util.getHashBytes(block.getHeader().toByteArray()));
				}
				break;
			}
		}
		headerTree.done();
		previousHashTree.done();
		dataHashTree.done();
		dataHashInHeaderTree.done();
		log.info("Finished block file check, using MerkleTree");
		String headerTreeStr = Hex.toHexString(headerTree.getRootHash());
		log.info("Summary of block header hash is " + headerTreeStr);
		String previousHashTreeStr = Hex.toHexString(previousHashTree.getRootHash());
		log.info("Summary of block previous hash in block header is " + previousHashTreeStr);
		String dataHashTreeStr = Hex.toHexString(dataHashTree.getRootHash());
		log.info("Summary of block data hash is " + dataHashTreeStr);
		String dataHashInHeaderTreeStr = Hex.toHexString(dataHashInHeaderTree.getRootHash());
		log.info("Summary of block data hash in block header is " + dataHashInHeaderTreeStr);
		if (!headerTreeStr.equals(previousHashTreeStr) || !dataHashTreeStr.equals(dataHashInHeaderTreeStr)) {
			log.error("Block file checking failed");
			retrievalBlockFiles(groupDir);
		} else {
			log.info("Block file in [" + groupDir + "] checking success");
		}
	} catch (Exception e) {
		log.error("Got error, total block number is " + totalBlockNum);
		log.error(e.getMessage());
		throw new LedgerException(e);
	}
}
 
Example 12
Source File: BurstCryptoImpl.java    From burstkit4j with Apache License 2.0 4 votes vote down vote up
@Override
public String toHexString(byte[] bytes) {
    return Hex.toHexString(bytes);
}
 
Example 13
Source File: Util.java    From julongchain with Apache License 2.0 4 votes vote down vote up
/**
   * 获取新的区块
   * 根据当前账本中最新区块的编号获取下一个区块编号
   * @param reader 账本
   * @param messages 区块Data
   */
  public static Common.Block createNextBlock(IReader reader, List<Common.Envelope> messages) throws LedgerException{
      long nextBlockNumber = 0;
      byte[] previousBlockHash = null;
      if(reader.height() > 0){
          //当当前账本中有数据时,应从最新的区块开始读取
          Ab.SeekPosition startPosition = Ab.SeekPosition.newBuilder()
                  .setNewest(Ab.SeekNewest.getDefaultInstance())
                  .build();
          IIterator itr = reader.iterator(startPosition);
          Map.Entry<QueryResult, Common.Status> entry = (Map.Entry<QueryResult, Common.Status>) itr.next().getObj();
          Common.Block block =  (Common.Block) entry.getKey().getObj();
          Common.Status status = entry.getValue();
          if(!status.equals(Common.Status.SUCCESS)){
              throw new LedgerException("Error seeking to newest block for group with non-zero height");
          }
          nextBlockNumber = block.getHeader().getNumber() + 1;
          previousBlockHash = getHashBytes(block.getHeader().toByteArray());
          String s = Hex.toHexString(previousBlockHash);
      }
      //添加区块Data
      Common.BlockData.Builder dataBuilder = Common.BlockData.newBuilder();
      if (messages != null) {
          messages.forEach((msg) -> dataBuilder.addData(msg.toByteString()));
      }
ByteString dataByteString = dataBuilder.build().toByteString();
//组装区块
      return Common.Block.newBuilder()
              .setHeader(Common.BlockHeader.newBuilder()
                      .setNumber(nextBlockNumber)
                      .setPreviousHash(previousBlockHash == null ? ByteString.EMPTY : ByteString.copyFrom(previousBlockHash))
				.setDataHash(dataByteString.equals(ByteString.EMPTY) ?
						ByteString.EMPTY :
						ByteString.copyFrom(getHashBytes(dataByteString.toByteArray())))
				.build())
              .setData(dataBuilder)
              .setMetadata(Common.BlockMetadata.newBuilder()
                      .addMetadata(ByteString.EMPTY)
                      .addMetadata(ByteString.EMPTY)
                      .addMetadata(ByteString.EMPTY)
                      .addMetadata(ByteString.EMPTY)
                      .build())
              .build();
  }
 
Example 14
Source File: UnsecuredNiFiRegistryClientIT.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
private String calculateSha256Hex(final String narFile) throws IOException {
    try (final InputStream bundleInputStream = new FileInputStream(narFile)) {
        return Hex.toHexString(DigestUtils.sha256(bundleInputStream));
    }
}
 
Example 15
Source File: ECKey.java    From javasdk with GNU Lesser General Public License v3.0 4 votes vote down vote up
public String toHex() {
    return Hex.toHexString(toByteArray());
}
 
Example 16
Source File: AESSensitivePropertyProvider.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
public AESSensitivePropertyProvider(byte[] key) throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException {
    this(key == null ? "" : Hex.toHexString(key));
}
 
Example 17
Source File: EncodeUtils.java    From java-sdk with Apache License 2.0 4 votes vote down vote up
public static String bytesToHex(byte[] bytes) {
    return Hex.toHexString(bytes);
}
 
Example 18
Source File: PlatOnTypeEncoder.java    From client-sdk-java with Apache License 2.0 4 votes vote down vote up
private static String encodeString(Utf8String string) {
    byte[] utfEncoded = string.getValue().getBytes(StandardCharsets.UTF_8);
    return Hex.toHexString(utfEncoded);
}
 
Example 19
Source File: HexTest.java    From nuls-v2 with MIT License 4 votes vote down vote up
@Test
    public void testHexs() throws IOException, DecoderException {
        TranList list = new TranList();
        for (int i = 0; i < 100000; i++) {
            Transaction tx = buildTransaction();
            list.getTxs().add(tx);
        }
        byte[] bytes = list.serialize();
        long time1 = System.currentTimeMillis();
        String hex0 = HexUtil.encode(bytes);
        byte[] bytes0 = HexUtil.decode(hex0);
        long time2 = System.currentTimeMillis();
        Log.info("{} time used - io.nuls.tools.crypto.HexUtil.encode && decode ===StringLenght= {}", (time2 - time1), hex0.length());

        String hex1 = Hex.toHexString(bytes);
        byte[] bytes1 = Hex.decode(hex1);
        long time3 = System.currentTimeMillis();
        Log.info("{} time used - org.spongycastle.util.encoders.Hex.encode && decode ===StringLenght= {}", (time3 - time2), hex1.length());


        String hex2 = org.apache.commons.codec.binary.Hex.encodeHexString(bytes);
        byte[] bytes2 = org.apache.commons.codec.binary.Hex.decodeHex(hex2.toCharArray());
        long time4 = System.currentTimeMillis();
        Log.info("{} time used - org.apache.commons.codec.binary.Hex.encode && decode ===StringLenght= {}", (time4 - time3), hex2.length());

        String base0 = RPCUtil.encode(bytes);
        byte[] bytes3 = RPCUtil.decode(base0);
        long time5 = System.currentTimeMillis();
        Log.info("{} time used - java.util.Base64.encode && decode ===StringLenght= {}", (time5 - time4), base0.length());

        String base1 = Base64.toBase64String(bytes);
        byte[] bytes5 = Base64.decode(base1);
        long time6 = System.currentTimeMillis();
        Log.info("{} time used - org.spongycastle.util.encoders.Base64.encode && decode ===StringLenght= {}", (time6 - time5), base1.length());

        String base2 = org.apache.commons.net.util.Base64.encodeBase64String(bytes);
        byte[] bytes6 = org.apache.commons.net.util.Base64.decodeBase64(base2);
        long time7 = System.currentTimeMillis();
        Log.info("{} time used - org.apache.commons.net.util.Base64.encode && decode ===StringLenght= {}", (time7 - time6), base2.length());

//        String base3 = org.apache.commons.codec.binary.Base64.encodeBase64String(bytes);
//        byte[] bytes7 = org.apache.commons.codec.binary.Base64.decodeBase64(base3);
//        long time8 = System.currentTimeMillis();
//        Log.info("{} time used - org.apache.commons.codec.binary.Base64.encode && decode ===StringLenght= {}", (time8 - time7), base3.length());

    }
 
Example 20
Source File: ByteFormatter.java    From eosio-java with MIT License 2 votes vote down vote up
/**
 * Convert the current ByteFormatter contents to a Hex encoded string and return it.
 * @return - Hex encoded string representation of the current formatter context.
 */
public String toHex() {
    return Hex.toHexString(this.context);
}