Java Code Examples for javax.xml.bind.DatatypeConverter#parseHexBinary()

The following examples show how to use javax.xml.bind.DatatypeConverter#parseHexBinary() . 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: SamlHelper.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
public String getArtifactUrl(String realmId, String artifact) {
    byte[] sourceId =  retrieveSourceId(artifact);
    Entity realm = realmHelper.findRealmById(realmId);

    if (realm == null) {
        LOG.error("Invalid realm: " + realmId);
        throw new APIAccessDeniedException("Authorization could not be verified.");
    }

    Map<String, Object> idp = (Map<String, Object>) realm.getBody().get("idp");
    String realmSourceId = (String) idp.get("sourceId");
    if (realmSourceId == null || realmSourceId.isEmpty()) {
        LOG.error("SourceId is not configured properly for realm: " + realmId);
        throw new APIAccessDeniedException("Authorization could not be verified.");
    }

    byte[] realmByteSourceId = DatatypeConverter.parseHexBinary(realmSourceId);
    if (!Arrays.equals(realmByteSourceId, sourceId)) {
        LOG.error("SourceId from Artifact does not match configured SourceId for realm: " + realmId);
        throw new APIAccessDeniedException("Authorization could not be verified.");
    }

    return (String) idp.get("artifactResolutionEndpoint");
}
 
Example 2
Source File: PublishKafka_0_10.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private byte[] getMessageKey(final FlowFile flowFile, final ProcessContext context) {
    if (context.getProperty(MESSAGE_DEMARCATOR).isSet()) {
        return null;
    }

    final String uninterpretedKey;
    if (context.getProperty(KEY).isSet()) {
        uninterpretedKey = context.getProperty(KEY).evaluateAttributeExpressions(flowFile).getValue();
    } else {
        uninterpretedKey = flowFile.getAttribute(KafkaProcessorUtils.KAFKA_KEY);
    }

    if (uninterpretedKey == null) {
        return null;
    }

    final String keyEncoding = context.getProperty(KEY_ATTRIBUTE_ENCODING).getValue();
    if (UTF8_ENCODING.getValue().equals(keyEncoding)) {
        return uninterpretedKey.getBytes(StandardCharsets.UTF_8);
    }

    return DatatypeConverter.parseHexBinary(uninterpretedKey);
}
 
Example 3
Source File: TestLumberjackDecoder.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecodeMultipleFrame() {
    final byte[] input = DatatypeConverter.parseHexBinary(multiFrameData);

    List<LumberjackFrame> frames = null;
    LumberjackFrame frame = null;

    for (byte b : input) {
        if (decoder.process(b)) {
            frames = decoder.getFrames();
            break;
        }
    }

    frame = frames.get(1);

    Assert.assertNotNull(frame);
    Assert.assertEquals(0x31, frame.getVersion());
    Assert.assertEquals(0x44, frame.getFrameType());
    // Load the second frame therefore seqNumber = 2
    Assert.assertEquals(2, frame.getSeqNumber());
    // Look for a predefined number of bytes for matching of the inner payload
    Assert.assertArrayEquals(DatatypeConverter.parseHexBinary("000000050000000466696c65000000"), Arrays.copyOfRange(frame.getPayload(), 0, 15));
}
 
Example 4
Source File: TestLumberjackDecoder.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecodeSingleFrame() {
    final byte[] input = DatatypeConverter.parseHexBinary(singleFrameData);

    List<LumberjackFrame> frames = null;
    LumberjackFrame frame = null;

    for (byte b : input) {
        if (decoder.process(b)) {
            frames = decoder.getFrames();
            break;
        }
    }

    frame = frames.get(frames.size() - 1);

    Assert.assertNotNull(frame);
    Assert.assertEquals(0x31, frame.getVersion());
    Assert.assertEquals(0x44, frame.getFrameType());
    Assert.assertEquals(1, frame.getSeqNumber());
    // Look for a predefined number of bytes for matching of the inner payload
    Assert.assertArrayEquals(DatatypeConverter.parseHexBinary("000000050000000466696c65000000"), Arrays.copyOfRange(frame.getPayload(), 0, 15));
}
 
Example 5
Source File: CryptoPrimitivesTest.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {
    config = Config.getConfig();

    plainText = DatatypeConverter.parseHexBinary(PLAIN_TEXT_HEX);
    sig = DatatypeConverter.parseHexBinary(SIGNATURE_HEX);
    pemCert = DatatypeConverter.parseHexBinary(PEM_CERT_HEX);
    invalidPemCert = DatatypeConverter.parseHexBinary(INVALID_PEM_CERT);

    kf = KeyFactory.getInstance("EC");

    cf = CertificateFactory.getInstance("X.509");

    crypto = new CryptoPrimitives();
    crypto.init();

}
 
Example 6
Source File: RFXComRainMessageTest.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testSomeMessages() throws RFXComException {
    String hexMessage = "0B550217B6000000004D3C69";
    byte[] message = DatatypeConverter.parseHexBinary(hexMessage);
    RFXComRainMessage msg = (RFXComRainMessage) RFXComMessageFactory.getMessageInterface(message);
    assertEquals("SubType", PCR800, msg.subType);
    assertEquals("Seq Number", 23, msg.seqNbr);
    assertEquals("Sensor Id", "46592", msg.generateDeviceId());
    assertEquals("Rain rate", 0.0, msg.rainRate, 0.001);
    assertEquals("Total rain", 1977.2, msg.rainTotal, 0.001);
    assertEquals("Signal Level", 6, msg.signalLevel);
    assertEquals("Battery Level", 9, msg.batteryLevel);

    byte[] decoded = msg.decodeMessage();

    assertEquals("Message converted back", hexMessage, DatatypeConverter.printHexBinary(decoded));
}
 
Example 7
Source File: TestLumberjackDecoder.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecodeMultipleFrame() {
    final byte[] input = DatatypeConverter.parseHexBinary(multiFrameData);

    List<LumberjackFrame> frames = null;
    LumberjackFrame frame = null;

    for (byte b : input) {
        if (decoder.process(b)) {
            frames = decoder.getFrames();
            break;
        }
    }

    frame = frames.get(1);

    Assert.assertNotNull(frame);
    Assert.assertEquals(0x31, frame.getVersion());
    Assert.assertEquals(0x44, frame.getFrameType());
    // Load the second frame therefore seqNumber = 2
    Assert.assertEquals(2, frame.getSeqNumber());
    // Look for a predefined number of bytes for matching of the inner payload
    Assert.assertArrayEquals(DatatypeConverter.parseHexBinary("000000050000000466696c65000000"), Arrays.copyOfRange(frame.getPayload(), 0, 15));
}
 
Example 8
Source File: LDAPServer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void addToCache(String hexString) throws IOException {
    byte[] encoding = DatatypeConverter.parseHexBinary(hexString);
    int[] ids = getIDs(encoding);
    int messageID = ids[0];
    List<byte[]> encodings = cache.get(messageID);
    if (encodings == null) {
        encodings = new ArrayList<>();
    }
    System.out.println("    adding LDAP " + getOperation(ids[1]) +
        " with message ID " + messageID + " to the cache");
    encodings.add(encoding);
    cache.put(messageID, encodings);
}
 
Example 9
Source File: CipherStreamClose.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    MessageDigest digest = MessageDigest.getInstance("SHA1");
    SecretKeySpec key = new SecretKeySpec(
        DatatypeConverter.parseHexBinary(
        "12345678123456781234567812345678"), "AES");

    // Run 'message' through streamEncrypt
    byte[] se = streamEncrypt(message, key, digest);
    // 'digest' already has the value from the stream, just finish the op
    byte[] sd = digest.digest();
    digest.reset();
    // Run 'message' through blockEncrypt
    byte[] be = blockEncrypt(message, key);
    // Take digest of encrypted blockEncrypt result
    byte[] bd = digest.digest(be);
    // Verify both returned the same value
    if (!Arrays.equals(sd, bd)) {
        System.err.println("Stream: "+DatatypeConverter.printHexBinary(se)+
            "\t Digest: "+DatatypeConverter.printHexBinary(sd));
        System.err.println("Block : "+DatatypeConverter.printHexBinary(be)+
            "\t Digest: "+DatatypeConverter.printHexBinary(bd));
        throw new Exception("stream & block encryption does not match");
    }

    digest.reset();
    // Sanity check: Decrypt separately from stream to verify operations
    String bm = (String) blockDecrypt(be, key);
    if (message.compareTo(bm) != 0) {
        System.err.println("Expected: "+message+"\nBlock:    "+bm);
        throw new Exception("Block decryption does not match expected");
    }

    // Have decryption and digest included in the object stream
    String sm = (String) streamDecrypt(se, key, digest);
    if (message.compareTo(sm) != 0) {
        System.err.println("Expected: "+message+"\nStream:   "+sm);
        throw new Exception("Stream decryption does not match expected.");
    }
}
 
Example 10
Source File: GcmCipherTest.java    From commons-crypto with Apache License 2.0 5 votes vote down vote up
private void testGcmReturnDataAfterTagVerified(final String kHex, final String pHex, final String ivHex, final String aadHex,
                                               final String cHex, final String tHex) throws Exception {

    final byte[] keyBytes = DatatypeConverter.parseHexBinary(kHex);
    final byte[] plainBytes = DatatypeConverter.parseHexBinary(pHex);
    final byte[] ivBytes = DatatypeConverter.parseHexBinary(ivHex);

    final byte[] aad = DatatypeConverter.parseHexBinary(aadHex);
    final byte[] cipherBytes = DatatypeConverter.parseHexBinary(cHex+tHex);

    final byte[] input = cipherBytes;
    final byte[] output = new byte[plainBytes.length];

    final CryptoCipher c = Utils.getCipherInstance(transformation, props);

    final Key key = new SecretKeySpec(keyBytes, "AES");

    final GCMParameterSpec iv = new GCMParameterSpec(128, ivBytes);
    c.init(Cipher.DECRYPT_MODE, key, iv);
    c.updateAAD(aad);

    //only return recovered data after tag is successfully verified
    int len = c.update(input, 0, input.length, output, 0);
    Assert.assertTrue(len == 0);
    len += c.doFinal(input, input.length, 0, output, 0);
    Assert.assertTrue(len == plainBytes.length);

    Assert.assertArrayEquals(plainBytes, output);
    c.close();
}
 
Example 11
Source File: Message.java    From anki-drive-java with MIT License 5 votes vote down vote up
public static Message parse(String hexMessage) {
  byte[] data = DatatypeConverter.parseHexBinary(hexMessage);
  ByteBuffer buffer = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);

  int size = Byte.toUnsignedInt(buffer.get());
  int type = Byte.toUnsignedInt(buffer.get());

  Message m = Message.createByType(type);

  m.payload = new byte[buffer.remaining()];
  buffer.get(m.payload).position(2);
  m.parsePayload(buffer);

  return m;
}
 
Example 12
Source File: UPBMessage.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Converts a hex string into a {@link UPBMessage}.
 * 
 * @param commandString
 *            the string as returned by the modem.
 * @return a new UPBMessage.
 */
public static UPBMessage fromString(String commandString) {
    UPBMessage command = new UPBMessage();

    String typeString = commandString.substring(0, 2);
    Type type = Type.NONE;

    if (typeMap.containsKey(typeString)) {
        type = typeMap.get(typeString);
    }

    command.setType(type);

    try {
        if (commandString.length() > 2) {
            byte[] data = DatatypeConverter.parseHexBinary(commandString.substring(2));
            command.getControlWord().setBytes(data[1], data[0]);
            int index = 2;
            command.setNetwork(data[index++]);
            command.setDestination(data[index++]);
            command.setSource(data[index++]);

            int commandCode = data[index++] & 0xFF;

            if (commandMap.containsKey(commandCode)) {
                command.setCommand(commandMap.get(commandCode));
            } else {
                command.setCommand(Command.NONE);
            }

            if (index < data.length - 1) {
                command.setArguments(Arrays.copyOfRange(data, index, data.length - 1));
            }
        }
    } catch (Exception e) {
        logger.error("Attempted to parse invalid message: {}", commandString, e);
    }

    return command;
}
 
Example 13
Source File: PasswordPBKDF2.java    From mini-platform with MIT License 5 votes vote down vote up
/**
 * PBKDF2
 * @param password
 * @param salt
 * @return
 */
private String getPbkdf2(String password, String salt) {
    try {
        byte[] bytes = DatatypeConverter.parseHexBinary(salt);
        KeySpec spec = new PBEKeySpec(password.toCharArray(), bytes, iterationCount, keyLength);
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
        byte[] hash = secretKeyFactory.generateSecret(spec).getEncoded();
        return DatatypeConverter.printHexBinary(hash);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        return "";
    }
}
 
Example 14
Source File: LDAPPasswordPropagationActions.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Transactional(readOnly = true)
@Override
public void before(final PropagationTask task, final ConnectorObject beforeObj) {
    if (AnyTypeKind.USER == task.getAnyTypeKind()) {
        User user = userDAO.find(task.getEntityKey());

        if (user != null && user.getPassword() != null) {
            Attribute missing = AttributeUtil.find(
                    PropagationTaskExecutor.MANDATORY_MISSING_ATTR_NAME,
                    task.getAttributes());

            ConnInstance connInstance = task.getResource().getConnector();
            String cipherAlgorithm = getCipherAlgorithm(connInstance);
            if (missing != null && missing.getValue() != null && missing.getValue().size() == 1
                    && missing.getValue().get(0).equals(OperationalAttributes.PASSWORD_NAME)
                    && cipherAlgorithmMatches(getCipherAlgorithm(connInstance), user.getCipherAlgorithm())) {

                String password = user.getPassword().toLowerCase();
                byte[] decodedPassword = DatatypeConverter.parseHexBinary(password);
                String base64EncodedPassword = Base64.getEncoder().encodeToString(decodedPassword);

                String cipherPlusPassword = ('{' + cipherAlgorithm.toLowerCase() + '}' + base64EncodedPassword);

                Attribute passwordAttribute = AttributeBuilder.buildPassword(
                        new GuardedString(cipherPlusPassword.toCharArray()));

                Set<Attribute> attributes = new HashSet<>(task.getAttributes());
                attributes.add(passwordAttribute);
                attributes.remove(missing);

                task.setAttributes(attributes);
            }
        }
    }
}
 
Example 15
Source File: JobID.java    From stratosphere with Apache License 2.0 4 votes vote down vote up
public static JobID fromHexString(String hexString) {
	return new JobID(DatatypeConverter.parseHexBinary(hexString));
}
 
Example 16
Source File: AesEncryptionStrategy.java    From java with Apache License 2.0 4 votes vote down vote up
private SecretKey createSecretKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(getPassphrase().toCharArray(), DatatypeConverter.parseHexBinary(salt), iterationCount, keySize);
    return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
}
 
Example 17
Source File: AbstractSpannerExpressionVisitorAdapter.java    From spanner-jdbc with MIT License 4 votes vote down vote up
@Override
public void visit(HexValue value) {
  String stringValue = value.getValue().substring(2);
  byte[] byteValue = DatatypeConverter.parseHexBinary(stringValue);
  setValue(byteValue, Types.BINARY);
}
 
Example 18
Source File: Sha1Checksum.java    From desktop with GNU General Public License v3.0 4 votes vote down vote up
private static byte[] toByteArray(String s) {
    return DatatypeConverter.parseHexBinary(s);
}
 
Example 19
Source File: HexBinaryAdapter.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public byte[] unmarshal(String s) {
    if(s==null)     return null;
    return DatatypeConverter.parseHexBinary(s);
}
 
Example 20
Source File: Codec.java    From java-tool with Apache License 2.0 2 votes vote down vote up
/**
 * Transform an hexadecimal String to a byte array.
 * @param hexString the string
 * @return the byte array of the hex string
 */
public static byte[] hexStringToByte(String hexString) {
    return DatatypeConverter.parseHexBinary(hexString);
}