javax.xml.bind.DatatypeConverter#parseBase64Binary ( )源码实例Demo

下面列出了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();
	}
}
 
源代码2 项目: AngularBeans   文件: CommonUtils.java
/**
 * 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();
}
 
源代码4 项目: my_curd   文件: JwtUtils.java
/**
 * 生成签名
 *
 * @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();
}
 
源代码5 项目: envelope   文件: TestConfigUtils.java
@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();
}
 
源代码7 项目: wechat-java-sdk   文件: WeChatMP.java
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);
    }
}
 
源代码8 项目: lams   文件: Base64Utils.java
/**
 * 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);
	}
}
 
源代码9 项目: spring-ldap   文件: LdapEncoder.java
/**
 * 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());
}
 
源代码10 项目: 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();
    }
 
源代码11 项目: bidder   文件: TestGoogle.java
@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"));
}
 
源代码12 项目: cassandra-reaper   文件: ShiroJwtProvider.java
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());
}
 
源代码13 项目: withme3.0   文件: JwtUtils.java
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;
}
 
源代码15 项目: CogniCrypt   文件: PasswordHasher.java
private static byte[] fromBase64(java.lang.String hash) {
	return DatatypeConverter.parseBase64Binary(hash);
}
 
源代码16 项目: cms   文件: CmsBase64Utility.java
public static byte[] fromBase64(String value)
{
	return DatatypeConverter.parseBase64Binary(value);
}
 
源代码17 项目: jkube   文件: Base64Util.java
public static byte[] decode(String raw) {
    return DatatypeConverter.parseBase64Binary(raw);
}
 
源代码18 项目: jarling   文件: Photo.java
public byte[] getPhoto(){
    return DatatypeConverter.parseBase64Binary(this.base64EncodedPhoto);
}
 
源代码19 项目: emissary   文件: ExtractionTest.java
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());
    }
}
 
源代码20 项目: yangtools   文件: BinaryStringCodec.java
@Override
public final byte[] deserializeImpl(final String product) {
    final byte[] ret = DatatypeConverter.parseBase64Binary(product);
    validate(ret);
    return ret;
}