Java Code Examples for org.bouncycastle.util.encoders.Hex

The following examples show how to use org.bouncycastle.util.encoders.Hex. These examples are extracted from open source projects. 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 Project: fido2   Source File: Main.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private static void addaccesskey(String keystorelocation, String password) throws Exception {
    KeyStore keystore = KeyStore.getInstance("BCFKS", BC_FIPS_PROVIDER);
    keystore.load(new FileInputStream(keystorelocation), password.toCharArray());
    KeyGenerator keygen = KeyGenerator.getInstance("AES", BC_FIPS_PROVIDER);
    keygen.init(128);
    SecretKey sk = keygen.generateKey();
    String secretkey = Hex.toHexString(sk.getEncoded());

    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    digest.update(new Date().toString().getBytes());
    String accesskey = Hex.toHexString(digest.digest()).substring(0, 16);

    keystore.setKeyEntry(accesskey, sk, password.toCharArray(), null);
    keystore.store(new FileOutputStream(keystorelocation), password.toCharArray());
    System.out.println("Created new access/secret key:");
    System.out.println("Access key:" + accesskey);
    System.out.println("Secret key:" + secretkey);
}
 
Example 2
private byte[] customHash(byte[] in) {
    if (algo != null) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algo);
            return Hex.encode(digest.digest(in));
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException(e);
        }
    } else if (regexReplacements != null) {
        String cur = new String(in, StandardCharsets.UTF_8);
        for(RegexReplacement rr: regexReplacements) {
            cur = cur.replaceAll(rr.getRegex(), rr.getReplacement());
        }
        return cur.getBytes(StandardCharsets.UTF_8);

    } else {
        throw new IllegalArgumentException();
    }
}
 
Example 3
Source Project: julongchain   Source File: FileKeyStore.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public IKey getKey(byte[] ski) throws CspException {
    if (ski.length == 0) {
        log.error("Invalid SKI. Cannot be of zero length.");
    }
    String suffix = getSuffix(Hex.toHexString(ski));
    System.out.println(suffix);
    switch (suffix) {
        case "pk":
            //IKey key= (IKey) loadPrivateKey(suffix);
            //return  key;
        case "sk":
            IKey key = loadPrivateKey(Hex.toHexString(ski));
            log.info(Hex.toHexString(key.toBytes()));
            return key;
        default:

    }

    return null;
}
 
Example 4
Source Project: hedera-sdk-java   Source File: PublicKeyTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("can convert from protobuf key list to PublicKey")
void fromProtoKeyKeyList() {
    // given
    final byte[][] keyBytes = new byte[][] {
        Hex.decode("0011223344556677889900112233445566778899001122334455667788990011"),
        Hex.decode("aa11223344556677889900112233445566778899001122334455667788990011")
    };
    final KeyList.Builder protoKeyList = KeyList.newBuilder();
    Arrays.stream(keyBytes).forEach(kb -> {
        protoKeyList.addKeys(Key.newBuilder().setEd25519(ByteString.copyFrom(kb)));
    });
    final KeyOrBuilder protoKey = Key.newBuilder().setKeyList(protoKeyList).build();

    // when
    final PublicKey cut = PublicKey.fromProtoKey(protoKey);

    // then
    assertEquals(cut.getClass(), com.hedera.hashgraph.sdk.crypto.KeyList.class);
    final com.hedera.hashgraph.sdk.crypto.KeyList keyList = (com.hedera.hashgraph.sdk.crypto.KeyList)cut;
    final KeyList actual = keyList.toKeyProto().getKeyList();
    assertEquals(2, actual.getKeysCount());
    assertArrayEquals(keyBytes[0], actual.getKeys(0).getEd25519().toByteArray());
    assertArrayEquals(keyBytes[1], actual.getKeys(1).getEd25519().toByteArray());
}
 
Example 5
Source Project: java-sdk   Source File: BinanceDexApiNodeClientImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Proposal getProposalById(String proposalId) {
    try {
        Map.Entry proposalIdEntry = Maps.immutableEntry("ProposalID", proposalId);
        String requestData = "0x" + Hex.toHexString(EncodeUtils.toJsonStringSortKeys(proposalIdEntry).getBytes());
        JsonRpcResponse<ABCIQueryResult> rpcResponse = BinanceDexApiClientGenerator.executeSync(binanceDexNodeApi.getProposalById(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 proposalJson = new String(response.getValue());
        return EncodeUtils.toObjectFromJsonString(proposalJson, Proposal.class);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 6
Source Project: web3sdk   Source File: ECKeyTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void eckeyTest() throws Exception {

    ECKeyPair keyPair = Keys.createEcKeyPair();
    System.out.println("public key " + keyPair.getPublicKey());
    System.out.println("private key " + keyPair.getPrivateKey());
    System.out.println("serialize key " + Hex.toHexString(Keys.serialize(keyPair)));
    // public key
    // 6005884739482598907019672016029935954035758996027051146272921018865015941269698926222431345309233458526942087465818124661687956402067203118790805113144306
    // private key 11695290896330592173013668505941497555094145434653626165899956696676058923570
    // serialize key
    keyPair =
            Keys.deserialize(
                    Hex.decode(
                            "19db4cd14479981c3d7e785ec2412619885b5a7ffc438e6801474b962996023272ac27315da55056067973a3b58b27385bb9c919331df1751771016efcbe61a969458d6f7286b7a7107e4cd6e17b348c9df6c2b3fe9bf239555f90a78f8603f2"));
    System.out.println("public key " + keyPair.getPublicKey());
    System.out.println("private key " + Hex.toHexString(keyPair.getPrivateKey().toByteArray()));
    String str = "hello world";
    Sign.SignatureData sigData = Sign.getSignInterface().signMessage(str.getBytes(), keyPair);
    BigInteger publicKey = Sign.signedMessageToKey(str.getBytes(), sigData);
    System.out.println("publicKey " + publicKey);
}
 
Example 7
Source Project: julongchain   Source File: GmCspTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 密钥生成测试
 *
 * @throws CspException
 */
@Test
public void keyGenTest() throws CspException {
    System.out.println("test keyGen...");
    try {
        IKey sm2key = csp.keyGen(new SM2KeyGenOpts());
        IKey sm4key = csp.keyGen(new SM4KeyGenOpts());
        if (sm2key instanceof SM2Key) {
            System.out.println("generate the key's type is SM2");
            System.out.println("SM2 publicKey:" + Hex.toHexString(sm2key.getPublicKey().toBytes()));
            System.out.println("SM2 privateKey:" + Hex.toHexString(sm2key.toBytes()));
        }
        if (sm4key instanceof SM4Key) {
            System.out.println("generate the key's type is SM4");
            System.out.println("SM4 Key:" + Hex.toHexString(sm4key.toBytes()));
        }
    } catch (CspException e) {
        throw new CspException(e);
    }
}
 
Example 8
@Test
@DisplayName("bytes32[] encodes correctly")
void fixedBytesArrayEncoding() {
    // each string should be padded to 32 bytes and have no length prefix

    final ContractFunctionParams params = new ContractFunctionParams()
        .addBytes32Array(new byte[][] {
            "Hello".getBytes(StandardCharsets.UTF_8),
            ",".getBytes(StandardCharsets.UTF_8),
            "world!".getBytes(StandardCharsets.UTF_8)
        });

    assertEquals(
        "0000000000000000000000000000000000000000000000000000000000000020" +
            "0000000000000000000000000000000000000000000000000000000000000003" + // length of array
            "48656c6c6f000000000000000000000000000000000000000000000000000000" + // "Hello" UTF-8 encoded
            "2c00000000000000000000000000000000000000000000000000000000000000" + // "," UTF-8 encoded
            "776f726c64210000000000000000000000000000000000000000000000000000", // "world!" UTF-8 encoded
        Hex.toHexString(params.toBytes(null).toByteArray())
    );
}
 
Example 9
Source Project: julongchain   Source File: MspValidateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void skKeyTest() throws IOException, JulongChainException, NoSuchAlgorithmException, InvalidKeySpecException {

    String sk_path = MspValidateTest.class.getResource("/sk-dxtest_sk").getPath();

    File inFile = new File(sk_path);
    long fileLen = inFile.length();
    Reader reader = null;
    PemObject pemObject = null;
    reader = new FileReader(inFile);
    char[] content = new char[(int) fileLen];
    reader.read(content);
    String str = new String(content);
    StringReader stringreader = new StringReader(str);
    PemReader pem = new PemReader(stringreader);
    pemObject = pem.readPemObject();

    System.out.println(Hex.toHexString(pemObject.getContent()));
}
 
Example 10
Source Project: cstc   Source File: RsaEncryption.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected byte[] perform(byte[] input) throws Exception {

		if( ! this.certAvailable.isSelected() )
			throw new IllegalArgumentException("No certificate available.");
		
		String padding = (String)paddings.getSelectedItem();
		Cipher cipher = Cipher.getInstance(String.format("%s/%s/%s", algorithm, cipherMode, padding));
        cipher.init(Cipher.ENCRYPT_MODE, this.cert.getPublicKey());
        
        String selectedInputMode = (String)inputMode.getSelectedItem();
        String selectedOutputMode = (String)outputMode.getSelectedItem();
        
        if( selectedInputMode.equals("Hex") )
        	input = Hex.decode(input);
        if( selectedInputMode.equals("Base64") )
        	input = Base64.decode(input);
      
		byte[] encrypted = cipher.doFinal(input);
		
		if( selectedOutputMode.equals("Hex") )
			encrypted = Hex.encode(encrypted);
		if( selectedOutputMode.equals("Base64") )
			encrypted = Base64.encode(encrypted);

		return encrypted;
	}
 
Example 11
Source Project: cstc   Source File: RsaDecryption.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected byte[] perform(byte[] input) throws Exception {

		if( ! this.keyAvailable.isSelected() )
			throw new IllegalArgumentException("No private key available.");
		
		String padding = (String)paddings.getSelectedItem();
		Cipher cipher = Cipher.getInstance(String.format("%s/%s/%s", algorithm, cipherMode, padding));
        cipher.init(Cipher.DECRYPT_MODE, this.selectedEntry.getPrivateKey());
        
        String selectedInputMode = (String)inputMode.getSelectedItem();
        String selectedOutputMode = (String)outputMode.getSelectedItem();
        
        if( selectedInputMode.equals("Hex") )
        	input = Hex.decode(input);
        if( selectedInputMode.equals("Base64") )
        	input = Base64.decode(input);
      
		byte[] encrypted = cipher.doFinal(input);
		
		if( selectedOutputMode.equals("Hex") )
			encrypted = Hex.encode(encrypted);
		if( selectedOutputMode.equals("Base64") )
			encrypted = Base64.encode(encrypted);

		return encrypted;
	}
 
Example 12
Source Project: burstkit4j   Source File: AT.java    License: Apache License 2.0 6 votes vote down vote up
public AT(ATResponse atResponse) {
    this.dead = atResponse.isDead();
    this.finished = atResponse.isFinished();
    this.frozen = atResponse.isFrozen();
    this.running = atResponse.isRunning();
    this.stopped = atResponse.isStopped();
    this.creator = BurstAddress.fromEither(atResponse.getCreator());
    this.id = BurstAddress.fromEither(atResponse.getAt());
    this.balance = BurstValue.fromPlanck(atResponse.getBalanceNQT());
    this.minimumActivation = BurstValue.fromPlanck(atResponse.getMinActivation());
    this.previousBalance = BurstValue.fromPlanck(atResponse.getPrevBalanceNQT());
    this.machineCode = Hex.decode(atResponse.getMachineCode());
    this.machineData = Hex.decode(atResponse.getMachineData());
    this.creationHeight = atResponse.getCreationBlock();
    this.nextBlockHeight = atResponse.getNextBlock();
    this.version = atResponse.getAtVersion();
    this.description = atResponse.getDescription();
    this.name = atResponse.getName();
}
 
Example 13
Source Project: julongchain   Source File: MerkleTree.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
		MerkleTree tree = new MerkleTree(2);
//		tree.update("1".getBytes(StandardCharsets.UTF_8));
//		tree.update("2".getBytes(StandardCharsets.UTF_8));
//		tree.update("3".getBytes(StandardCharsets.UTF_8));
//		tree.update("4".getBytes(StandardCharsets.UTF_8));
//		tree.update("5".getBytes(StandardCharsets.UTF_8));
//		tree.update("6".getBytes(StandardCharsets.UTF_8));
//		tree.update("7".getBytes(StandardCharsets.UTF_8));
//		tree.update("8".getBytes(StandardCharsets.UTF_8));
//		tree.update("9".getBytes(StandardCharsets.UTF_8));
		tree.done();
		System.out.println(Hex.toHexString(tree.getRootHash()) == null);
		KvRwset.QueryReadsMerkleSummary summery = tree.getSummery();
		System.out.println(summery);
	}
 
Example 14
Source Project: eosio-java   Source File: PEMProcessorTest.java    License: MIT License 6 votes vote down vote up
@Test
public void validatePEMProcessorMethodsWorkWithPEMFormattedPublicKey(){
    String keyType = "PUBLIC KEY";
    AlgorithmEmployed algorithmEmployed = AlgorithmEmployed.SECP256R1;
    String derFormat = "3039301306072a8648ce3d020106082a8648ce3d0301070322000225504e5e605305251e74a9e4bf5d6c0fc6411d598937768224493ee5a02b0e16";
    String keyData = "0225504e5e605305251e74a9e4bf5d6c0fc6411d598937768224493ee5a02b0e16";

    String pemFormattedPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
            "MDkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDIgACJVBOXmBTBSUedKnkv11sD8ZBHVmJN3aCJEk+5aArDhY=\n" +
            "-----END PUBLIC KEY-----";

    try {
        PEMProcessor pemProcessor = new PEMProcessor(pemFormattedPublicKey);
        assertEquals(keyType, pemProcessor.getType());
        assertEquals(algorithmEmployed, pemProcessor.getAlgorithm());
        assertEquals(derFormat, pemProcessor.getDERFormat());
        assertEquals(keyData, Hex.toHexString(pemProcessor.getKeyData()));
    } catch (PEMProcessorError pemProcessorError) {
        fail("Not expecting an PEMProcessorError to be thrown!");
    }

}
 
Example 15
Source Project: java-sdk   Source File: BinanceDexApiNodeClientImpl.java    License: 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 16
Source Project: burstkit4j   Source File: HttpBurstNodeService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Single<byte[]> generateMultiOutSameTransaction(byte[] senderPublicKey, BurstValue amount, BurstValue fee, int deadline, Set<BurstAddress> recipients) throws IllegalArgumentException {
    return Single.fromCallable(() -> {
        StringBuilder recipientsString = new StringBuilder();
        if (recipients.size() > 128 || recipients.size() < 2) {
            throw new IllegalArgumentException("Must have 2-128 recipients, had " + recipients.size());
        }
        for (BurstAddress recipient : recipients) {
            recipientsString.append(recipient.getID()).append(";");
        }
        recipientsString.setLength(recipientsString.length() - 1);
        return recipientsString;
    }).flatMap(recipientsString -> assign(burstAPIService.sendMoneyMultiSame(BurstKitUtils.getEndpoint(), null,
            Hex.toHexString(senderPublicKey), fee.toPlanck().toString(), String.valueOf(deadline), null, false,
            recipientsString.toString(), amount.toPlanck().toString()))
                    .map(response -> Hex.decode(response.getUnsignedTransactionBytes())));
}
 
Example 17
Source Project: WeEvent   Source File: DataTypeUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * generate topicName hash
 *
 * @param topicName topic name
 * @return substring left 4bit hash data to hex encode
 */
public static String genTopicNameHash(String topicName) {
    if (topicHashMap.containsKey(topicName)) {
        return topicHashMap.get(topicName);
    }

    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] messageDigest = md.digest(topicName.getBytes());
        String hash = new String(Hex.encode(messageDigest)).substring(0, WeEventConstants.TOPIC_NAME_ENCODE_LENGTH);
        topicHashMap.put(topicName, hash);

        log.info("topic name hash: {} <-> {}", topicName, hash);
        return hash;
    } catch (NoSuchAlgorithmException e) {
        log.error("NoSuchAlgorithmException:{}", e.getMessage());
        return "";
    }
}
 
Example 18
Source Project: java-sdk   Source File: BinanceDexApiNodeClientImpl.java    License: 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 19
Source Project: burstkit4j   Source File: HttpBurstNodeService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Single<byte[]> generateMultiOutTransaction(byte[] senderPublicKey, BurstValue fee, int deadline, Map<BurstAddress, BurstValue> recipients) throws IllegalArgumentException {
    return Single.fromCallable(() -> {
        StringBuilder recipientsString = new StringBuilder();
        if (recipients.size() > 64 || recipients.size() < 2) {
            throw new IllegalArgumentException("Must have 2-64 recipients, had " + recipients.size());
        }
        for (Map.Entry<BurstAddress, BurstValue> recipient : recipients.entrySet()) {
            recipientsString.append(recipient.getKey().getID()).append(":").append(recipient.getValue().toPlanck())
                    .append(";");
        }
        recipientsString.setLength(recipientsString.length() - 1);
        return recipientsString;
    }).flatMap(recipientsString -> assign(
            burstAPIService.sendMoneyMulti(BurstKitUtils.getEndpoint(), null, Hex.toHexString(senderPublicKey),
                    fee.toPlanck().toString(), String.valueOf(deadline), null, false, recipientsString.toString()))
                            .map(response -> Hex.decode(response.getUnsignedTransactionBytes())));
}
 
Example 20
Source Project: fido2   Source File: common.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public static String calculateHMAC(String secret, String data) {
    try {
        SecretKeySpec signingKey = new SecretKeySpec(Hex.decode(secret), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256", new BouncyCastleFipsProvider());
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(data.getBytes());
        return Base64.toBase64String(rawHmac);
    } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalStateException ex) {
        System.out.println("Unexpected error while creating hash: " + ex.getMessage());
        throw new IllegalArgumentException();
    }
}
 
Example 21
Source Project: nuls-v2   Source File: Utils.java    License: MIT License 5 votes vote down vote up
/**
 * @param number should be in form '0x34fabd34....'
 * @return String
 */
public static BigInteger unifiedNumericToBigInteger(String number) {

    boolean match = Pattern.matches("0[xX][0-9a-fA-F]+", number);
    if (!match) {
        return (new BigInteger(number));
    } else {
        number = number.substring(2);
        number = number.length() % 2 != 0 ? "0".concat(number) : number;
        byte[] numberBytes = Hex.decode(number);
        return (new BigInteger(1, numberBytes));
    }
}
 
Example 22
Source Project: besu   Source File: GenesisStateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void encodeOlympicBlock() throws Exception {
  final GenesisState genesisState =
      GenesisState.fromJson(
          Resources.toString(
              GenesisStateTest.class.getResource("genesis-olympic.json"), Charsets.UTF_8),
          MainnetProtocolSchedule.create());
  final BytesValueRLPOutput tmp = new BytesValueRLPOutput();
  genesisState.getBlock().writeTo(tmp);
  assertThat(Hex.toHexString(genesisState.getBlock().getHeader().getHash().toArray()))
      .isEqualTo(OLYMPIC_HASH);
  assertThat(Hex.toHexString(tmp.encoded().toArray())).isEqualTo(OLYMPIC_RLP);
}
 
Example 23
Source Project: hedera-sdk-java   Source File: SolidityUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static String addressForEntity(long shardNum, long realmNum, long entityNum) {
    if (Long.highestOneBit(shardNum) > 32) {
        throw new IllegalArgumentException("shardNum out of 32-bit range " + shardNum);
    }

    return Hex.toHexString(
        ByteBuffer.allocate(20)
            .putInt((int) shardNum)
            .putLong(realmNum)
            .putLong(entityNum)
            .array());
}
 
Example 24
Source Project: besu   Source File: IbftExtraDataTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void parseGenesisBlockWithZeroProposerSeal() {
  final byte[] genesisBlockExtraData =
      Hex.decode(
          "0000000000000000000000000000000000000000000000000000000000000000f89af85494c332d0db1704d18f89a590e7586811e36d37ce049424defc2d149861d3d245749b81fe0e6b28e04f31943814f17bd4b7ce47ab8146684b3443c0a4b2fc2c942a813d7db3de19b07f92268b6d4125ed295cbe00b8410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0");

  final Bytes bufferToInject = Bytes.wrap(genesisBlockExtraData);

  final IbftExtraData extraData = IbftExtraData.decodeRaw(bufferToInject);
  assertThat(extraData.getProposerSeal()).isNull();
}
 
Example 25
Source Project: julongchain   Source File: SM4Test.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void DataTest() throws  CspException {
    System.out.println("------------------------------------------消息加密-----------------------------------------------------");
    String plainText = "Ding xuan abccddee!!!!";
    System.out.println("消息原文:" + plainText);
    System.out.println(Hex.toHexString(plainText.getBytes()));
    byte[] sm4key = SM4.generateKey();
    byte[] decryptData = sm4.encryptECB(plainText.getBytes(), sm4key);
    System.out.println("加密后消息:" + Hex.toHexString(decryptData));
    System.out.println("------------------------------------------解密数据-----------------------------------------------------");
    byte[] plainContent = sm4.decryptECB(decryptData, sm4key);
    String encryptBefore = new String(plainContent);
    System.out.println("原文数据:" + encryptBefore);
}
 
Example 26
Source Project: hedera-sdk-java   Source File: Keystore.java    License: Apache License 2.0 5 votes vote down vote up
private JsonObject exportJson(String passphrase) {
    final JsonObject object = new JsonObject();
    object.addProperty("version", 1);

    final JsonObject crypto = new JsonObject();
    crypto.addProperty("cipher", "aes-128-ctr");
    crypto.addProperty("kdf", "pbkdf2");

    final byte[] salt = CryptoUtils.randomBytes(CryptoUtils.SALT_LEN);

    final KeyParameter cipherKey = CryptoUtils.deriveKeySha256(passphrase, salt, CryptoUtils.ITERATIONS, CryptoUtils.DK_LEN);

    final byte[] iv = CryptoUtils.randomBytes(CryptoUtils.IV_LEN);

    final byte[] cipherBytes = CryptoUtils.encryptAesCtr128(cipherKey, iv, keyBytes);

    final byte[] mac = CryptoUtils.calcHmacSha384(cipherKey, cipherBytes);

    final JsonObject cipherParams = new JsonObject();
    cipherParams.addProperty("iv", Hex.toHexString(iv));

    final JsonObject kdfParams = new JsonObject();
    kdfParams.addProperty("dkLen", CryptoUtils.DK_LEN);
    kdfParams.addProperty("salt", Hex.toHexString(salt));
    kdfParams.addProperty("c", CryptoUtils.ITERATIONS);
    kdfParams.addProperty("prf", "hmac-sha256");

    crypto.add("cipherparams", cipherParams);
    crypto.addProperty("ciphertext", Hex.toHexString(cipherBytes));
    crypto.add("kdfparams", kdfParams);
    crypto.addProperty("mac", Hex.toHexString(mac));

    object.add("crypto", crypto);

    return object;
}
 
Example 27
Source Project: burstkit4j   Source File: BurstCryptoTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCryptoMd5() {
    MessageDigest md5 = burstCrypto.getMD5();
    assertEquals("d41d8cd98f00b204e9800998ecf8427e", Hex.toHexString(md5.digest(stringToBytes(""))));
    assertEquals("fa6a5a3224d7da66d9e0bdec25f62cf0", Hex.toHexString(md5.digest(stringToBytes("Testing"))));
    assertEquals("5251a8a65a96abd2bf344f84c64b7d71", Hex.toHexString(md5.digest(stringToBytes("Burstcoin!"))));
    assertEquals("48fe9ca8e71d7334f4566909aef4350d", Hex.toHexString(md5.digest(stringToBytes("Burst Apps Team"))));
}
 
Example 28
Source Project: jlibra   Source File: LibraKeyFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void hasherTest() {
    SHA3.Digest256 sha3 = new SHA3.Digest256();
    byte[] digest = sha3.digest("abc".getBytes());
    assertEquals(
            "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532",
            Hex.toHexString(digest));
}
 
Example 29
Source Project: jlibra   Source File: LibraKeyFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void privateChild() {
    Mnemonic mnemonic = Mnemonic.fromString(TEST_MNEMONIC);
    Seed seed = new Seed(mnemonic, "LIBRA");
    LibraKeyFactory libraKeyFactory = new LibraKeyFactory(seed);

    // Check child_0 key derivation.
    ExtendedPrivKey childPrivate0 = libraKeyFactory.privateChild(new ChildNumber(0));

    assertEquals(
            "3051020101300506032b657004220420358a375f36d74c30b7f3299b62d712b307725938f8cc931100fbd10a434fc8b9812100b1894672e853ee6d2f1c094b0db2c2644edd4736f46c4357c709fdded5797c44",
            Hex.toHexString(childPrivate0.privateKey.getEncoded()));

    // Check determinism, regenerate child_0.
    ExtendedPrivKey childPrivate0_again = libraKeyFactory.privateChild(new ChildNumber(0));
    assertEquals(
            Hex.toHexString(childPrivate0.privateKey.getEncoded()),
            Hex.toHexString(childPrivate0_again.privateKey.getEncoded()));

    // Check child_1 key derivation.
    ExtendedPrivKey childPrivate1 = libraKeyFactory.privateChild(new ChildNumber(1));
    assertEquals(
            "3051020101300506032b657004220420a325fe7d27b1b49f191cc03525951fec41b6ffa2d4b3007bb1d9dd353b7e56a6812100c66551332920eda683a977292305ef6c10c34b27d9fef331bbd851f5c74d09ee",
            Hex.toHexString(childPrivate1.privateKey.getEncoded()));

    ChildNumber child1Again = new ChildNumber(0).increment();
    assertEquals(new ChildNumber(1).data, child1Again.data);

    // Check determinism, regenerate child_1, but by incrementing ChildNumber(0).
    ExtendedPrivKey childPrivate1FromIncrement = libraKeyFactory.privateChild(child1Again);
    assertEquals(
            "3051020101300506032b657004220420a325fe7d27b1b49f191cc03525951fec41b6ffa2d4b3007bb1d9dd353b7e56a6812100c66551332920eda683a977292305ef6c10c34b27d9fef331bbd851f5c74d09ee",
            Hex.toHexString(childPrivate1FromIncrement.privateKey.getEncoded()));
}
 
Example 30
Source Project: julongchain   Source File: BlockStream.java    License: Apache License 2.0 5 votes vote down vote up
/**
   * 下一区块并返回当前信息
   */
  public AbstractMap.SimpleEntry<byte[], BlockPlacementInfo> nextBlockBytesAndPlacementInfo() throws LedgerException{
      AbstractMap.SimpleEntry<byte[], BlockPlacementInfo> entry = currentFileStream.nextBlockBytesAndPlacementInfo();
      byte[] blockBytes = entry.getKey();
      log.debug(String.format("Blockbytes [%s] read from file [%d]", Hex.toHexString(blockBytes), currentFileNum));
      //当前文件无法读取出block
boolean expected = ((blockBytes == null || blockBytes.length == 0) && (currentFileNum < endFileNum || endFileNum < 0));
      if(expected){
          log.debug(String.format("Current file [%d] exhausted. Moving to next file", currentFileNum));
          moveToNextBlockFileStream();
          return nextBlockBytesAndPlacementInfo();
      }
      return entry;
  }