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

The following examples show how to use javax.xml.bind.DatatypeConverter#parseBase64Binary() . 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: ConversionBase64Decode.java    From equalize-xpi-modules with MIT License 6 votes vote down vote up
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();
	}
}
 
Example 2
Source File: CommonUtils.java    From AngularBeans with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 3
Source File: TestGoogle.java    From bidder with Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example 4
Source File: SecurityServiceImpl.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 6 votes vote down vote up
@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();
}
 
Example 5
Source File: JwtUtils.java    From my_curd with Apache License 2.0 6 votes vote down vote up
/**
 * 生成签名
 *
 * @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();
}
 
Example 6
Source File: TestConfigUtils.java    From envelope with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 7
Source File: SecurityServiceImpl.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 6 votes vote down vote up
@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();
}
 
Example 8
Source File: JWTUtils.java    From DBus with Apache License 2.0 6 votes vote down vote up
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();
    }
 
Example 9
Source File: WeChatMP.java    From wechat-java-sdk with MIT License 6 votes vote down vote up
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);
    }
}
 
Example 10
Source File: Base64Utils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 11
Source File: LdapEncoder.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example 12
Source File: HttpBinaryMessageConverter.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 13
Source File: JwtUtils.java    From withme3.0 with MIT License 5 votes vote down vote up
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();
}
 
Example 14
Source File: ShiroJwtProvider.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 15
Source File: ExtractionTest.java    From emissary with Apache License 2.0 4 votes vote down vote up
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());
    }
}
 
Example 16
Source File: Photo.java    From jarling with MIT License 4 votes vote down vote up
public byte[] getPhoto(){
    return DatatypeConverter.parseBase64Binary(this.base64EncodedPhoto);
}
 
Example 17
Source File: Base64Util.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
public static byte[] decode(String raw) {
    return DatatypeConverter.parseBase64Binary(raw);
}
 
Example 18
Source File: BinaryStringCodec.java    From yangtools with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public final byte[] deserializeImpl(final String product) {
    final byte[] ret = DatatypeConverter.parseBase64Binary(product);
    validate(ret);
    return ret;
}
 
Example 19
Source File: CmsBase64Utility.java    From cms with Apache License 2.0 4 votes vote down vote up
public static byte[] fromBase64(String value)
{
	return DatatypeConverter.parseBase64Binary(value);
}
 
Example 20
Source File: PasswordHasher.java    From CogniCrypt with Eclipse Public License 2.0 4 votes vote down vote up
private static byte[] fromBase64(java.lang.String hash) {
	return DatatypeConverter.parseBase64Binary(hash);
}