下面列出了javax.xml.bind.DatatypeConverter#parseBase64Binary ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public byte[] decode() throws IOException {
byte[] decoded = DatatypeConverter.parseBase64Binary(this.base64String);
if(!this.zippedContent) {
return decoded;
} else {
// Unzip the contents, assumption is only 1 zip entry in the zip content
ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(decoded));
ByteArrayOutputStream baos = null;
ZipEntry ze = zis.getNextEntry();
// Check if there is a zip entry
if (ze == null) {
throw new NullPointerException("Unable to decompress as content is not zipped");
}
baos = Converter.toBAOS(zis);
zis.closeEntry();
zis.close();
return baos.toByteArray();
}
}
/**
* Returns array of bytes
*
* @param element
* JsonPrimitive with base64 javascript pattern
* @return Array of bytes
*/
public static byte[] getBytesFromJson(JsonElement element) {
String value = element.getAsString();
if (value != null && value.trim().length() > 0) {
try {
if (value.contains(DATA_MARK) && value.contains(BASE64_MARK)) {
value = value.substring(value.indexOf(BASE64_MARK) + BASE64_MARK.length());
}
if (value.length() > 0) {
return DatatypeConverter.parseBase64Binary(value); // Base64.getDecoder().decode(value); (Java8)
}
}
catch (Exception e) {}
}
return null;
}
@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();
}
/**
* 生成签名
*
* @param username 用户名
* @param roleList 角色集合
* @param permissionList 权限集合
* @return
*/
public static String buildToken(String username, List<String> roleList, List<String> permissionList) {
// HS256签名算法
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
// 构造payload
long nowSeconds = System.currentTimeMillis() / 1000;
JSONObject payload = new JSONObject();
payload.put("iss", ISS); // 签发者
payload.put("iat", nowSeconds); // 签发时间
payload.put("exp", nowSeconds + EXPIRATION_TIME_VALUE); // 过期时间
payload.put("username", username);
if (roleList == null) {
payload.put("roleList", new ArrayList<>());
}
if (permissionList == null) {
payload.put("permissionList", new ArrayList<>());
}
JwtBuilder builder = Jwts.builder().setPayload(payload.toJSONString())
.signWith(signatureAlgorithm, signingKey);
return builder.compact();
}
@Test
public void testConfigFromPathButJarFile() throws Exception {
byte[] testJarContents = DatatypeConverter.parseBase64Binary(
"UEsDBAoAAAAAAPJrbU4AAAAAAAAAAAAAAAAFABAAdGVzdC9VWAwAfD6JXHc+iVz2ARQAUEsBAhUDCgAAAAAA8mtt" +
"TgAAAAAAAAAAAAAAAAUADAAAAAAAAAAAQO1BAAAAAHRlc3QvVVgIAHw+iVx3PolcUEsFBgAAAAABAAEAPwAA" +
"ADMAAAAAAA==");
try {
File jarFile = folder.newFile("test.jar");
Files.write(jarFile.toPath(), testJarContents);
ConfigUtils.configFromPath(jarFile.getAbsolutePath());
}
catch (RuntimeException e) {
if (e.getMessage().equals(ConfigUtils.JAR_FILE_EXCEPTION_MESSAGE)) {
return;
}
}
fail();
}
@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();
}
public WeChatMP(WeChatMPConfig config, WeChatMPEventHandler eventHandler, WeChatMPHttpClient httpClient,
WeChatMPAccessTokenStorage atStorage) {
this.config = config;
this.eventHandler = eventHandler;
this.httpClient = httpClient;
this.atStorage = atStorage;
this.appIdBytes = config.getAppId().getBytes(Charset.forName("utf-8"));
if (config.getAESKey() != null) {
this.aesKeyBytes = DatatypeConverter.parseBase64Binary(config.getAESKey() + "=");
} else {
this.aesKeyBytes = null;
}
if (null != eventHandler) {
eventHandler.setWeChatMP(this);
}
}
/**
* Base64-decode the given byte array from an UTF-8 String.
* @param src the encoded UTF-8 String (may be {@code null})
* @return the original byte array (or {@code null} if the input was {@code null})
*/
public static byte[] decodeFromString(String src) {
if (src == null) {
return null;
}
if (src.isEmpty()) {
return new byte[0];
}
if (delegate != null) {
// Full encoder available
return delegate.decode(src.getBytes(DEFAULT_CHARSET));
}
else {
// JAXB fallback for String case
return DatatypeConverter.parseBase64Binary(src);
}
}
/**
* Converts the Base64 encoded string argument into an array of bytes.
*
* @param val
* @return
* An array of bytes represented by the string argument.
* @throws IllegalArgumentException if <tt>val</tt> is null or does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:base64Binary.
*/
public static byte[] parseBase64Binary(String val) {
Assert.notNull(val, "val must not be null!");
int length = val.length();
StringBuilder sb = new StringBuilder(length);
for (int i = 0, len = length; i < len; i++) {
char c = val.charAt(i);
if(c == '\n'){
if(i + 1 < len && val.charAt(i + 1) == ' ') {
i++;
}
continue;
}
sb.append(c);
}
return DatatypeConverter.parseBase64Binary(sb.toString());
}
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();
}
@Test
public void testVerticals() throws Exception {
String proto = Charset.defaultCharset()
.decode(ByteBuffer
.wrap(Files.readAllBytes(Paths.get("./SampleBids/nositedomain.proto"))))
.toString();
byte[] data = DatatypeConverter.parseBase64Binary(proto);
InputStream is = new ByteArrayInputStream(data);
GoogleBidRequest r = new GoogleBidRequest(is);
Object s = r.interrogate("site.domain");
String test = s.toString();
assertTrue(test.contains("mobile.sabq.org"));
ArrayNode node = (ArrayNode)r.interrogate("site.cat");
test = node.toString();
assertTrue(test.contains("5098"));
assertTrue(test.contains("702"));
assertTrue(test.contains("666"));
assertTrue(test.contains("16"));
}
private static Key getSigningKey(AppContext cxt) {
String txt = System.getenv("JWT_SECRET");
if (null == txt) {
if (cxt.storage instanceof CassandraStorage) {
txt = cxt.config.getCassandraFactory().getClusterName();
} else if (cxt.storage instanceof PostgresStorage) {
txt = cxt.config.getPostgresDataSourceFactory().getUrl();
} else {
txt = AppContext.REAPER_INSTANCE_ADDRESS;
}
}
return new SecretKeySpec(DatatypeConverter.parseBase64Binary(txt), SIG_ALG.getJcaName());
}
public static String createJWT(String authUser) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(CONSTANT.SECRET_KEY);
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
JwtBuilder builder = Jwts.builder()
.setHeaderParam("typ", "jwt")
.setHeaderParam("alg", "HS256")
.setPayload(authUser)
.signWith(signatureAlgorithm, signingKey);
return builder.compact();
}
@Override
public KafkaProducerRecord<byte[], byte[]> toKafkaRecord(String kafkaTopic, Integer partition, Buffer message) {
Integer partitionFromBody = null;
byte[] key = null;
byte[] value = null;
JsonObject json = message.toJsonObject();
if (!json.isEmpty()) {
if (json.containsKey("key")) {
key = DatatypeConverter.parseBase64Binary(json.getString("key"));
}
if (json.containsKey("value")) {
value = DatatypeConverter.parseBase64Binary(json.getString("value"));
}
if (json.containsKey("partition")) {
partitionFromBody = json.getInteger("partition");
}
if (partition != null && partitionFromBody != null) {
throw new IllegalStateException("Partition specified in body and in request path");
}
if (partition != null) {
partitionFromBody = partition;
}
}
KafkaProducerRecord<byte[], byte[]> record = KafkaProducerRecord.create(kafkaTopic, key, value, partitionFromBody);
return record;
}
private static byte[] fromBase64(java.lang.String hash) {
return DatatypeConverter.parseBase64Binary(hash);
}
public static byte[] fromBase64(String value)
{
return DatatypeConverter.parseBase64Binary(value);
}
public static byte[] decode(String raw) {
return DatatypeConverter.parseBase64Binary(raw);
}
public byte[] getPhoto(){
return DatatypeConverter.parseBase64Binary(this.base64EncodedPhoto);
}
protected void checkStringValue(Element meta, String data, String tname) {
String key = meta.getChildTextTrim("name");
String value = meta.getChildText("value");
String matchMode = "equals";
Attribute mm = meta.getAttribute("matchMode");
if (value == null) {
return; // checking the value is optional
}
if (mm != null) {
matchMode = mm.getValue();
}
if (matchMode.equals("equals")) {
assertEquals(meta.getName() + " element '" + key + "' problem in " + tname + " value '" + data + "' does not equal '" + value + "'",
value, data);
} else if (matchMode.equals("index")) {
assertTrue(meta.getName() + " element '" + key + "' problem in " + tname + " value '" + data + "' does not index '" + value + "'",
data.indexOf(value) > -1);
} else if (matchMode.equals("match")) {
assertTrue(meta.getName() + " element '" + key + "' problem in " + tname + " value '" + data + "' does not match '" + value + "'",
data.matches(value));
} else if (matchMode.equals("base64")) {
// decode value as a base64 encoded byte[] array and use the string
// representation of the byte array for comparison to the incoming value
value = new String(DatatypeConverter.parseBase64Binary(value));
assertEquals(meta.getName() + " element '" + key + "' problem in " + tname + " value '" + data + "' does not match '" + value + "'",
value, data);
} else if ("collection".equalsIgnoreCase(matchMode)) {
Attribute separatorAttribute = meta.getAttribute("collectionSeparator");
String separator = null != separatorAttribute ? separatorAttribute.getValue() : ","; // comma is default
// separator
Collection<String> expectedValues = Arrays.asList(value.split(separator));
Collection<String> actualValues = Arrays.asList(data.split(separator));
assertTrue(meta.getName() + " element '" + key + "' problem in " + tname + " did not have equal collection, value ' " + data
+ "' does not equal '" + value + "' split by separator '" + separator + "'",
CollectionUtils.isEqualCollection(expectedValues, actualValues));
} else {
fail("Problematic matchMode specified for test '" + matchMode + "' on " + key + " in element " + meta.getName());
}
}
@Override
public final byte[] deserializeImpl(final String product) {
final byte[] ret = DatatypeConverter.parseBase64Binary(product);
validate(ret);
return ret;
}