Java Code Examples for javax.xml.bind.DatatypeConverter

The following are top voted examples for showing how to use javax.xml.bind.DatatypeConverter. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: SistemaAlmoxarifado   File: Token.java   Source Code and License 9 votes vote down vote up
public static boolean Verify(String jwt, String type) throws Exception {
    
    try{
        Claims claims = Jwts.parser()
            .setSigningKey(DatatypeConverter.parseBase64Binary(Parameters.TOKENKEY))
            .parseClaimsJws(jwt).getBody();
        
        //verifica se o issuer é igual ao type
        return claims.getIssuer().equals(type);
        
    } catch (ExpiredJwtException | MalformedJwtException | SignatureException 
            | UnsupportedJwtException | IllegalArgumentException e) {
        System.out.println(e.getMessage());
        return false;
    }
}
 
Example 2
Project: SistemaAlmoxarifado   File: Token.java   Source Code and License 8 votes vote down vote up
public static String Gerate(String issuer, int idSubject, int hours) {

        //The JWT signature algorithm we will be using to sign the token
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        
        //Hours to milliseconds
        long ttlMillis = hours * 3600000;
        String subject = String.valueOf(idSubject);
        
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        
        //We will sign our JWT with our ApiKey secret
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(Parameters.TOKENKEY);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //Let's set the JWT Claims
        JwtBuilder builder = Jwts.builder().setIssuedAt(now)
                                    .setSubject(subject)
                                    .setIssuer(issuer)
                                    .signWith(signatureAlgorithm, signingKey);

        //if it has been specified, let's add the expiration
        if (ttlMillis >= 0) {
        long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }

        //Builds the JWT and serializes it to a compact, URL-safe string
        return builder.compact();
    }
 
Example 3
Project: daf-replicate-ingestion   File: AvroDeserializer.java   Source Code and License 7 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public T deserialize(String topic, byte[] data) {
	try {
		T result = null;

		if (data != null) {
			LOGGER.debug("data='{}'", DatatypeConverter.printHexBinary(data));

			DatumReader<GenericRecord> datumReader = new SpecificDatumReader<>(
					targetType.newInstance().getSchema());
			Decoder decoder = DecoderFactory.get().binaryDecoder(data, null);

			result = (T) datumReader.read(null, decoder);
			LOGGER.debug("deserialized data='{}'", result);
		}
		return result;
	} catch (Exception ex) {
		throw new SerializationException(
				"Can't deserialize data '" + Arrays.toString(data) + "' from topic '" + topic + "'", ex);
	}
}
 
Example 4
Project: jdk8u-jdk   File: CipherStreamClose.java   Source Code and License 6 votes vote down vote up
public static byte[] streamEncrypt(String message, SecretKey key,
    MessageDigest digest)
    throws Exception {

    byte[] data;
    Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DigestOutputStream dos = new DigestOutputStream(bos, digest);
        CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
        try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            oos.writeObject(message);
        }
        data = bos.toByteArray();
    }

    if (debug) {
        System.out.println(DatatypeConverter.printHexBinary(data));
    }
    return data;
}
 
Example 5
Project: xrd4j   File: MessageHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Encodes the given image InputStream to a base64 coded string.
 *
 * @param is image InputStream to encode
 * @param type type of the image: jpeg, bmp, png, gif etc.
 * @return encoded string
 */
public static String encodeImg2String(InputStream is, String type) {
    String imageString = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        BufferedImage image = ImageIO.read(is);
        ImageIO.write(image, type, bos);
        byte[] imageBytes = bos.toByteArray();
        imageString = DatatypeConverter.printBase64Binary(imageBytes);
        bos.close();
    } catch (IOException ex) {
        LOGGER.error(ex.getMessage(), ex);
    }
    return imageString;
}
 
Example 6
Project: dss-demonstrations   File: SignatureMultipleDocumentsController.java   Source Code and License 6 votes vote down vote up
@RequestMapping(value = "/get-data-to-sign", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public GetDataToSignResponse getDataToSign(Model model, @RequestBody @Valid DataToSignParams params,
		@ModelAttribute("signatureMultipleDocumentsForm") @Valid SignatureMultipleDocumentsForm signatureMultipleDocumentsForm, BindingResult result) {
	signatureMultipleDocumentsForm.setBase64Certificate(params.getSigningCertificate());
	signatureMultipleDocumentsForm.setBase64CertificateChain(params.getCertificateChain());
	signatureMultipleDocumentsForm.setEncryptionAlgorithm(params.getEncryptionAlgorithm());
	signatureMultipleDocumentsForm.setSigningDate(new Date());
	model.addAttribute("signatureMultipleDocumentsForm", signatureMultipleDocumentsForm);

	ToBeSigned dataToSign = signingService.getDataToSign(signatureMultipleDocumentsForm);
	if (dataToSign == null) {
		return null;
	}

	GetDataToSignResponse responseJson = new GetDataToSignResponse();
	responseJson.setDataToSign(DatatypeConverter.printBase64Binary(dataToSign.getBytes()));
	return responseJson;
}
 
Example 7
Project: dss-demonstrations   File: SigningService.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public DSSDocument signDocument(SignatureDocumentForm form) {
	logger.info("Start signDocument with one document");
	DocumentSignatureService service = getSignatureService(form.getContainerType(), form.getSignatureForm());

	AbstractSignatureParameters parameters = fillParameters(form);

	DSSDocument signedDocument = null;
	try {
		DSSDocument toSignDocument = WebAppUtils.toDSSDocument(form.getDocumentToSign());
		SignatureAlgorithm sigAlgorithm = SignatureAlgorithm.getAlgorithm(form.getEncryptionAlgorithm(), form.getDigestAlgorithm());
		SignatureValue signatureValue = new SignatureValue(sigAlgorithm, DatatypeConverter.parseBase64Binary(form.getBase64SignatureValue()));
		signedDocument = service.signDocument(toSignDocument, parameters, signatureValue);
	} catch (Exception e) {
		logger.error("Unable to execute signDocument : " + e.getMessage(), e);
	}
	logger.info("End signDocument with one document");
	return signedDocument;
}
 
Example 8
Project: dss-demonstrations   File: SigningService.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public DSSDocument signDocument(SignatureMultipleDocumentsForm form) {
	logger.info("Start signDocument with multiple documents");
	MultipleDocumentsSignatureService service = getASiCSignatureService(form.getSignatureForm());

	AbstractSignatureParameters parameters = fillParameters(form);

	DSSDocument signedDocument = null;
	try {
		List<DSSDocument> toSignDocuments = WebAppUtils.toDSSDocuments(form.getDocumentsToSign());
		SignatureAlgorithm sigAlgorithm = SignatureAlgorithm.getAlgorithm(form.getEncryptionAlgorithm(), form.getDigestAlgorithm());
		SignatureValue signatureValue = new SignatureValue(sigAlgorithm, DatatypeConverter.parseBase64Binary(form.getBase64SignatureValue()));
		signedDocument = service.signDocument(toSignDocuments, parameters, signatureValue);
	} catch (Exception e) {
		logger.error("Unable to execute signDocument : " + e.getMessage(), e);
	}
	logger.info("End signDocument with multiple documents");
	return signedDocument;
}
 
Example 9
Project: kafka-0.11.0.0-src-with-comment   File: ScramMessages.java   Source Code and License 6 votes vote down vote up
public ServerFinalMessage(byte[] messageBytes) throws SaslException {
    String message = toMessage(messageBytes);
    Matcher matcher = PATTERN.matcher(message);
    if (!matcher.matches())
        throw new SaslException("Invalid SCRAM server final message format: " + message);
    String error = null;
    try {
        error = matcher.group("error");
    } catch (IllegalArgumentException e) {
        // ignore
    }
    if (error == null) {
        this.serverSignature = DatatypeConverter.parseBase64Binary(matcher.group("signature"));
        this.error = null;
    } else {
        this.serverSignature = null;
        this.error = error;
    }
}
 
Example 10
Project: komodoGUI   File: ProvingKeyFetcher.java   Source Code and License 6 votes vote down vote up
private static boolean checkSHA256(File provingKey, Component parent) throws IOException {
    MessageDigest sha256;
    try {
        sha256 = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException impossible) {
        throw new RuntimeException(impossible);
    }
    try (InputStream is = new BufferedInputStream(new FileInputStream(provingKey))) {
        ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(parent,"Verifying proving key",is);
        pmis.getProgressMonitor().setMaximum(PROVING_KEY_SIZE);
        pmis.getProgressMonitor().setMillisToPopup(10);
        DigestInputStream dis = new DigestInputStream(pmis, sha256);
        byte [] temp = new byte[0x1 << 13];
        while(dis.read(temp) >= 0);
        byte [] digest = sha256.digest();
        return SHA256.equalsIgnoreCase(DatatypeConverter.printHexBinary(digest));
    }
}
 
Example 11
Project: emr-nlp-server   File: AuthFilter.java   Source Code and License 6 votes vote down vote up
public static String[] decode(String auth) {
    //Replacing "Basic THE_BASE_64" to "THE_BASE_64" directly
    auth = auth.replaceFirst("[B|b]asic ", "");
 
    //Decode the Base64 into byte[]
    byte[] decodedBytes = DatatypeConverter.parseBase64Binary(auth);
 
    //If the decode fails in any case
    if(decodedBytes == null || decodedBytes.length == 0){
        return null;
    }
 
    //Now split the byte[] into an array :
    //  - the first one is login,
    //  - the second one password
    return new String(decodedBytes).split(":", 2);
}
 
Example 12
Project: IO   File: CompressionTask.java   Source Code and License 6 votes vote down vote up
/**
   * Testing method for decompression of ewf file hex bytes
   * @param ewfHexStr any zlib compressed hex
   * @return decompressed string
   */
  protected static String decompress(String ewfHexStr) {
Inflater inflater = new Inflater();
byte[] input = DatatypeConverter.parseHexBinary(ewfHexStr);
inflater.setInput(input, 0, input.length);
String outputString = "empty";

byte[] result = new byte[input.length];
int resultLength;
try {
	resultLength = inflater.inflate(result);
	outputString = new String(result, 0, resultLength, "UTF-8");
} catch (DataFormatException | UnsupportedEncodingException e) {
	e.printStackTrace();
}
inflater.end();

return outputString;
  }
 
Example 13
Project: openjdk-jdk10   File: CipherStreamClose.java   Source Code and License 6 votes vote down vote up
public static byte[] streamEncrypt(String message, SecretKey key,
    MessageDigest digest)
    throws Exception {

    byte[] data;
    Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DigestOutputStream dos = new DigestOutputStream(bos, digest);
        CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
        try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            oos.writeObject(message);
        }
        data = bos.toByteArray();
    }

    if (debug) {
        System.out.println(DatatypeConverter.printHexBinary(data));
    }
    return data;
}
 
Example 14
Project: oscm   File: AssertionContentVerifier.java   Source Code and License 6 votes vote down vote up
/**
 * Verify that the NotOnOrAfter attribute in any bearer
 * <SubjectConfirmationData> has not passed, subject to allowable clock skew
 * between the providers
 * 
 * @throws AssertionValidationException
 */
void verifyAssertionExpirationDate(Node nodeAssertion,
        Node nodeConfirmationData) throws AssertionValidationException {

    Calendar expirationDate = DatatypeConverter.parseDateTime(XMLConverter
            .getStringAttValue(nodeConfirmationData,
                    SamlXmlTags.ATTRIBUTE_NOT_ON_OR_AFTER));
    if (now.equals(expirationDate) || now.after(expirationDate)) {
        String assertionId = XMLConverter.getStringAttValue(nodeAssertion,
                SamlXmlTags.ATTRIBUTE_ID);
        AssertionValidationException exception = new AssertionValidationException(
                String.format("Assertion (id=%s) expired", assertionId),
                AssertionValidationException.ReasonEnum.ASSERTION_EXPIRED,
                new String[] { assertionId });
        throw exception;
    }
}
 
Example 15
Project: Richkware-Manager-Client   File: Crypto.java   Source Code and License 6 votes vote down vote up
public static String EncryptAES(String input, SecretKey key) throws CryptoException {
    // encode input
    input = DatatypeConverter.printBase64Binary(input.getBytes());

    byte[] ciphertext = null;
    try {
        ciphertext = AES.encrypt(input.getBytes(), key);
    } catch (Exception e) {
        throw new CryptoException(e);
    }


    // encode encrypted input
    //return DatatypeConverter.printBase64Binary(ciphertext.getBytes());
    return DatatypeConverter.printHexBinary(ciphertext);
}
 
Example 16
Project: storm-dynamic-spout   File: ZookeeperWatchTrigger.java   Source Code and License 6 votes vote down vote up
/**
 * Using a filter chain step, make some JSON out of it and then hash it to create an idempotent identifier.
 * @param triggerEvent Trigger event that contains metadata about the request
 * @param step The FilterChainStep that we are going to generate the request from
 * @return A sideline request identifier for the filter chain step
 * @throws NoSuchAlgorithmException Your java install is whack yo, it's missing MD5, for realz???
 */
private SidelineRequestIdentifier generateSidelineRequestIdentifier(
    final TriggerEvent triggerEvent,
    final FilterChainStep step
) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    final String json = gson.toJson(step);

    final StringBuilder identifier = new StringBuilder(
        DatatypeConverter.printHexBinary(MessageDigest.getInstance("MD5").digest(json.getBytes("UTF-8")))
    );

    // If we were provided a date time in the event, append the time stamp of that event to the identifier
    if (triggerEvent.getCreatedAt() != null) {
        identifier.append("-");
        identifier.append(
            triggerEvent.getCreatedAt().atZone(ZoneOffset.UTC).toInstant().toEpochMilli()
        );
    }

    return new SidelineRequestIdentifier(identifier.toString());
}
 
Example 17
Project: osc-core   File: BackupFileServiceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testExec_withValidKeyStoreProperties_ProperlyEncodesBackup() throws Exception {
	// Arrange.
	TestBackupFileServiceRequest testRequest = new TestBackupFileServiceRequest();

       SecretKey secretKey = generateTestSecretKey();
       KeyStoreProvider.getInstance().putSecretKey(BACKUP_KEY_ALIAS, secretKey, BACKUP_KEY_PASSWORD);
       String ivHex = generateTestIVHex();
       KeyStoreProvider.getInstance().putPassword(BACKUP_IV_ALIAS, ivHex, BACKUP_IV_PASSWORD);

	// Act.
	TestBackupFileServiceResponse response = this.target.exec(testRequest, this.em);

	// Assert.
	assertEquals(secretKey, response.key);
	assertEquals(ivHex, DatatypeConverter.printHexBinary(response.iv));
}
 
Example 18
Project: phone-simulator   File: DiameterIdentityImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void read(javolution.xml.XMLFormat.InputElement xml, DiameterIdentityImpl diameterIdentity)
        throws XMLStreamException {
    String s = xml.getAttribute(DATA, DEFAULT_VALUE);
    if (s != null) {
        diameterIdentity.data = DatatypeConverter.parseHexBinary(s);
    }
}
 
Example 19
Project: phone-simulator   File: DiameterIdentityImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void write(DiameterIdentityImpl diameterIdentity, javolution.xml.XMLFormat.OutputElement xml)
        throws XMLStreamException {
    if (diameterIdentity.data != null) {
        xml.setAttribute(DATA, DatatypeConverter.printHexBinary(diameterIdentity.data));
    }
}
 
Example 20
Project: openjdk-jdk10   File: HttpTransportPipe.java   Source Code and License 5 votes vote down vote up
private void addBasicAuth(Packet context, Map<String, List<String>> reqHeaders) {
    String user = (String) context.invocationProperties.get(BindingProvider.USERNAME_PROPERTY);
    if (user != null) {
        String pw = (String) context.invocationProperties.get(BindingProvider.PASSWORD_PROPERTY);
        if (pw != null) {
            StringBuilder buf = new StringBuilder(user);
            buf.append(":");
            buf.append(pw);
            String creds = DatatypeConverter.printBase64Binary(buf.toString().getBytes());
            reqHeaders.put("Authorization", Collections.singletonList("Basic "+creds));
        }
    }
}
 
Example 21
Project: phone-simulator   File: TAIdImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void read(javolution.xml.XMLFormat.InputElement xml, TAIdImpl taId) throws XMLStreamException {
    String s = xml.getAttribute(DATA, DEFAULT_VALUE);
    if (s != null) {
        taId.data = DatatypeConverter.parseHexBinary(s);
    }
}
 
Example 22
Project: mybatis-generator-plugin   File: TemplateCommentGenerator.java   Source Code and License 5 votes vote down vote up
private String getGeneratedAnnotation(String comment) {
    StringBuilder buffer = new StringBuilder();
    buffer.append("@Generated("); //$NON-NLS-1$
    if (suppressAllComments) {
        buffer.append('\"');
    } else {
        buffer.append("value=\""); //$NON-NLS-1$
    }

    buffer.append(MyBatisGenerator.class.getName());
    buffer.append('\"');

    if (!suppressDate && !suppressAllComments) {
        buffer.append(", date=\""); //$NON-NLS-1$
        buffer.append(DatatypeConverter.printDateTime(Calendar.getInstance()));
        buffer.append('\"');
    }

    if (!suppressAllComments) {
        buffer.append(", comments=\""); //$NON-NLS-1$
        buffer.append(comment);
        buffer.append('\"');
    }

    buffer.append(')');
    return buffer.toString();
}
 
Example 23
Project: athena   File: IsisUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Converts a number to four bytes.
 *
 * @param numberToConvert number to convert
 * @return numInBytes given number as bytes
 */
public static byte[] convertToFourBytes(int numberToConvert) {
    byte[] numInBytes = new byte[4];
    String s1 = Integer.toHexString(numberToConvert);
    if (s1.length() % 2 != 0) {
        s1 = "0" + s1;
    }
    byte[] hexas = DatatypeConverter.parseHexBinary(s1);
    if (hexas.length == 1) {
        numInBytes[0] = 0;
        numInBytes[1] = 0;
        numInBytes[2] = 0;
        numInBytes[3] = hexas[0];
    } else if (hexas.length == 2) {
        numInBytes[0] = 0;
        numInBytes[1] = 0;
        numInBytes[2] = hexas[0];
        numInBytes[3] = hexas[1];
    } else if (hexas.length == 3) {
        numInBytes[0] = 0;
        numInBytes[1] = hexas[0];
        numInBytes[2] = hexas[1];
        numInBytes[3] = hexas[2];
    } else {
        numInBytes[0] = hexas[0];
        numInBytes[1] = hexas[1];
        numInBytes[2] = hexas[2];
        numInBytes[3] = hexas[3];
    }
    return numInBytes;
}
 
Example 24
Project: Richkware-Manager-Client   File: RSA.java   Source Code and License 5 votes vote down vote up
public static String sign(byte[] plainText, PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    Signature privateSignature = Signature.getInstance(signVerifyAlgorithm);
    privateSignature.initSign(privateKey);
    privateSignature.update(plainText);

    return DatatypeConverter.printBase64Binary(privateSignature.sign());
}
 
Example 25
Project: phone-simulator   File: CUGInterlockImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void read(javolution.xml.XMLFormat.InputElement xml, CUGInterlockImpl cugInterlock) throws XMLStreamException {
    String s = xml.getAttribute(DATA, DEFAULT_VALUE);
    if (s != null) {
        cugInterlock.data = DatatypeConverter.parseHexBinary(s);
    }
}
 
Example 26
Project: athena   File: OspfUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Converts a number to four bytes.
 *
 * @param numberToConvert number to convert
 * @return given number as bytes
 */
public static byte[] convertToFourBytes(int numberToConvert) {

    byte[] numInBytes = new byte[4];
    String s1 = Integer.toHexString(numberToConvert);
    if (s1.length() % 2 != 0) {
        s1 = "0" + s1;
    }
    byte[] hexas = DatatypeConverter.parseHexBinary(s1);
    if (hexas.length == 1) {
        numInBytes[0] = 0;
        numInBytes[1] = 0;
        numInBytes[2] = 0;
        numInBytes[3] = hexas[0];
    } else if (hexas.length == 2) {
        numInBytes[0] = 0;
        numInBytes[1] = 0;
        numInBytes[2] = hexas[0];
        numInBytes[3] = hexas[1];
    } else if (hexas.length == 3) {
        numInBytes[0] = 0;
        numInBytes[1] = hexas[0];
        numInBytes[2] = hexas[1];
        numInBytes[3] = hexas[2];
    } else {
        numInBytes[0] = hexas[0];
        numInBytes[1] = hexas[1];
        numInBytes[2] = hexas[2];
        numInBytes[3] = hexas[3];
    }
    return numInBytes;
}
 
Example 27
Project: avr-bootloader   File: StrUtils.java   Source Code and License 5 votes vote down vote up
public static byte[] hexStringToBytes(String text) {
    text = text.replace(" ", "");
    if (text.length() % 2 == 1) {
        text = text.substring(0, text.length() - 1) + "0" + text.charAt(text.length() - 1);
    }
    return DatatypeConverter.parseHexBinary(text);
}
 
Example 28
Project: kms-jwt   File: JWTEncoder.java   Source Code and License 5 votes vote down vote up
public static JwtBuilder builder(KeyEncrypt keyEncrypt) throws KeyOperationException {
    SecretKey secretKey = MacProvider.generateKey(SignatureAlgorithm.HS256);
    byte[] encryptedKey = keyEncrypt.encrypt(secretKey.getEncoded());

    return Jwts.builder()
            .setHeaderParam("kid", DatatypeConverter.printBase64Binary(encryptedKey))
            .signWith(SignatureAlgorithm.HS256, secretKey);
}
 
Example 29
Project: spanner-jdbc   File: AbstractSpannerExpressionVisitorAdapter.java   Source Code and License 5 votes vote down vote up
@Override
public void visit(HexValue value)
{
	String stringValue = value.getValue().substring(2);
	byte[] byteValue = DatatypeConverter.parseHexBinary(stringValue);
	setValue(byteValue);
}
 
Example 30
Project: spanner-jdbc   File: DMLTester.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("deprecation")
private void verifyTableContentsAfterUpdate() throws SQLException
{
	verifyTableContents("SELECT UUID FROM TEST WHERE ID=1", DatatypeConverter.parseHexBinary("aabbcc"));
	verifyTableContents("SELECT ACTIVE FROM TEST WHERE ID=1", Boolean.FALSE);
	verifyTableContents("SELECT AMOUNT FROM TEST WHERE ID=1", Double.valueOf(129.95d));

	verifyTableContents("SELECT AMOUNT FROM TEST WHERE ID=2", Double.valueOf(-129.95d));
	verifyTableContents("SELECT CREATED_DATE FROM TEST WHERE ID=2", new Date(2017 - 1900, 1, 17));
	verifyTableContents("SELECT LAST_UPDATED FROM TEST WHERE ID=2", new Timestamp(2017 - 1900, 1, 17, 8, 0, 0, 0));
}
 
Example 31
Project: ramus   File: Options.java   Source Code and License 5 votes vote down vote up
public static void setStroke(String name, Stroke stroke) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        DataSaver.saveStroke(os, stroke, new DataLoader.MemoryData());
        setString(name, DatatypeConverter.printHexBinary(os.toByteArray()));
    } catch (IOException e) {
    }
}
 
Example 32
Project: wherehowsX   File: SchemaId.java   Source Code and License 5 votes vote down vote up
/**
 * convert String id into ByteBuffer
 * @param type
 * @param id String
 * @return byte[]
 */
public static byte[] getIdBytes(Type type, String id) {
  if (type == Type.INT) {
    return ByteBuffer.allocate(Type.INT.size).putInt(Integer.parseInt(id)).array();
  } else if (type == Type.LONG) {
    return ByteBuffer.allocate(Type.LONG.size).putLong(Long.parseLong(id)).array();
  } else if (type == Type.UUID) {
    return DatatypeConverter.parseHexBinary(id);
  } else {
    return new byte[0];
  }
}
 
Example 33
Project: pac4j-plus   File: CasClientTests.java   Source Code and License 5 votes vote down vote up
private String deflateAndBase64(final String data) {
    try {
        final Deflater deflater = new Deflater();
        deflater.setInput(data.getBytes(HttpConstants.UTF8_ENCODING));
        deflater.finish();
        final byte[] buffer = new byte[data.length()];
        final int resultSize = deflater.deflate(buffer);
        final byte[] output = new byte[resultSize];
        System.arraycopy(buffer, 0, output, 0, resultSize);
        return DatatypeConverter.printBase64Binary(output);
    } catch (final UnsupportedEncodingException e) {
        throw new RuntimeException("Cannot find encoding:" + HttpConstants.UTF8_ENCODING, e);
    }
}
 
Example 34
Project: incubator-netbeans   File: ProxyPreferencesImpl.java   Source Code and License 5 votes vote down vote up
@Override
public byte[] getByteArray(String key, byte[] def) {
    String value = get(key, null);
    if (value != null) {
        byte [] decoded = DatatypeConverter.parseBase64Binary(value);
        if (decoded != null) {
            return decoded;
        }
    }
    return def;
}
 
Example 35
Project: rapidminer   File: DefaultLicenseManager.java   Source Code and License 5 votes vote down vote up
private final LicenseStatus verifyProduct(Product product) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {
    if(product.isExtension() && product.getProductId().startsWith("rapidminer-")) {
        return LicenseStatus.WRONG_PRODUCT_ID;
    } else {
        Signature rsaSignature = Signature.getInstance("SHA1withRSA");
        rsaSignature.initVerify(this.publicKey);
        rsaSignature.update(product.createBase64Representation().getBytes(StandardCharsets.UTF_8));
        return rsaSignature.verify(DatatypeConverter.parseBase64Binary(product.getSignature()))?LicenseStatus.VALID:LicenseStatus.SIGNATURE_INVALID;
    }
}
 
Example 36
Project: MonitorYourLAN   File: NetworkTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testconvertImageToBase64()
{
	System.out.println("\n   testconvertImageToBase64()");
	
	String encodedImage = null;		
	Network TempNetwork = new Network ();
	
	encodedImage = TempNetwork.convertImageToBase64("");		
	DatatypeConverter.parseBase64Binary(encodedImage);	
	
}
 
Example 37
Project: xrd4j   File: MessageHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Encodes the given image to a base64 coded string.
 *
 * @param image image to encode
 * @param type type of the image: jpeg, bmp, png, gif etc.
 * @return encoded string
 */
public static String encodeImg2String(BufferedImage image, String type) {
    String imageString = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        ImageIO.write(image, type, bos);
        byte[] imageBytes = bos.toByteArray();
        imageString = DatatypeConverter.printBase64Binary(imageBytes);
        bos.close();
    } catch (IOException ex) {
        LOGGER.error(ex.getMessage(), ex);
    }
    return imageString;
}
 
Example 38
Project: SkinFixer   File: SkinConfig.java   Source Code and License 5 votes vote down vote up
public JsonElement toJson(String uuid, String username, String skinUrl, String capeUrl) {
    // Lets add all the information in case the game really needs them

    JsonObject tex = new JsonObject();

    if(skinUrl != null && !skinUrl.isEmpty()) {
        JsonObject skin = new JsonObject();
        skin.addProperty("url", skinUrl);
        tex.add("SKIN", skin);
    }

    if(capeUrl != null && !capeUrl.isEmpty()) {
        JsonObject cape = new JsonObject();
        cape.addProperty("url", capeUrl);
        tex.add("CAPE", cape);
    }

    JsonObject textures = new JsonObject();
    textures.addProperty("timestamp", (int)(System.currentTimeMillis() / 1000L));
    textures.addProperty("profileId", uuid);
    textures.addProperty("profileName", username);
    textures.add("textures", tex);

    JsonObject property = new JsonObject();
    property.addProperty("name", "textures");
    property.addProperty("value", DatatypeConverter.printBase64Binary(textures.toString().getBytes()));

    JsonArray properties = new JsonArray();
    properties.add(property);

    JsonObject obj = new JsonObject();
    obj.addProperty("id", uuid);
    obj.addProperty("name", username);
    obj.add("properties", properties);

    return obj;
}
 
Example 39
Project: BadIntent   File: ParcelByteArrDetails.java   Source Code and License 5 votes vote down vote up
public ArrayList getByteArrayList(){
    String hexStr = this.byteArray.getText().replace(" ", "");
    byte[] bytes = DatatypeConverter.parseHexBinary(hexStr);
    ArrayList doubleArrayList = new ArrayList();
    for (byte byteVal : bytes){
        doubleArrayList.add((double) byteVal);
    }
    return doubleArrayList;
}
 
Example 40
Project: sdk-java-demo   File: Sign.java   Source Code and License 5 votes vote down vote up
public static String digestHex(String str) {
	try {
		MessageDigest md = MessageDigest.getInstance("SHA-512");
		byte[] data = md.digest(str.getBytes());
		return DatatypeConverter.printHexBinary(data);
	} catch (NoSuchAlgorithmException e) {
		throw new RuntimeException(e);
	}
}
 
Example 41
Project: stroom-stats   File: ByteArrayUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Converts a byte array into a hex representation with a space between each
 * byte e.g 00 00 01 00 05 59 B3
 *
 * @param arr
 *            The byte array to convert
 * @return The byte array as a string of hex values separated by a spaces
 */
public static String byteArrayToHex(final byte[] arr) {
    final StringBuilder sb = new StringBuilder();
    if (arr != null) {
        for (final byte b : arr) {
            final byte[] oneByteArr = new byte[1];
            oneByteArr[0] = b;
            sb.append(DatatypeConverter.printHexBinary(oneByteArr));
            sb.append(" ");
        }
    }
    return sb.toString().replaceAll(" $", "");
}
 
Example 42
Project: Richkware-Manager-Client   File: Crypto.java   Source Code and License 5 votes vote down vote up
public static String EncryptRC4(String input, String key) {
    // encode input
    input = DatatypeConverter.printBase64Binary(input.getBytes());
    //input = DatatypeConverter.printHexBinary(input.getBytes());

    RC4 rc4 = new RC4(key.getBytes());
    byte[] ciphertext = rc4.encrypt(input.getBytes());

    // encode encrypted input
    //return DatatypeConverter.printBase64Binary(ciphertext);
    return DatatypeConverter.printHexBinary(ciphertext);
}
 
Example 43
Project: traccar-service   File: ExtendedObjectDecoder.java   Source Code and License 5 votes vote down vote up
private void saveOriginal(Object decodedMessage, Object originalMessage) {
    if (Context.getConfig().getBoolean("database.saveOriginal") && decodedMessage instanceof Position) {
        Position position = (Position) decodedMessage;
        if (originalMessage instanceof ChannelBuffer) {
            ChannelBuffer buf = (ChannelBuffer) originalMessage;
            position.set(Position.KEY_ORIGINAL, ChannelBuffers.hexDump(buf, 0, buf.writerIndex()));
        } else if (originalMessage instanceof String) {
            position.set(Position.KEY_ORIGINAL, DatatypeConverter.printHexBinary(
                            ((String) originalMessage).getBytes(StandardCharsets.US_ASCII)));
        }
    }
}
 
Example 44
Project: CharmMylynConnector   File: BasicAuthenticator.java   Source Code and License 5 votes vote down vote up
private String getBasicAuthentication() {
	String token = this.user + ":" + this.password;
	try {
		return "BASIC " + DatatypeConverter.printBase64Binary(token.getBytes("UTF-8"));
	} catch (UnsupportedEncodingException e) {
		throw new IllegalStateException("Encoding with UTF-8 failed", e);
	}
}
 
Example 45
Project: hearthstone   File: Img.java   Source Code and License 5 votes vote down vote up
/**
 * Codificar imagem para base64
 *
 * @param file local da imagem
 * @param type formato da codificação: jpeg, bmp, ...
 * @return String com a imagem na base64
 * @throws java.lang.Exception
 */
public static String encodeToString(File file, String type) throws Exception {
    BufferedImage img = ImageIO.read(file);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ImageIO.write(img, type, bos);
    String imageString = DatatypeConverter.printBase64Binary(bos.toByteArray());
    bos.close();
    return imageString;
}
 
Example 46
Project: loafer   File: TokenAuthenticationServiceImpl.java   Source Code and License 5 votes vote down vote up
public TokenAuthenticationServiceImpl(UserRepository userRepository,
                                      StringRedisTemplate stringRedisTemplate) {
    this.userRepository = userRepository;
    this.stringRedisTemplate = stringRedisTemplate;
    // TODO: parse this as a property
    tokenHandler = new TokenHandler(DatatypeConverter.parseBase64Binary("9SyECk96oDsTmXfogIfgdjhdsgvagHJLKNLvfdsfR8cbXTvoPjX+Pq/T/b1PqpHX0lYm0oCBjXWICA=="));
}
 
Example 47
Project: microbean-helm   File: TestDigest.java   Source Code and License 5 votes vote down vote up
@Test
public void testDigest() throws IOException, NoSuchAlgorithmException {
  final URL redisChart = Thread.currentThread().getContextClassLoader().getResource("redis-0.5.1/redis-0.5.1.tgz");
  assertNotNull(redisChart);
  final URL digest = Thread.currentThread().getContextClassLoader().getResource("redis-0.5.1/digest");
  assertNotNull(digest);
  assertTrue(digest.getProtocol().equals("file"));
  String expectedDigest = null;
  try (final BufferedReader reader = new BufferedReader(new InputStreamReader(digest.openStream(), StandardCharsets.UTF_8))) {
    assertNotNull(reader);
    expectedDigest = reader.readLine();
    assertNotNull(expectedDigest);
    expectedDigest = expectedDigest.toUpperCase();
  }
  final MessageDigest md = MessageDigest.getInstance("SHA-256");
  assertNotNull(md);
  ByteBuffer buffer = null;
  try (final InputStream rawInputStream = redisChart.openStream();
       final BufferedInputStream stream = rawInputStream instanceof BufferedInputStream ? (BufferedInputStream)rawInputStream : new BufferedInputStream(rawInputStream)) {
    assertNotNull(rawInputStream);
    assertNotNull(stream);
    buffer = readByteBuffer(stream);
  }
  assertNotNull(buffer);
  md.update(buffer);
  assertEquals(expectedDigest, DatatypeConverter.printHexBinary(md.digest()));
}
 
Example 48
Project: openjdk-jdk10   File: LDAPServer.java   Source Code and License 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 49
Project: hearthstone   File: Img.java   Source Code and License 5 votes vote down vote up
/**
 * Converter String Base64 em imagem
 *
 * @param imageString string com a imagem no formato base64
 * @return imagem
 * @throws java.lang.Exception
 */
public static BufferedImage decodeToImage(String imageString) throws Exception {
    BufferedImage image;
    byte[] imageByte = DatatypeConverter.parseBase64Binary(imageString);
    ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
    image = ImageIO.read(bis);
    bis.close();
    return image;
}
 
Example 50
Project: E-Clinic   File: PharmacistServiceImpl.java   Source Code and License 5 votes vote down vote up
private String encodehashPassword(String password) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("MD5");// SHA-512m SHA-256
    byte[] message = password.getBytes();
    md.update(message);
    byte[] digestbyte = md.digest();
    password = DatatypeConverter.printHexBinary(digestbyte).toLowerCase();

    return password;
}
 
Example 51
Project: ramus   File: Options.java   Source Code and License 5 votes vote down vote up
public static Stroke getStroke(String name, Stroke defaultStroke) {
    String val = getString(name);
    if (val == null)
        return defaultStroke;
    ByteArrayInputStream is = new ByteArrayInputStream(
            DatatypeConverter.parseHexBinary(val));
    try {
        return DataLoader.readStroke(is, new DataLoader.MemoryData());
    } catch (IOException e) {// shell never happen
        e.printStackTrace();
        return null;
    }
}
 
Example 52
Project: fts-tree   File: ProofEntry.java   Source Code and License 5 votes vote down vote up
@Override
public String toString() {
	return String.format("(%s, %d, %d)", 
			DatatypeConverter.printHexBinary(hash), 
			x1, 
			x2);
}
 
Example 53
Project: E-Clinic   File: ReceptionistServiceImpl.java   Source Code and License 5 votes vote down vote up
private String encodehashPassword(String password) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("MD5");// SHA-512m SHA-256
    byte[] message = password.getBytes();
    md.update(message);
    byte[] digestbyte = md.digest();
    password = DatatypeConverter.printHexBinary(digestbyte).toLowerCase();

    return password;
}
 
Example 54
Project: fresco_floodlight   File: AbstractRPCChannelHandler.java   Source Code and License 5 votes vote down vote up
private void authenticateResponse(String challenge, 
                                  String response) throws AuthException {
    String expected = generateResponse(challenge);
    if (expected == null) return;

    byte[] expectedBytes = DatatypeConverter.parseBase64Binary(expected);
    byte[] reponseBytes = DatatypeConverter.parseBase64Binary(response);
    
    if (!Arrays.equals(expectedBytes, reponseBytes)) {
        throw new AuthException("Challenge response does not match " +
                                "expected response");
    } 
}
 
Example 55
Project: vertx-sfdc-platformevents   File: RedisDedup.java   Source Code and License 5 votes vote down vote up
/**
 * Get a reasonable key value for the object
 * 
 * @param j
 *            the Json Object
 * @return a MD5 String
 */
private String getMd5(final JsonObject j) {
	String result = null;
	try {
		final MessageDigest md = MessageDigest.getInstance("MD5");
		final byte[] bresult = md.digest(j.toBuffer().getBytes());
		result = DatatypeConverter.printHexBinary(bresult);
	} catch (final NoSuchAlgorithmException e) {
		this.logger.fatal(e);
	}
	return result;
}
 
Example 56
Project: Clash-Royale   File: Producer.java   Source Code and License 5 votes vote down vote up
private void hashWord(MessageDigest msgDigest, String word) {
    try {
        byte[] digest = msgDigest.digest(word.getBytes("UTF-8"));
        String hex = DatatypeConverter.printHexBinary(digest);
        Item item = new Item(hex.toLowerCase(), word);
        // waits if queue is full
        queue.put(item);
    } catch (UnsupportedEncodingException | InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example 57
Project: osc-core   File: BackupFileService.java   Source Code and License 5 votes vote down vote up
private EncryptionParameters() throws KeyStoreProviderException, IOException {
	// get aliases/passwords to keystore from properties
	Properties properties = getProperties();
       String keyAlias = properties.getProperty("db.backup.key.alias");
       String keyPassword = properties.getProperty("db.backup.key.password");
       String ivAlias = properties.getProperty("db.backup.iv.alias");
       String ivPassword = properties.getProperty("db.backup.iv.password");

       // get key and iv from keystore
       this.key = KeyStoreProvider.getInstance().getSecretKey(keyAlias, keyPassword);
       this.iv = DatatypeConverter.parseHexBinary(KeyStoreProvider.getInstance().getPassword(ivAlias, ivPassword));
}
 
Example 58
Project: twasi-core   File: JWTManager.java   Source Code and License 5 votes vote down vote up
public String generateNewSecret() {
    final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    SecureRandom rnd = new SecureRandom();

    StringBuilder sb = new StringBuilder( 32 );
    for( int i = 0; i < 32; i++ )
        sb.append( AB.charAt( rnd.nextInt(AB.length()) ) );
    String randomString = sb.toString();

    return DatatypeConverter.printBase64Binary(randomString.getBytes());
}
 
Example 59
Project: osc-core   File: AESCTREncryption.java   Source Code and License 5 votes vote down vote up
public String encrypt(String plainText) throws EncryptionException {
    if (StringUtils.isBlank(plainText)) {
        return plainText;
    }

    byte[] plainTextBytes = plainText.getBytes();
    byte[] iv = generateIv();

    return String.join(":", DatatypeConverter.printHexBinary(iv),
                            DatatypeConverter.printHexBinary(encryptAesCtr(plainTextBytes, iv)));
}
 
Example 60
Project: E-Clinic   File: AdminClinicServiceImpl.java   Source Code and License 5 votes vote down vote up
private String encodehashPassword(String password) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("MD5");// SHA-512m SHA-256
    byte[] message = password.getBytes();
    md.update(message);
    byte[] digestbyte = md.digest();
    password = DatatypeConverter.printHexBinary(digestbyte).toLowerCase();

    return password;
}