public void afterPropertiesSet() throws UnsupportedEncodingException { Collection<Header> defaultHeaders = new ArrayList<Header>(); Header header = new BasicHeader("Authorization", "Basic " + BaseEncoding.base64().encode("apollo:".getBytes("UTF-8"))); defaultHeaders.add(header); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("apollo", "")); CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider) .setDefaultHeaders(defaultHeaders).build(); restTemplate = new RestTemplate(httpMessageConverters.getConverters()); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); requestFactory.setConnectTimeout(portalConfig.connectTimeout()); requestFactory.setReadTimeout(portalConfig.readTimeout()); restTemplate.setRequestFactory(requestFactory); }
private void initCrypto(String privateKey, String certificate) throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] privateBytes = BaseEncoding.base64().decode(privateKey); KeySpec spec = new PKCS8EncodedKeySpec(privateBytes); String serviceAccountCertificates = String.format("{\"%s\" : \"%s\"}", PRIVATE_KEY_ID, certificate); MockHttpTransport mockTransport = new MockHttpTransport.Builder() .setLowLevelHttpResponse( new MockLowLevelHttpResponse().setContent(serviceAccountCertificates)) .build(); this.privateKey = KeyFactory.getInstance("RSA").generatePrivate(spec); this.verifier = new FirebaseTokenVerifier.Builder() .setClock(CLOCK) .setPublicKeysManager( new GooglePublicKeysManager.Builder(mockTransport, FACTORY) .setClock(CLOCK) .setPublicCertsEncodedUrl(FirebaseTokenVerifier.CLIENT_CERT_URL) .build()) .setProjectId(PROJECT_ID) .build(); }
public static Schema decode(String schemaName, String[] compressedFragments) { try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { for (String part : compressedFragments) { bos.write(BaseEncoding.base64Url().decode(part)); } bos.flush(); try (ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray())) { try (InflaterInputStream in = new InflaterInputStream(bin)) { byte[] allBinary = ByteStreams.toByteArray(in); String all = new String(allBinary, StandardCharsets.UTF_8); return new Parser() .parse(all) .getSchema(schemaName); } } } catch (IOException e) { throw new RuntimeException(e); } }
String build() { try { bytes = new ByteArrayOutputStream(); out = new ObjectOutputStream(bytes); // We will generate SHA-1 hash of the call site information based on call site // attributes used in equality comparison, such that if the two call sites are // different their hashes should also be different. write(methodName); write(methodProto); write(bootstrapMethod); write(bootstrapArgs); out.close(); MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(bytes.toByteArray()); return BaseEncoding.base64Url().omitPadding().encode(digest.digest()); } catch (NoSuchAlgorithmException | IOException ex) { throw new Unreachable("Cannot get SHA-1 message digest"); } }
@Override public CompletableFuture<Long> onLogin(ChannelHandlerContext ctx, SocketASK ask) { // 整个消息就是 token ByteString tokenArg = ask.getBody().getArgs(0); if (tokenArg == null) { logger.info("Token arg must be input."); return null; } String token = tokenArg.toStringUtf8(); if (Strings.isNullOrEmpty(token)) { logger.info("Token arg must be input."); return null; } return CompletableFuture.supplyAsync(() -> { String parseToken = new String(BaseEncoding.base64Url().decode(token)); List<String> tokenChars = Splitter.on('|').splitToList(parseToken); return Long.valueOf(tokenArg.toStringUtf8()); }); }
@Override public CompletableFuture<Long> onLogin(ChannelHandlerContext ctx, SocketASK ask) { // 整个消息就是 token ByteString tokenArg = ask.getBody().getArgs(0); if (tokenArg == null) { logger.info("Token arg must be input."); return null; } String token = tokenArg.toStringUtf8(); if (Strings.isNullOrEmpty(token)) { logger.info("Token arg must be input."); return null; } return CompletableFuture.supplyAsync(() -> { String parseToken = new String(BaseEncoding.base64Url().decode(token)); List<String> tokenChars = Splitter.on('|').splitToList(parseToken); Long userId = Long.valueOf(tokenArg.toStringUtf8()); RoomGroup.getRoomManger().onOnline(ctx, userId); return userId; }); }
@NonNull private Map<String, Object> createResponseMap(Parcel reply) { Map<String, Object> data = new HashMap<>(); data.put("message", "reply"); if (reply != null) { try { byte[] marshalled = reply.marshall(); data.put("data", marshalled); if (marshalled != null) { String base64 = BaseEncoding.base64().encode(marshalled).replace("/", ""); data.put("data_base64", base64); } } catch (RuntimeException e) { data.put("info", "activeObject"); } } return data; }
public static ItemStack deserializeItemStack(String itemStackString) { if (itemStackString == null || itemStackString.length() == 0 || itemStackString.equals("null")) return null; ByteArrayInputStream inputStream = new ByteArrayInputStream(BaseEncoding.base64().decode(itemStackString)); NBTTagCompound tagComp; try { tagComp = NBTCompressedStreamTools.a(inputStream); net.minecraft.server.v1_10_R1.ItemStack item = net.minecraft.server.v1_10_R1.ItemStack.createStack(tagComp); ItemStack bukkitItem = CraftItemStack.asBukkitCopy(item); return bukkitItem; } catch (IOException e) { e.printStackTrace(); } return null; }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // retrieve userId and set if (request instanceof HttpServletRequest) { Principal principal = ((HttpServletRequest) request).getUserPrincipal(); if (principal != null) { String ppal = principal.getName(); if (hashAlgorithm == null || "none".equalsIgnoreCase(hashAlgorithm)) { // no hash } else if ("hashcode".equalsIgnoreCase(hashAlgorithm)) { // simply hashcode ppal = Strings.padStart(Integer.toHexString(ppal.hashCode()), 8, '0'); } else { // hexadecimal hash try { MessageDigest digest = MessageDigest.getInstance(hashAlgorithm); ppal = BaseEncoding.base16().encode(digest.digest(ppal.getBytes())); } catch (NoSuchAlgorithmException e) { throw new ServletException(e); } } // add to MDC and request attribute MDC.put(mdcName, ppal); request.setAttribute(attributeName, ppal); } } try { chain.doFilter(request, response); } finally { MDC.remove(mdcName); } }
private String getCertificateThumbprint(String pfxPath, String password) { try { InputStream inStream = new FileInputStream(pfxPath); KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(inStream, password.toCharArray()); String alias = ks.aliases().nextElement(); X509Certificate certificate = (X509Certificate) ks.getCertificate(alias); inStream.close(); MessageDigest sha = MessageDigest.getInstance("SHA-1"); return BaseEncoding.base16().encode(sha.digest(certificate.getEncoded())); } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException ex) { throw new RuntimeException(ex); } }
/** * @param data * @throws ResponseException */ public AuthenticatorAssertionResponse(JsonElement data) throws ResponseException { Gson gson = new Gson(); try { AssertionResponseJson parsedObject = gson.fromJson(data, AssertionResponseJson.class); clientDataBytes = BaseEncoding.base64().decode(parsedObject.clientDataJSON); clientData = gson.fromJson(new String(clientDataBytes), CollectedClientData.class); authDataBytes = BaseEncoding.base64().decode(parsedObject.authenticatorData); authData = AuthenticatorData.decode(authDataBytes); signature = BaseEncoding.base64().decode(parsedObject.signature); userHandle = BaseEncoding.base64().decode(parsedObject.userHandle); } catch (JsonSyntaxException e) { throw new ResponseException("Response format incorrect"); } }
/** * @param data * @throws ResponseException */ public AuthenticatorAttestationResponse(JsonElement data) throws ResponseException { Gson gson = new Gson(); AttestationResponseJson parsedObject = gson.fromJson(data, AttestationResponseJson.class); clientDataBytes = BaseEncoding.base64().decode(parsedObject.clientDataJSON); byte[] attestationObject = BaseEncoding.base64().decode(parsedObject.attestationObject); try { decodedObject = AttestationObject.decode(attestationObject); } catch (CborException e) { throw new ResponseException("Cannot decode attestation object"); } clientData = gson.fromJson(new String(clientDataBytes), CollectedClientData.class); }
/** * @return Encoded JsonObject representation of PublicKeyCredentialDescriptor */ public JsonObject getJsonObject() { JsonObject result = new JsonObject(); result.addProperty("type", type.toString()); result.addProperty("id", BaseEncoding.base64().encode(id)); JsonArray transports = new JsonArray(); if (this.transports != null) { for (AuthenticatorTransport t : this.transports) { JsonPrimitive element = new JsonPrimitive(t.toString()); transports.add(element); } if (transports.size() > 0) { result.add("transports", transports); } } return result; }
/** * @return JsonObject representation of PublicKeyCredentialRequestOptions */ public JsonObject getJsonObject() { JsonObject result = new JsonObject(); result.addProperty("challenge", BaseEncoding.base64().encode(challenge)); if (timeout > 0) { result.addProperty("timeout", timeout); } result.addProperty("rpId", rpId); JsonArray allowList = new JsonArray(); for (PublicKeyCredentialDescriptor credential : this.allowCredentials) { allowList.add(credential.getJsonObject()); } result.add("allowList", allowList); return result; }
/** * Tests concurrently creating an instance of {@link PreimageSha256Condition}. This test validates * the fix for Github issue #40 where construction of this class was not thread-safe. * * @see "https://github.com/interledger/java-crypto-conditions/issues/40" * @see "https://github.com/junit-team/junit4/wiki/multithreaded-code-and-concurrency" */ @Test public void testConstructionUsingMultipleThreads() throws Exception { final Runnable runnableTest = () -> { final PreimageSha256Condition condition = new PreimageSha256Condition(PREIMAGE.getBytes()); assertThat(condition.getType(), is(CryptoConditionType.PREIMAGE_SHA256)); assertThat(condition.getCost(), is(3L)); assertThat(CryptoConditionUri.toUri(condition), is(CONDITION_URI)); assertThat(BaseEncoding.base64().encode(condition.getFingerprint()), is("mDSHbc+wXLFnpcJJU+uljErImxrfV/KPL50JrxB+6PA=")); assertThat( BaseEncoding.base64().encode(condition.constructFingerprintContents(PREIMAGE.getBytes())), is("YWFh")); }; this.runConcurrent(1, runnableTest); this.runConcurrent(runnableTest); }
/** * This test ensures that the supplied private key signs a message correctly. */ @Test public void testSignsCorrectly() throws Exception { final String privKeyPem = rsaJsonTestVector.getPrivateKey(); final RSAPrivateKey privKey = this.buildRsaPrivKey(privKeyPem); rsaJsonTestVector.getCases().stream().forEach(_case -> { try { final byte[] saltHex = BaseEncoding.base16().decode(_case.getSalt().toUpperCase()); rsaSigner.initSign(privKey, new FixedRandom(saltHex)); rsaSigner.update(BaseEncoding.base16().decode(_case.getMessage().toUpperCase())); byte[] rsaSignature = rsaSigner.sign(); assertThat(_case.getSignature().toUpperCase(), is(BaseEncoding.base16().encode(rsaSignature))); } catch (Exception e) { throw new RuntimeException(e); } }); }
/** * This test ensures that the supplied private key signs a message correctly. */ @Test public void testVerifiesCorrectly() throws Exception { final String privKeyPem = rsaJsonTestVector.getPrivateKey(); final RSAPrivateKey privKey = this.buildRsaPrivKey(privKeyPem); rsaJsonTestVector.getCases().stream().forEach(_case -> { try { final byte[] saltHex = BaseEncoding.base16().decode(_case.getSalt().toUpperCase()); rsaSigner.initSign(privKey, new FixedRandom(saltHex)); rsaSigner.update(BaseEncoding.base16().decode(_case.getMessage().toUpperCase())); final byte[] expectedSignatureBytes = BaseEncoding.base16() .decode(_case.getSignature().toUpperCase()); final byte[] actualSignatureByte = rsaSigner.sign(); assertThat(actualSignatureByte, is(expectedSignatureBytes)); } catch (Exception e) { throw new RuntimeException(e); } }); }
/** * This test creates a fulfillment from individual values found in the json test vector file, * then converts the fulfillment to a condition, and then asserts that the binary fulfillment in * JSON test vector matches what is generated by the Java code. */ @Test public void testParseJsonFulfillment() throws Exception { // Reads binary from the JSON test vector, and converts to Java... final Fulfillment controlFulfillment = CryptoConditionReader .readFulfillment(BaseEncoding.base16().decode(testVector.getFulfillment())); // Reads individual components from JSON and assembles a condition... final Condition conditionToFulfill = TestVectorFactory .getConditionFromTestVectorJson(testVector.getJson()); // Assert that the control fulfillment (which we assume is assembled properly since we're not // testing CryptoConditionReader here) can be verifed with the manually-assembled condition. final byte[] messageBytes = BaseEncoding.base16().decode(testVector.getMessage()); assertTrue(controlFulfillment.verify(conditionToFulfill, messageBytes)); }
/** * Tests concurrently creating an instance of {@link Ed25519Sha256Condition}. This test validates * the fix for Github issue #40 where construction of this class was not thread-safe. * * @see "https://github.com/interledger/java-crypto-conditions/issues/40" * @see "https://github.com/junit-team/junit4/wiki/multithreaded-code-and-concurrency" */ @Test public void testConstructionUsingMultipleThreads() throws Exception { final KeyPair keypair = this.constructEd25519KeyPair(); final Runnable runnableTest = () -> { final Ed25519Sha256Condition ed25519Sha256Condition = new Ed25519Sha256Condition( (EdDSAPublicKey) keypair.getPublic()); assertThat(ed25519Sha256Condition.getType(), is(CryptoConditionType.ED25519_SHA256)); assertThat(ed25519Sha256Condition.getCost(), is(131072L)); assertThat(CryptoConditionUri.toUri(ed25519Sha256Condition), is(URI.create( "ni:///sha-256;aJ5kk1zn2qrQQO5QhYZXoGigv0Y5rSafiV3BUM1F9hM?cost=131072&" + "fpt=ed25519-sha-256"))); assertThat(BaseEncoding.base64().encode(ed25519Sha256Condition.getFingerprint()), is("aJ5kk1zn2qrQQO5QhYZXoGigv0Y5rSafiV3BUM1F9hM=")); assertThat(BaseEncoding.base64().encode(ed25519Sha256Condition .constructFingerprintContents((EdDSAPublicKey) keypair.getPublic())), is("MCKAIDauG5fFd65q+wKU6Rg5+nsfkzJ5G58sXVhoGQJfSi8d")); }; this.runConcurrent(1, runnableTest); this.runConcurrent(runnableTest); }
/** * Tests concurrently creating an instance of {@link Ed25519Sha256Condition}. This test validates * the fix for Github issue #40 where construction of this class was not thread-safe. * * @see "https://github.com/interledger/java-crypto-conditions/issues/40" * @see "https://github.com/junit-team/junit4/wiki/multithreaded-code-and-concurrency" */ @Test public void testConstructionUsingMultipleThreads() throws Exception { final RSAPublicKey rsaPublicKey = TestKeyFactory.constructRsaPublicKey(MODULUS); final Runnable runnableTest = () -> { final RsaSha256Condition rsaSha256Condition = new RsaSha256Condition(rsaPublicKey); assertThat(rsaSha256Condition.getType(), is(CryptoConditionType.RSA_SHA256)); assertThat(rsaSha256Condition.getCost(), is(65536L)); assertThat(CryptoConditionUri.toUri(rsaSha256Condition), is(URI.create( "ni:///sha-256;sx-oIG5Op-UVM3s7Mwgrh3ZRgBCF7YT7Ta6yR79pjX8?cost=65536&fpt=rsa-sha-256"))); assertThat(BaseEncoding.base64().encode(rsaSha256Condition.getFingerprint()), is("sx+oIG5Op+UVM3s7Mwgrh3ZRgBCF7YT7Ta6yR79pjX8=")); assertThat(BaseEncoding.base64() .encode(rsaSha256Condition.constructFingerprintContents(rsaPublicKey)), is("MIIBBICCAQDh74sk1vdrCcge13UqomLwRPBKh01DgJ0xzqYS+ZsMl6i0N0FT4+7z1mYWhD4OQcKTJkt" + "xthc9sc8NbNVYxYZXcG/PCX9wTEg+Wcv9/Vs+57yA10DF4PBH8+hfwNdYFXdqbz8jxdxeeXE5poguODNqS" + "l+zYTdiD/NmPbrjKEcoAYYvcvL4eyArnImt181bCgdvfFPjUDn2ftF+yBXltDBcxjGXBo1eblebpt5fTj5" + "X315OBy/yzkxm60UjOXOHUnWWOfAle/V9vVxEP7UVjM4KPTatx7oB8zoLttuyv5idYHES8jRNmT535WPB0" + "2He31falu8s/GhfACtjgkalswm5")); }; this.runConcurrent(1, runnableTest); this.runConcurrent(runnableTest); }
@Test public void test_parse_prefix_sha_256() throws URISyntaxException { URI uri = URI.create( "ni:///sha-256;47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU?cost=0&fpt=prefix-sha-256" + "&subtypes=preimage-sha-256,prefix-sha-256"); Condition condition = CryptoConditionUri.parse(uri); assertEquals(CryptoConditionType.PREFIX_SHA256, condition.getType()); assertEquals("E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855", BaseEncoding.base16().encode(condition.getFingerprint())); assertEquals(0, condition.getCost()); assertTrue(condition instanceof CompoundCondition); CompoundCondition compoundCondition = (CompoundCondition) condition; assertEquals(EnumSet.of(CryptoConditionType.PREIMAGE_SHA256, CryptoConditionType.PREFIX_SHA256), compoundCondition.getSubtypes()); }
/** * The data for this test... */ @Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ // Input Value as a int; Expected byte[] in ASN.1 // 0 {0, BaseEncoding.base16().decode("00")}, // 1 {1, BaseEncoding.base16().decode("01")}, // 2 {2, BaseEncoding.base16().decode("02")}, // 3 {127, BaseEncoding.base16().decode("7F")}, // 4 {128, BaseEncoding.base16().decode("80")}, // 5 {254, BaseEncoding.base16().decode("FE")}, // 6 {255, BaseEncoding.base16().decode("FF")},}); }
/** * Convert base64 string back to a list of items */ public static List<ItemStack> itemsFromBase64(String base64) { if (base64.length() <= 0) return new ArrayList<>(); byte[] uncompressed_binary = decompress(BaseEncoding.base64().decode(base64)); List<ItemStack> ret = new ArrayList<>(); try (ByteArrayInputStream bis = new ByteArrayInputStream(uncompressed_binary); DataInputStream dis = new DataInputStream(bis)) { int n = dis.readByte(); int[] nbt_length = new int[n]; for (int i = 0; i < n; i++) nbt_length[i] = dis.readInt(); for (int i = 0; i < n; i++) { byte[] tmp = new byte[nbt_length[i]]; dis.readFully(tmp); ret.add(itemFromBinary(tmp)); } } catch (IOException | ReflectiveOperationException ex) { throw new RuntimeException(ex); } return ret; }
@Test public void testApplicationSentDataMessage() { String messageData = "{\"id\": 1, \"result\": true}"; String messageDataBase64 = BaseEncoding.base64().encode(messageData.getBytes(UTF_8)); InspectorMessage message = ApplicationSentDataMessage.builder() .applicationId("PID:176") .destination("C1EAD225-D6BC-44B9-9089-2D7CC2D2204C") .messageData(JsonParser.parseObject(messageData)) .build(); String argumentsXml = "<key>WIRApplicationIdentifierKey</key>" + "<string>PID:176</string>" + "<key>WIRDestinationKey</key>" + "<string>C1EAD225-D6BC-44B9-9089-2D7CC2D2204C</string>" + "<key>WIRMessageDataKey</key>" + "<data>" + messageDataBase64 + "</data>"; testPlistConversion(message, argumentsXml); }
/** Parsers a bytes value out of the input. */ static ByteString parseBytes(JsonParser parser) throws IOException { JsonToken json = parser.currentToken(); byte[] result = null; try { // Use Guava to decode base64, which can handle more variants than Jackson. result = BaseEncoding.base64() .decode( CharBuffer.wrap( parser.getTextCharacters(), parser.getTextOffset(), parser.getTextLength())); } catch (IllegalArgumentException e) { // Fall through } if (result == null) { throw new InvalidProtocolBufferException("Not a bytes value: " + json); } return ByteString.copyFrom(result); }
@Override protected Object postprocessParsedValue(final String textContent) { BaseEncoding en = BaseEncoding.base64(); byte[] decode = en.decode(textContent); List<String> parsed = Lists.newArrayListWithCapacity(decode.length); for (byte b : decode) { parsed.add(Byte.toString(b)); } return parsed; }
@Test public void testPersistenceKey() { String name = "myApp"; FirebaseApp firebaseApp = FirebaseApp.initializeApp(OPTIONS, name); String persistenceKey = firebaseApp.getPersistenceKey(); assertEquals(name, new String(BaseEncoding.base64Url().omitPadding().decode(persistenceKey), UTF_8)); }
/** * */ public DecodeTest() { String pwd = "Change#@$%*Me!"; String bar = BaseEncoding.base64().encode(pwd.getBytes()); byte [] foo = BaseEncoding.base64().decode(bar); String creds = new String(foo); System.out.println(creds); }
private List<String> processDsl() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DeflaterOutputStream dos = new DeflaterOutputStream(bos); dos.write(dsl.getBytes(StandardCharsets.UTF_8)); dos.flush(); dos.close(); bos.flush(); bos.close(); String encoded = BaseEncoding.base64Url().encode(bos.toByteArray()); return split(encoded); }
@Override public void addAuth(HttpRequestBase request, CookieStore cookieStore) { String basicAuthUnencoded = String.format("%s:%s", username, password); String basicAuth = "Basic " + BaseEncoding.base64().encode(basicAuthUnencoded.getBytes()); request.addHeader("Authorization", basicAuth); }
private byte[] getBytes(CreateArkTransactionRequest createArkTransactionRequest, String senderPublicKey) { ByteBuffer buffer = ByteBuffer.allocate(1000); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.put(createArkTransactionRequest.getType()); buffer.putInt((int) createArkTransactionRequest.getTimestamp()); // todo: fix downcast buffer.put(BaseEncoding.base16().lowerCase().decode(senderPublicKey)); if(createArkTransactionRequest.getRecipientId() != null){ buffer.put(Base58.decodeChecked(createArkTransactionRequest.getRecipientId())); } else { buffer.put(new byte[21]); } if (createArkTransactionRequest.getVendorField() != null) { byte[] vbytes = createArkTransactionRequest.getVendorField().getBytes(); if(vbytes.length < 65){ buffer.put(vbytes); buffer.put(new byte[64-vbytes.length]); } } else { buffer.put(new byte[64]); } buffer.putLong(createArkTransactionRequest.getAmount()); buffer.putLong(createArkTransactionRequest.getFee()); byte[] outBuffer = new byte[buffer.position()]; buffer.rewind(); buffer.get(outBuffer); return outBuffer; }
public static String[] mapHttpSourceTestToCsvRow(HttpSourceTest httpSourceTest) { return new String[]{ httpSourceTest.getUrl(), httpSourceTest.getSource(), BaseEncoding.base64().encode(httpSourceTest.getHtml().getBytes(Charsets.UTF_8)), Objects.toString(httpSourceTest.getUrlAccepted(), "false"), Strings.nullToEmpty(httpSourceTest.getTitle()), Strings.nullToEmpty(httpSourceTest.getText()), Strings.nullToEmpty(httpSourceTest.getDate()) }; }
public static HttpSourceTest mapCsvRowToHttpSourceTest(String[] row, Map<String, Integer> columnIndexes) { HttpSourceTest hst = new HttpSourceTest(); hst.setUrl(Strings.emptyToNull(row[columnIndexes.get("url")])); hst.setSource(Strings.emptyToNull(row[columnIndexes.get("source")])); hst.setHtml(new String(BaseEncoding.base64().decode(row[columnIndexes.get("html")]), Charsets.UTF_8)); hst.setUrlAccepted(Boolean.parseBoolean(row[columnIndexes.get("url_accepted")])); hst.setTitle(Strings.emptyToNull(row[columnIndexes.get("title")])); hst.setText(Strings.emptyToNull(row[columnIndexes.get("text")])); hst.setDate(Strings.emptyToNull(row[columnIndexes.get("date")])); return hst; }
@Override public void put ( final IoBuffer data, String value ) { value = value.replaceAll ( "\\s", "" ); value = value.toUpperCase (); data.put ( BaseEncoding.base16 ().decode ( value ) ); }
/** * Encodes the json policy and signs it using the app secret. * Do not include the app secret in client-side code. */ public Policy build(String appSecret) { Gson gson = new Gson(); HashFunction hashFunction = Hashing.hmacSha256(appSecret.getBytes(Charsets.UTF_8)); String jsonPolicy = gson.toJson(this); String encodedPolicy = BaseEncoding.base64Url().encode(jsonPolicy.getBytes(Charsets.UTF_8)); String signature = hashFunction.hashString(encodedPolicy, Charsets.UTF_8).toString(); return new Policy(encodedPolicy, signature); }
public void testRoundTrip() { for (ExpectedHashCode expected : expectedHashCodes) { String string = HashCode.fromBytes(expected.bytes).toString(); assertEquals(expected.toString, string); assertEquals( expected.toString, HashCode.fromBytes( BaseEncoding.base16().lowerCase().decode(string)).toString()); } }
public BinaryLiteral(Optional<NodeLocation> location, String value) { super(location); requireNonNull(value, "value is null"); String hexString = WHITESPACE_PATTERN.matcher(value).replaceAll("").toUpperCase(); if (NOT_HEX_DIGIT_PATTERN.matcher(hexString).matches()) { throw new ParsingException("Binary literal can only contain hexadecimal digits", location.get()); } if (hexString.length() % 2 != 0) { throw new ParsingException("Binary literal must contain an even number of digits", location.get()); } this.value = Slices.wrappedBuffer(BaseEncoding.base16().decode(hexString)); }
@Bean public Cryptor cryptor() { if (config.getSalt() != null) { return new Cryptor(BaseEncoding.base16().lowerCase().decode(config.getSalt())); } return new Cryptor(config.getBaseDir()); }
@Override public byte[] adminKubeConfigContent() { if (this.inner().accessProfiles() == null || this.inner().accessProfiles().clusterAdmin() == null || this.inner().accessProfiles().clusterAdmin().kubeConfig() == null) { return new byte[0]; } else { return BaseEncoding.base64().decode(this.inner().accessProfiles().clusterAdmin().kubeConfig()); } }
@Override public byte[] userKubeConfigContent() { if (this.inner().accessProfiles() == null || this.inner().accessProfiles().clusterUser() == null || this.inner().accessProfiles().clusterUser().kubeConfig() == null) { return new byte[0]; } else { return BaseEncoding.base64().decode(this.inner().accessProfiles().clusterUser().kubeConfig()); } }