类javax.xml.bind.DatatypeConverter源码实例Demo

下面列出了怎么用javax.xml.bind.DatatypeConverter的API类实例代码及写法,或者点击链接到github查看源代码。

@Override
public String createToken(String subject, long ttlMillis) {
	
	if (ttlMillis <= 0) {
		throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] ");
	}
	
	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

	// The JWT signature algorithm we will be using to sign the token
	long nowMillis = System.currentTimeMillis();

	byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey);
	Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

	JwtBuilder builder = Jwts.builder()
			.setSubject(subject)				
			.signWith(signatureAlgorithm, signingKey);
	
	builder.setExpiration(new Date(nowMillis + ttlMillis));		

	return builder.compact();
}
 
@Override
public User getUserByToken(String token){
	Claims claims = Jwts.parser()         
		       .setSigningKey(DatatypeConverter.parseBase64Binary(SecurityServiceImpl.secretKey))
		       .parseClaimsJws(token).getBody();
	
	if(claims == null || claims.getSubject() == null){
		return null;
	}
	
	String subject = claims.getSubject();
	
	if(subject.split("=").length != 2){
		return null;
	}
	
	String[] subjectParts = subject.split("=");
	
	
	Integer userid = new Integer(subjectParts[0]);
	Integer usertype = new Integer(subjectParts[1]);		
	
	System.out.println("{getUserByToken} usertype["+usertype+"], userid["+userid+"]");
	
	return new User(userid, usertype);
}
 
源代码3 项目: jmxtrans-agent   文件: Connection.java
private PrivateKey getPrivateKeyFromString(String serviceKeyPem) {
    if (isNullOrEmpty(serviceKeyPem))
        return null;
    PrivateKey privateKey = null;
    try {
        String privKeyPEM = serviceKeyPem.replace("-----BEGIN PRIVATE KEY-----", "")
                .replace("-----END PRIVATE KEY-----", "")
                .replace("\\r", "")
                .replace("\\n", "")
                .replace("\r", "")
                .replace("\n", "");

        byte[] encoded = DatatypeConverter.parseBase64Binary(privKeyPEM);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
        privateKey = KeyFactory.getInstance("RSA")
                .generatePrivate(keySpec);
    } catch (Exception e) {
        String error = "Constructing Private Key from PEM string failed: " + e.getMessage();
        logger.log(Level.SEVERE, error, e);
    }
    return privateKey;
}
 
源代码4 项目: faster-framework-project   文件: JwtService.java
/**
 * 解密
 *
 * @param token          要解密的token
 * @param base64Security 秘钥
 * @return Claims
 */
private Claims parseToken(String token, String base64Security) {
    try {
        Claims claims = Jwts.parser()
                .setSigningKey(DatatypeConverter.parseBase64Binary(base64Security))
                .parseClaimsJws(token).getBody();
        if (claims == null) {
            return null;
        }
        //如果环境相同
        if (this.env.equals(claims.get("env", String.class))) {
            return claims;
        }
        return null;
    } catch (Exception e) {
        return null;
    }
}
 
源代码5 项目: spring-kafka   文件: AvroDeserializer.java
@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);
  }
}
 
源代码6 项目: mongo-java-driver-rx   文件: GridFSTest.java
private void doDownload(final BsonDocument arguments, final BsonDocument assertion) {
    Throwable error = null;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    try {
        gridFSBucket.downloadToStream(arguments.getObjectId("id").getValue(), toAsyncOutputStream(outputStream))
                .timeout(30, SECONDS).toList().toBlocking().first();
        outputStream.close();
    } catch (Throwable e) {
        error = e;
    }

    if (assertion.containsKey("result")) {
        assertNull("Should not have thrown an exception", error);
        assertEquals(DatatypeConverter.printHexBinary(outputStream.toByteArray()).toLowerCase(),
                assertion.getDocument("result").getString("$hex").getValue());
    } else if (assertion.containsKey("error")) {
        assertNotNull("Should have thrown an exception", error);
    }
}
 
源代码7 项目: localization_nifi   文件: PublishKafka_0_10.java
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);
}
 
源代码8 项目: semanticMDR   文件: AdministrationRecordImpl.java
@Override
public void setLastChangeDate(Calendar lastChangeDate,
		String changeDescription) {
	if (lastChangeDate != null && Util.isNull(changeDescription)) {
		throw new IllegalArgumentException(
				"Change Description must be specified if a Last Change Date is set for Administration Record.");
	}
	if (lastChangeDate == null && !Util.isNull(changeDescription)) {
		throw new IllegalArgumentException(
				"Change Description cannot be set if a Last Change Date is not specified for Administration Record.");
	}
	if (lastChangeDate == null) {
		setPropertyValue(mdrDatabase.getVocabulary().lastChangeDate,
				mdrDatabase.getUtil().createTypedLiteral(null));
	} else {
		setPropertyValue(
				mdrDatabase.getVocabulary().lastChangeDate,
				mdrDatabase.getOntModel().createTypedLiteral(
						DatatypeConverter.printDateTime(lastChangeDate)));
	}
	setPropertyValue(mdrDatabase.getVocabulary().changeDescription,
			mdrDatabase.getUtil().createTypedLiteral(changeDescription));
}
 
@Test
public void trickyBlock() {
    byte[] compressedData = DatatypeConverter.parseHexBinary("1F000100078078000000B4000000");
    int uncompressedSizeBytes = 35;

    ClickHouseBlockChecksum checksum = ClickHouseBlockChecksum.calculateForBlock(
        (byte) ClickHouseLZ4Stream.MAGIC,
        compressedData.length + HEADER_SIZE_BYTES,
        uncompressedSizeBytes,
        compressedData,
        compressedData.length
    );

    Assert.assertEquals(
        new ClickHouseBlockChecksum(-493639813825217902L, -6253550521065361778L),
        checksum
    );
}
 
源代码10 项目: openhab1-addons   文件: RFXComUndecodedRFMessage.java
@Override
public State convertToState(RFXComValueSelector valueSelector) throws RFXComException {

    org.openhab.core.types.State state = UnDefType.UNDEF;

    if (valueSelector.getItemClass() == StringItem.class) {
        if (valueSelector == RFXComValueSelector.RAW_DATA) {
            state = new StringType(DatatypeConverter.printHexBinary(rawMessage));
        } else if (valueSelector == RFXComValueSelector.DATA) {
            state = new StringType(DatatypeConverter.printHexBinary(rawData));
        } else {
            throw new RFXComException("Can't convert " + valueSelector + " to StringItem");
        }
    } else {
        throw new RFXComException("Can't convert " + valueSelector + " to " + valueSelector.getItemClass());
    }

    return state;
}
 
源代码11 项目: DBus   文件: JWTUtils.java
public static String buildToken(String key, long expirationMinutes, Map<String, Object> claims) {

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(key);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        JwtBuilder builder = Jwts.builder().setIssuedAt(now)
                .addClaims(claims)
                .signWith(signatureAlgorithm, signingKey);
        builder.setExpiration(new Date(nowMillis + expirationMinutes * 60 * 1000));

        return builder.compact();
    }
 
源代码12 项目: elasticsearch-hadoop   文件: DateUtils.java
public static Calendar parseDate(String value) {
    // check for colon in the time offset
    int timeZoneIndex = value.indexOf("T");
    if (timeZoneIndex > 0) {
        int sign = value.indexOf("+", timeZoneIndex);
        if (sign < 0) {
            sign = value.indexOf("-", timeZoneIndex);
        }

        // +4 means it's either hh:mm or hhmm
        if (sign > 0) {
            // +3 points to either : or m
            int colonIndex = sign + 3;
            // +hh - need to add :mm
            if (colonIndex >= value.length()) {
                value = value + ":00";
            }
            else if (value.charAt(colonIndex) != ':') {
                value = value.substring(0, colonIndex) + ":" + value.substring(colonIndex);
            }
        }
    }

    return DatatypeConverter.parseDateTime(value);
}
 
源代码13 项目: cf-java-logging-support   文件: TokenCreator.java
private static RSAPrivateKey privateKeyConverter(String pemKey) throws NoSuchAlgorithmException,
                                                                InvalidKeySpecException {
    byte[] keyBytes = DatatypeConverter.parseBase64Binary(pemKey);
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return (RSAPrivateKey) keyFactory.generatePrivate(spec);
}
 
源代码14 项目: tutorials   文件: StringToByteArrayUnitTest.java
@Test
public void whenConvertStringToByteArray_thenOk(){
    String originalInput = "7465737420696E707574";
    byte[] result = DatatypeConverter.parseHexBinary(originalInput);
    System.out.println(Arrays.toString(result));
    
    assertEquals("test input", new String(result));
}
 
源代码15 项目: cf-java-logging-support   文件: TokenCreator.java
private static RSAPublicKey publicKeyConverter(String pemKey) throws NoSuchAlgorithmException,
                                                              InvalidKeySpecException {
    byte[] keyBytes = DatatypeConverter.parseBase64Binary(pemKey);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return (RSAPublicKey) keyFactory.generatePublic(spec);
}
 
源代码16 项目: eagle   文件: Base64.java
public static String encode(String plain) {
    try {
        return DatatypeConverter.printBase64Binary(plain.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("UTF-8 must be supported", e);
    }
}
 
源代码17 项目: emissary   文件: MagicNumberTest.java
@Test
public void testByte() throws ParseException {
    MagicNumber m = MagicNumberFactory.buildMagicNumber("0 byte 0x09");
    assertTrue("Equal magic operator failed", m.test(DatatypeConverter.parseHexBinary("09")));
    assertFalse("Equal magic operator failed", m.test(DatatypeConverter.parseHexBinary("A1")));
    assertFalse("Equal magic operator failed", m.test(DatatypeConverter.parseHexBinary("AB")));

    m = MagicNumberFactory.buildMagicNumber("0 byte 0xF2");
    assertTrue("Equal magic operator failed", m.test(DatatypeConverter.parseHexBinary("F2")));
    assertFalse("Equal magic operator failed", m.test(DatatypeConverter.parseHexBinary("A1")));
    assertFalse("Equal magic operator failed", m.test(DatatypeConverter.parseHexBinary("AB")));
}
 
源代码18 项目: java-client-api   文件: ValueConverter.java
static public void convertFromJava(Byte value, ValueProcessor processor) {
  if (value == null) {
    processor.process(null, null, null);
    return;
  }
  processor.process(
    value,
    "xs:byte",
    DatatypeConverter.printByte(value)
  );
}
 
源代码19 项目: tech-gallery   文件: TechnologyServiceImpl.java
private String saveImage(Technology technology) throws IOException, GeneralSecurityException {
    String imageLink = technology.getImage();
    if (technology.getImageContent() != null) {
        imageLink = storageDAO.insertImage(technology.convertNameToId(technology.getName()),
                new ByteArrayInputStream(DatatypeConverter.parseBase64Binary(technology.getImageContent())));
    }
    return imageLink;
}
 
源代码20 项目: java-client-api   文件: ValueConverter.java
static public BigDecimal StringToBigDecimal(String value) {
  try {
    return (value == null || value.length() == 0) ? null :
          DatatypeConverter.parseDecimal(value);
  } catch(Exception e) {
    throw new IllegalArgumentException("Could not convert to BigDecimal: "+value, e);
  }
}
 
源代码21 项目: openjdk-8   文件: HttpTransportPipe.java
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));
        }
    }
}
 
源代码22 项目: OpenEstate-IO   文件: TrovitUtils.java
/**
 * Write a {@link BigInteger} value into XML output for a year number.
 *
 * @param value value to write
 * @return XML string
 * @throws IllegalArgumentException if a validation error occurred
 */
public static String printYearValue(BigInteger value) {
    if (value == null)
        throw new IllegalArgumentException("Can't print empty year value!");
    if (value.compareTo(BigInteger.valueOf(1700L)) < 0)
        throw new IllegalArgumentException("Can't print year value '" + value + "' because it is below 1700!");
    if (value.compareTo(BigInteger.valueOf(9999L)) > 0)
        throw new IllegalArgumentException("Can't print year value '" + value + "' because it is above 9999!");

    return DatatypeConverter.printInteger(value);
}
 
@Test
public void signAndVerify() {
    Bytes privateKeyBuffer = null;
    Bytes secretKeyBuffer = null;
    Bytes privateOrSecret = bft.fromHex(privateOrSecretKey);
    if (privateOrSecret.readRemaining() == Ed25519.SECRET_KEY_LENGTH) {
        secretKeyBuffer = privateOrSecret;
    } else {
        privateKeyBuffer = privateOrSecret;
    }

    Bytes publicKeyBuffer = bft.fromHex(publicKey);
    if (secretKeyBuffer == null) {
        secretKeyBuffer = bft.bytesWithZeros(Ed25519.SECRET_KEY_LENGTH);
        Bytes tmpPublicKeyBuffer = bft.bytesWithZeros(Ed25519.PUBLIC_KEY_LENGTH);
        Ed25519.privateToPublicAndSecret(tmpPublicKeyBuffer, secretKeyBuffer, privateKeyBuffer);
        assertEquals(publicKeyBuffer.toHexString(), tmpPublicKeyBuffer.toHexString());
    }
    Bytes messageBuffer = bft.fromHex(message);
    Bytes signExpectedBuffer;
    if (signExpected.length() == 128) {
        signExpectedBuffer = Bytes.wrapForRead(DatatypeConverter.parseHexBinary(signExpected + message));
    } else {
        signExpectedBuffer = Bytes.wrapForRead(DatatypeConverter.parseHexBinary(signExpected));
    }
    Bytes signedMsgBuffer = bft.fromHex(Ed25519.SIGNATURE_LENGTH, message);
    signedMsgBuffer.writePosition(0);
    Ed25519.sign(signedMsgBuffer, messageBuffer, secretKeyBuffer);
    assertEquals(signExpectedBuffer.toHexString(), signedMsgBuffer.toHexString());
    signedMsgBuffer.readPosition(0);
    publicKeyBuffer.readPositionRemaining(0, Ed25519.PUBLIC_KEY_LENGTH);
    assertTrue(Ed25519.verify(signedMsgBuffer, publicKeyBuffer));
}
 
源代码24 项目: mogu_blog_v2   文件: JwtUtil.java
public static String createSysUserJWT(Long shopId, Long sysUserId, String loginUserName, String loginPassWord, boolean isShop) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        //生成签名密钥
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                .claim("shop_id", shopId)
                .claim("sys_user_id", sysUserId)
                .claim("is_shop", isShop)
                .claim("login_username", loginUserName)
                .claim("login_password", loginPassWord)
//	                .claim("user_open_id", userOpenId)
                .signWith(signatureAlgorithm, signingKey);
        //添加Token过期时间
        if (expiresSecond >= 0) {
            long expMillis = nowMillis + expiresSecond;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp).setNotBefore(now);
        }

        //生成JWT
        String compact = builder.compact();
        log.info("生成jwt===========" + compact);
        return compact;
    }
 
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");
    } 
}
 
源代码26 项目: sailfish-core   文件: SerializeUtil.java
public static String serializeToBase64(Serializable o) {
    if (o == null) {
        return null;
    }

    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(o);
        }
       return DatatypeConverter.printBase64Binary(baos.toByteArray());
    }catch (IOException e) {
        logger.error("Object serializing error", e);
        return null;
    }
}
 
源代码27 项目: essentials   文件: StringUtilsJvmTest.java
@Test
public void testHexBig() {
    for (int i = 0; i < 256 * 256; i++) {
        byte[] bytes = {(byte) (i >> 8), (byte) i};
        String hexExpected = DatatypeConverter.printHexBinary(bytes);
        String hex = StringUtils.hex(bytes);
        assertEquals(hexExpected, hex);

        byte[] bytes2 = StringUtils.parseHex(hex);
        assertEquals(bytes[0], bytes2[0]);
        assertEquals(bytes[1], bytes2[1]);
    }
}
 
源代码28 项目: semanticMDR   文件: PermissibleValueImpl.java
@Override
public void setPermissibleValueEndDate(Calendar permissibleValueEndDate) {
	if (permissibleValueEndDate == null) {
		setPropertyValue(
				mdrDatabase.getVocabulary().permissibleValueEndDate,
				mdrDatabase.getUtil().createTypedLiteral(null));
	} else {
		setPropertyValue(
				mdrDatabase.getVocabulary().permissibleValueEndDate,
				mdrDatabase.getOntModel().createTypedLiteral(
						DatatypeConverter
								.printDateTime(permissibleValueEndDate)));
	}
}
 
源代码29 项目: arcusplatform   文件: TestCRC16.java
@Test
public void testHubFromMac() {
	String str = "00112233445566778899AABBCCDDEEFF";
	byte[] bytes = DatatypeConverter.parseHexBinary(str);
	assertEquals((short) 0x27A9, CRC16.ARC.crc(bytes));
	assertEquals((short) 0x57E3, CRC16.AUG.crc(bytes));
	assertEquals((short) 0x0B62, CRC16.BUYPASS.crc(bytes));
	assertEquals((short) 0x7842, CRC16.CCITT.crc(bytes));
	assertEquals((short) 0x9F0B, CRC16.CDMA2000.crc(bytes));
	assertEquals((short) 0x8545, CRC16.DDS110.crc(bytes));
	assertEquals((short) 0xDFE2, CRC16.DECT_R.crc(bytes));
	assertEquals((short) 0xDFE3, CRC16.DECT_X.crc(bytes));
	assertEquals((short) 0xF289, CRC16.DNP.crc(bytes));
	assertEquals((short) 0xAF18, CRC16.EN_13757.crc(bytes));
	assertEquals((short) 0x87BD, CRC16.GENIBUS.crc(bytes));
	assertEquals((short) 0xD856, CRC16.MAXIM.crc(bytes));
	assertEquals((short) 0x70AD, CRC16.MCRF4XX.crc(bytes));
	assertEquals((short) 0x198A, CRC16.RIELLO.crc(bytes));
	assertEquals((short) 0xB1B2, CRC16.T10_DIF.crc(bytes));
	assertEquals((short) 0x70BC, CRC16.TELEDISK.crc(bytes));
	assertEquals((short) 0x348C, CRC16.TMS37157.crc(bytes));
	assertEquals((short) 0x28E8, CRC16.USB.crc(bytes));
	assertEquals((short) 0x69CC, CRC16.A.crc(bytes));
	assertEquals((short) 0xD717, CRC16.MODBUS.crc(bytes));		
	assertEquals((short) 0x8F52, CRC16.X25.crc(bytes));
	assertEquals((short) 0x1248, CRC16.XMODEM.crc(bytes));
	assertEquals((short) 0x20FB, CRC16.KERMIT.crc(bytes));
}
 
源代码30 项目: olingo-odata4   文件: SearchHandler.java
private static String asString(final Object primitive) {
  // TODO: improve 'string' conversion; maybe consider only String properties
  if (primitive instanceof String) {
    return (String) primitive;
  } else if (primitive instanceof Calendar) {
    return DatatypeConverter.printDateTime((Calendar) primitive);
  } else if (primitive instanceof byte[]) {
    return DatatypeConverter.printBase64Binary((byte[]) primitive);
  } else {
    return primitive.toString();
  }
}
 
 类所在包