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

The following examples show how to use org.bouncycastle.util.encoders.Hex#decode() . 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: GmCspTest.java    From julongchain with Apache License 2.0 6 votes vote down vote up
/**
 * GM/T 0004-2012 <SM3密码杂凑算法>附录A 示例2
 *
 * @throws CspException
 */
@Test
public void hashUnitTest2() throws CspException {
    try {
        String message = "abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd";
        byte[] msg = message.getBytes("ASCII");
        String encodedHexMsg = Hex.toHexString(msg);
        System.out.println("To Hash Message:" + encodedHexMsg);
        String expectedResult = "debe9ff92275b8a138604889c18e5a4d6fdb70e5387e5765293dcba39c0c5732";
        byte[] expectedHashMsg = Hex.decode(expectedResult);
        IHashOpts hashOpts = new SM3HashOpts();
        byte[] digests = csp.hash(msg, hashOpts);
        String encodedHexDigests = Hex.toHexString(digests);
        System.out.println(encodedHexDigests);
        Assert.assertArrayEquals(digests, expectedHashMsg);
        System.out.println("Hash Unit Test 2 passed!");
    } catch (UnsupportedEncodingException e) {
        throw new CspException(e);
    }
}
 
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: ByteUtilsTest.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
@Test
public void omitsSignIndicationByteProperly() {
  final BigInteger a = new BigInteger(1, Hex.decode("ff12345678"));
  final byte[] a5 = ByteUtils.bigIntegerToBytes(a);
  assertThat(a5.length).isEqualTo(5);
  assertThat(a5).containsExactly(Hex.decode("ff12345678"));

  final BigInteger b = new BigInteger(1, Hex.decode("0f12345678"));
  final byte[] b5 = ByteUtils.bigIntegerToBytes(b);
  assertThat(b5.length).isEqualTo(5);
  assertThat(b5).containsExactly(Hex.decode("0f12345678"));
}
 
Example 4
Source File: PublicKeyTest.java    From hedera-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("can convert from protobuf ED25519 key to PublicKey")
void fromProtoKeyEd25519() {
    final byte[] keyBytes = Hex.decode("0011223344556677889900112233445566778899001122334455667788990011");
    final Key protoKey = Key.newBuilder().setEd25519(ByteString.copyFrom(keyBytes)).build();

    final PublicKey cut = PublicKey.fromProtoKey(protoKey);

    assertEquals(cut.getClass(), Ed25519PublicKey.class);
    assertArrayEquals(keyBytes, ((Ed25519PublicKey)cut).toBytes());
}
 
Example 5
Source File: SM4Test.java    From julongchain with Apache License 2.0 5 votes vote down vote up
@Test
public void  decryptEcb() throws CspException {
    byte[] testData = Hex.decode("01234567454545");
    byte[] sm4key = SM4.generateKey();
    byte[] decryptData = sm4.encryptECB(testData, sm4key);
    byte[] plainText=sm4.decryptECB(decryptData, sm4key);
    System.out.println(Hex.toHexString(plainText));
}
 
Example 6
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 7
Source File: Utils.java    From nuls-v2 with 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 8
Source File: PublicKeyTest.java    From hedera-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("can convert from protobuf threshold key to PublicKey")
void fromProtoKeyThresholdKey() {
    // 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 ThresholdKey.Builder protoThresholdKey = ThresholdKey.newBuilder().setThreshold(1).setKeys(protoKeyList);
    final KeyOrBuilder protoKey = Key.newBuilder().setThresholdKey(protoThresholdKey).build();

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

    // then
    assertEquals(cut.getClass(), com.hedera.hashgraph.sdk.crypto.ThresholdKey.class);
    final com.hedera.hashgraph.sdk.crypto.ThresholdKey thresholdKey =
        (com.hedera.hashgraph.sdk.crypto.ThresholdKey)cut;
    final ThresholdKey actual = thresholdKey.toKeyProto().getThresholdKey();
    assertEquals(1, actual.getThreshold());
    assertEquals(2, actual.getKeys().getKeysCount());
    assertArrayEquals(keyBytes[0], actual.getKeys().getKeys(0).getEd25519().toByteArray());
    assertArrayEquals(keyBytes[1], actual.getKeys().getKeys(1).getEd25519().toByteArray());
}
 
Example 9
Source File: FromHex.java    From cstc with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected byte[] perform(byte[] input) throws Exception {
	String selectedKey = (String) this.delimiterBox.getSelectedItem();
	Delimiter delimiter = ToHex.delimiters.get(selectedKey);

	if (delimiter.value.length == 0) { // No delimiter
		return Hex.decode(input);
	}
	
	String delimiterStr = new String(delimiter.value);		
	String inputStr = new String(input);
	inputStr = inputStr.replace(delimiterStr, "");
	
	return Hex.decode(inputStr);
}
 
Example 10
Source File: PublicKey.java    From hedera-sdk-java with Apache License 2.0 5 votes vote down vote up
public static PublicKey fromString(String keyString) {
    SubjectPublicKeyInfo pubKeyInfo;

    try {
        byte[] keyBytes = Hex.decode(keyString);

        // it could be a hex-encoded raw public key or a DER-encoded public key
        if (keyBytes.length == Ed25519.PUBLIC_KEY_SIZE) {
            return Ed25519PublicKey.fromBytes(keyBytes);
        }

        pubKeyInfo = SubjectPublicKeyInfo.getInstance(keyBytes);
    } catch (Exception e) {
        throw new IllegalArgumentException("Failed to parse public key", e);
    }

    ASN1ObjectIdentifier algId = pubKeyInfo.getAlgorithm()
        .getAlgorithm();

    if (algId.equals(EdECObjectIdentifiers.id_Ed25519)) {
        return Ed25519PublicKey.fromBytes(
            pubKeyInfo.getPublicKeyData()
                .getBytes());
    } else {
        throw new IllegalArgumentException("Unsupported public key type: " + algId.toString());
    }
}
 
Example 11
Source File: CryptOperation.java    From cstc with GNU General Public License v3.0 5 votes vote down vote up
protected byte[] crypt(byte[] input, int cipherMode, String algorithm, String mode, String padding)
		throws Exception {
	byte[] key = keyTxt.getText();
	byte[] iv = ivTxt.getText();

	SecretKeySpec secretKeySpec = new SecretKeySpec(key, algorithm);
	IvParameterSpec ivSpec = new IvParameterSpec(iv);
	Cipher cipher = Cipher.getInstance(String.format("%s/%s/%s", algorithm, mode, padding));

       if( mode.equals("ECB") ) {
           cipher.init(cipherMode, secretKeySpec);
       } else {
           cipher.init(cipherMode, secretKeySpec, ivSpec);
       }

       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 File: CryptoTest.java    From webauthndemo with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetRSAPublicKey() {
  byte[] n = Hex.decode("A9E167983F39D55FF2A093415EA6798985C8355D9A915BFB1D01DA197026170FBDA522D035856D7A986614415CCFB7B7083B09C991B81969376DF9651E7BD9A93324A37F3BBBAF460186363432CB07035952FC858B3104B8CC18081448E64F1CFB5D60C4E05C1F53D37F53D86901F105F87A70D1BE83C65F38CF1C2CAA6AA7EB");
  byte[] e = Hex.decode("010001");
  Algorithm alg = Algorithm.RS256;
  RsaKey rsaPublicKey = new RsaKey(alg, n, e);
  try {
    Crypto.getRSAPublicKey(rsaPublicKey);
  } catch (WebAuthnException ex) {
    fail("WebAuthnException: " + ex.getMessage());
  }
}
 
Example 13
Source File: CmsCryptoDES.java    From oneops with Apache License 2.0 5 votes vote down vote up
private KeyParameter getSecretKeyFromFile() throws IOException, GeneralSecurityException {
    BufferedInputStream keystream =
            new BufferedInputStream(new FileInputStream(secretKeyFile));
    int len = keystream.available();
    if (len < MIN_DES_FILE_LENGTH) {
        keystream.close();
        throw new EOFException(">>>> Bad DES file length = " + len);
    }
    byte[] keyhex = new byte[len];
    keystream.read(keyhex, 0, len);
    keystream.close();
    return new KeyParameter(Hex.decode(keyhex));
}
 
Example 14
Source File: TransactionBroadcast.java    From burstkit4j with Apache License 2.0 4 votes vote down vote up
public TransactionBroadcast(BroadcastTransactionResponse response) {
    this.fullHash = Hex.decode(response.getFullHash());
    this.transactionId = BurstID.fromLong(response.getTransactionID());
    this.numberPeersSentTo = response.getNumberPeersSentTo();
}
 
Example 15
Source File: EncryptedMessageResponse.java    From burstkit4j with Apache License 2.0 4 votes vote down vote up
public BurstEncryptedMessage toEncryptedMessage() {
    return new BurstEncryptedMessage(Hex.decode(data), Hex.decode(nonce), isText);
}
 
Example 16
Source File: ATCreationAttachmentResponse.java    From burstkit4j with Apache License 2.0 4 votes vote down vote up
@Override
public TransactionAttachment toAttachment() {
    return new ATCreationAttachment(version, name, description, Hex.decode(creationBytes));
}
 
Example 17
Source File: ByteArray.java    From jlibra with Apache License 2.0 4 votes vote down vote up
public static ByteArray from(String hexValue) {
    return new ByteArray(Hex.decode(hexValue));
}
 
Example 18
Source File: NodeIdTool.java    From client-sdk-java with Apache License 2.0 4 votes vote down vote up
static byte[] decodeHash(String hex) {
    return Hex.decode(Numeric.cleanHexPrefix(hex));
}
 
Example 19
Source File: MnemonicUtilsTest.java    From client-sdk-java with Apache License 2.0 4 votes vote down vote up
public MnemonicUtilsTest(String initialEntropy, String mnemonic, String seed) {
    this.initialEntropy = Hex.decode(initialEntropy);
    this.mnemonic = mnemonic;
    this.seed = Hex.decode(seed);
}
 
Example 20
Source File: Ed25519PrivateKey.java    From hedera-sdk-java with Apache License 2.0 2 votes vote down vote up
/**
 * Recover a private key from its text-encoded representation.
 *
 * @param privateKeyString the hex-encoded private key string
 * @return the restored private key
 * @throws org.bouncycastle.util.encoders.DecoderException if the hex string is invalid
 * @throws RuntimeException                                if the decoded key was invalid
 */
public static Ed25519PrivateKey fromString(String privateKeyString) {
    // TODO: catch unchecked `DecoderException`
    byte[] keyBytes = Hex.decode(privateKeyString);
    return fromBytes(keyBytes);
}