org.bouncycastle.util.encoders.Hex Java Examples

The following examples show how to use org.bouncycastle.util.encoders.Hex. 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: Main.java    From fido2 with GNU Lesser General Public License v2.1 7 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
Source File: PublicKeyTest.java    From hedera-sdk-java with 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 #3
Source File: MaskedField.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
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 #4
Source File: HttpBurstNodeService.java    From burstkit4j with 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 #5
Source File: FileKeyStore.java    From julongchain with 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 #6
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 #7
Source File: AT.java    From burstkit4j with 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 #8
Source File: BinanceDexApiNodeClientImpl.java    From java-sdk with 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 #9
Source File: ECKeyTest.java    From web3sdk with 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 #10
Source File: DataTypeUtils.java    From WeEvent with 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 #11
Source File: HttpBurstNodeService.java    From burstkit4j with 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 #12
Source File: GmCspTest.java    From julongchain with 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 #13
Source File: ContractFunctionParamsTest.java    From hedera-sdk-java with Apache License 2.0 6 votes vote down vote up
@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 #14
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 #15
Source File: MspValidateTest.java    From julongchain with 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 #16
Source File: RsaEncryption.java    From cstc with 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 #17
Source File: RsaDecryption.java    From cstc with 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 #18
Source File: PEMProcessorTest.java    From eosio-java with 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 #19
Source File: MerkleTree.java    From julongchain with 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 #20
Source File: Utils.java    From nuls-v2 with MIT License 5 votes vote down vote up
/**
 * Decodes a hex string to address bytes and checks validity
 *
 * @param hex - a hex string of the address, e.g., 6c386a4b26f73c802f34673f7248bb118f97424a
 * @return - decode and validated address byte[]
 */
public static byte[] addressStringToBytes(String hex) {
    final byte[] addr;
    try {
        addr = Hex.decode(hex);
    } catch (DecoderException addressIsNotValid) {
        return null;
    }

    if (isValidAddress(addr)) {
        return addr;
    }
    return null;
}
 
Example #21
Source File: Ed25519PrivateKeyTest.java    From hedera-sdk-java with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@DisplayName("reproducible signature can be computed")
@MethodSource("privKeyStrings")
void reproducibleSignature(String keyStr) {
    final Ed25519PrivateKey key = Ed25519PrivateKey.fromString(keyStr);
    final byte[] signature = key.sign(messageBytes);

    assertEquals(
        sigStr,
        Hex.toHexString(signature)
    );
}
 
Example #22
Source File: HashUtil.java    From nuls-v2 with MIT License 5 votes vote down vote up
/**
 * @return generates random peer id for the HelloMessage
 */
public static byte[] randomPeerId() {

    byte[] peerIdBytes = new BigInteger(512, Utils.getRandom()).toByteArray();

    final String peerId;
    if (peerIdBytes.length > 64) {
        peerId = Hex.toHexString(peerIdBytes, 1, 64);
    } else {
        peerId = Hex.toHexString(peerIdBytes);
    }

    return Hex.decode(peerId);
}
 
Example #23
Source File: SM3Test.java    From julongchain with Apache License 2.0 5 votes vote down vote up
@Test
public void standardDataTest() throws CspException {
    byte[] testData = "abc".getBytes();
    String standardDigest = "66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0";
    System.out.println("测试数据ASCII码" + Hex.toHexString(testData));
    byte[] hashValue = sm3.hash(testData);
    System.out.println(hashValue.length);
    System.out.println(Hex.toHexString(hashValue));
    assertEquals(standardDigest, Hex.toHexString(hashValue));
}
 
Example #24
Source File: HttpBurstNodeService.java    From burstkit4j with Apache License 2.0 5 votes vote down vote up
@Override
public Single<byte[]> generateTransactionWithMessage(BurstAddress recipient, byte[] senderPublicKey, BurstValue amount, BurstValue fee, int deadline, byte[] message) {
    return assign(burstAPIService.sendMoney(BurstKitUtils.getEndpoint(), recipient.getID(), null,
            amount.toPlanck().toString(), null, Hex.toHexString(senderPublicKey), fee.toPlanck().toString(),
            deadline, null, false, Hex.toHexString(message), false, null, null, null, null, null, null, null, null))
                    .map(response -> Hex.decode(response.getUnsignedTransactionBytes()));
}
 
Example #25
Source File: GMT0016CpsGetKeyTest.java    From julongchain with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetKeyByRSA2048()  throws JulongChainException{
    System.out.println("==========test function geyGen and IKeyGenOpts instance RSAOpts.RSA2048KeyGenOpts==========");

    IKeyGenOpts rsa2048keyGenOpts = new RSAOpts.RSA2048KeyGenOpts(false);
    IKey rsa2048Key = csp.keyGen(rsa2048keyGenOpts);
    Assert.assertNotNull(rsa2048Key);
    byte [] ski = rsa2048Key.ski();
    IKey rsa2048KeyCopy = csp.getKey(ski);
    Assert.assertNotNull(rsa2048KeyCopy);
    Assert.assertEquals(Hex.toHexString(rsa2048Key.toBytes()),Hex.toHexString(rsa2048KeyCopy.toBytes()));
}
 
Example #26
Source File: ModhexTest.java    From yubikit-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testEncode() {
    Assert.assertEquals("dteffuje", Modhex.encode(Hex.decode("2d344e83")));
    Assert.assertEquals("hknhfjbrjnlnldnhcujvddbikngjrtgh", Modhex.encode(Hex.decode("69b6481c8baba2b60e8f22179b58cd56")));
    Assert.assertEquals("urtubjtnuihvntcreeeecvbregfjibtn", Modhex.encode(Hex.decode("ecde18dbe76fbd0c33330f1c354871db")));
    Assert.assertEquals("ifhgieif", Modhex.encode("test".getBytes()));
}
 
Example #27
Source File: EOSFormatterTest.java    From eosio-java with MIT License 5 votes vote down vote up
/**
 * Validate positive ExtractSerializedTransactionFromSignable
 */
@Test
public void validateExtractSerializedTransactionFromSignable() {
    String chainId = "687fa513e18843ad3e820744f4ffcf93b1354036d80737db8dc444fe4b15ad17";
    String expectedSerializedTransaction = "8BC2A35CF56E6CC25F7F000000000100A6823403EA3055000000572D3CCDCD01000000000000C03400000000A8ED32322A000000000000C034000000000000A682A08601000000000004454F530000000009536F6D657468696E6700";
    String signableTransaction = chainId + expectedSerializedTransaction + Hex.toHexString(new byte[32]);

    try {
        String serializedTransaction = EOSFormatter.extractSerializedTransactionFromSignable(signableTransaction);
        assertEquals(expectedSerializedTransaction, serializedTransaction);
    } catch (EOSFormatterError eosFormatterError) {
        eosFormatterError.printStackTrace();
        fail("Should not throw exception here");
    }
}
 
Example #28
Source File: GmCspTest.java    From julongchain with Apache License 2.0 5 votes vote down vote up
@Test
public void rngTest() throws CspException {
    for (int i = 0; i < 100; i++) {
        long t1 = System.currentTimeMillis();
        byte[] secureSeed = csp.rng(24, null);
        long t2 = System.currentTimeMillis();
        System.out.println(String.format("随机数长度:%s", secureSeed.length));
        System.out.println(Hex.toHexString(secureSeed));
        System.out.println(String.format("生成随机数消耗时间%s ms", (t2 - t1)));
    }

}
 
Example #29
Source File: CmsCryptoOpenSSLImpl.java    From oneops with Apache License 2.0 5 votes vote down vote up
/**
 * Decrypt.
 *
 * @param instr the instr
 * @return the string
 * @throws GeneralSecurityException the general security exception
 */
@Override
public String decrypt(String instr)  throws GeneralSecurityException {
	byte[]  in;
	if (instr.startsWith(CmsCrypto.ENC_PREFIX)) {
		in =  Hex.decode(instr.substring(CmsCrypto.ENC_PREFIX.length()));
	} else {
		in = Hex.decode(instr);
	}
       byte[]  out = decryptor.doFinal(in);
       return new String(out);
}
 
Example #30
Source File: BurstNodeServiceTest.java    From burstkit4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testBurstServiceGenerateCreateATTransaction() {
    byte[] lotteryAtCode = Hex.decode("1e000000003901090000006400000000000000351400000000000201000000000000000104000000803a0900000000000601000000040000003615000200000000000000260200000036160003000000020000001f030000000100000072361b0008000000020000002308000000090000000f1af3000000361c0004000000020000001e0400000035361700040000000200000026040000007f2004000000050000001e02050000000400000036180006000000020000000200000000030000001a39000000352000070000001b07000000181b0500000012332100060000001a310100000200000000030000001a1a0000003618000a0000000200000020080000000900000023070800000009000000341f00080000000a0000001a78000000341f00080000000a0000001ab800000002000000000400000003050000001a1a000000");
    byte[] lotteryAtCreationBytes = BurstCrypto.getInstance().getATCreationBytes((short) 1, lotteryAtCode, new byte[0], (short) 1, (short) 1, (short) 1, BurstValue.fromBurst(2));
    assertEquals("01000000020001000100010000c2eb0b0000000044011e000000003901090000006400000000000000351400000000000201000000000000000104000000803a0900000000000601000000040000003615000200000000000000260200000036160003000000020000001f030000000100000072361b0008000000020000002308000000090000000f1af3000000361c0004000000020000001e0400000035361700040000000200000026040000007f2004000000050000001e02050000000400000036180006000000020000000200000000030000001a39000000352000070000001b07000000181b0500000012332100060000001a310100000200000000030000001a1a0000003618000a0000000200000020080000000900000023070800000009000000341f00080000000a0000001a78000000341f00080000000a0000001ab800000002000000000400000003050000001a1a00000000", Hex.toHexString(lotteryAtCreationBytes));
    byte[] createATResponse = RxTestUtils.testSingle(burstNodeService.generateCreateATTransaction(TestVariables.EXAMPLE_ACCOUNT_PUBKEY, BurstValue.fromBurst(5), 1440, "TestAT", "An AT For Testing", lotteryAtCreationBytes));

    byte[] fatLotteryAtCreationBytes = BurstCrypto.getInstance().getATCreationBytes((short) 1, lotteryAtCode, new byte[0], (short) 10, (short) 10, (short) 10, BurstValue.fromBurst(2));
    assertEquals("0100000002000a000a000a0000c2eb0b0000000044011e000000003901090000006400000000000000351400000000000201000000000000000104000000803a0900000000000601000000040000003615000200000000000000260200000036160003000000020000001f030000000100000072361b0008000000020000002308000000090000000f1af3000000361c0004000000020000001e0400000035361700040000000200000026040000007f2004000000050000001e02050000000400000036180006000000020000000200000000030000001a39000000352000070000001b07000000181b0500000012332100060000001a310100000200000000030000001a1a0000003618000a0000000200000020080000000900000023070800000009000000341f00080000000a0000001a78000000341f00080000000a0000001ab800000002000000000400000003050000001a1a0000000000", Hex.toHexString(fatLotteryAtCreationBytes));
    byte[] fatCreateATResponse = RxTestUtils.testSingle(burstNodeService.generateCreateATTransaction(TestVariables.EXAMPLE_ACCOUNT_PUBKEY, BurstValue.fromBurst(5), 1440, "TestAT", "An AT For Testing", lotteryAtCreationBytes));
}