com.google.common.io.BaseEncoding Java Examples

The following examples show how to use com.google.common.io.BaseEncoding. 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: PubsubIT.java    From async-google-pubsub-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testPullSingle() throws IOException, ExecutionException, InterruptedException {
  // Create topic and subscription
  pubsub.createTopic(PROJECT, TOPIC).get();
  pubsub.createSubscription(PROJECT, SUBSCRIPTION, TOPIC).get();

  // Publish a message
  final String data = BaseEncoding.base64().encode("hello world".getBytes("UTF-8"));
  final Message message = Message.of(data);
  final List<String> ids = pubsub.publish(PROJECT, TOPIC, message).get();
  final String id = ids.get(0);
  final List<ReceivedMessage> response = pubsub.pull(PROJECT, SUBSCRIPTION, false).get();

  // Verify received message
  assertThat(response.size(), is(1));
  assertThat(response.get(0).message().data(), is(data));
  assertThat(response.get(0).message().messageId().get(), is(id));
  assertThat(response.get(0).message().publishTime().get(), is(notNullValue()));
  assertThat(response.get(0).ackId(), not(isEmptyOrNullString()));

  // Modify ack deadline
  pubsub.modifyAckDeadline(PROJECT, SUBSCRIPTION, 30, response.get(0).ackId()).get();

  // Ack message
  pubsub.acknowledge(PROJECT, SUBSCRIPTION, response.get(0).ackId()).get();
}
 
Example #2
Source File: HostNameSslBindingImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
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);
    }
}
 
Example #3
Source File: Header.java    From elastic-load-balancing-tools with Apache License 2.0 6 votes vote down vote up
private void verifyAddressSize(byte[] address) {
// CHECKSTYLE:ON
    int addressLength = address.length;
    switch (addressFamily) {
    case AF_UNSPEC:
    case AF_INET:
    case AF_INET6:
        if (addressLength != addressFamily.getAddressSize()) {
            throw new InvalidHeaderException("For the address family " + addressFamily +
                    " expected address size " + addressFamily.getAddressSize() + " but got "
                    + addressLength + " for the address "
                    + BaseEncoding.base16().lowerCase().encode(address));
        }
        break;
    case AF_UNIX:
        // Unix address can be smaller than the reserved space
        if (addressLength > addressFamily.getAddressSize()
            || addressLength == 0) {
            throw new InvalidHeaderException("Invalid size " + addressLength +
                    " of the Unix address "
                    + BaseEncoding.base16().lowerCase().encode(address));
        }
        break;
    }
}
 
Example #4
Source File: ValidateHeaderIsBase64Encoded.java    From sfs with Apache License 2.0 6 votes vote down vote up
@Override
public SfsRequest call(SfsRequest httpServerRequest) {
    MultiMap headers = httpServerRequest.headers();

    String value = headers.get(headerName);
    if (value != null) {
        boolean failed = false;
        BaseEncoding baseEncoding = base64();
        try {
            byte[] decoded = baseEncoding.decode(value);
            if (decoded == null || !value.equals(baseEncoding.encode(decoded))) {
                failed = true;
            }
        } catch (Throwable e) {
            // do nothing
        }
        if (failed) {
            JsonObject jsonObject = new JsonObject()
                    .put("message", format("%s must be Base64 encoded", headerName));

            throw new HttpRequestValidationException(HTTP_BAD_REQUEST, jsonObject);
        }
    }
    return httpServerRequest;
}
 
Example #5
Source File: FirebaseChannel.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Create a secure JWT token for the given userId. */
public String createFirebaseToken(Game game, String userId) {
  final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
  final BaseEncoding base64 = BaseEncoding.base64();

  String header = base64.encode("{\"typ\":\"JWT\",\"alg\":\"RS256\"}".getBytes());

  // Construct the claim
  String channelKey = game.getChannelKey(userId);
  String clientEmail = appIdentity.getServiceAccountName();
  long epochTime = System.currentTimeMillis() / 1000;
  long expire = epochTime + 60 * 60; // an hour from now

  Map<String, Object> claims = new HashMap<String, Object>();
  claims.put("iss", clientEmail);
  claims.put("sub", clientEmail);
  claims.put("aud", IDENTITY_ENDPOINT);
  claims.put("uid", channelKey);
  claims.put("iat", epochTime);
  claims.put("exp", expire);

  String payload = base64.encode(new Gson().toJson(claims).getBytes());
  String toSign = String.format("%s.%s", header, payload);
  AppIdentityService.SigningResult result = appIdentity.signForApp(toSign.getBytes());
  return String.format("%s.%s", toSign, base64.encode(result.getSignature()));
}
 
Example #6
Source File: AbstractGoogleClientRequestTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testReturnRawInputStream_True() throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(final String method, final String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          return new MockLowLevelHttpResponse().setContentEncoding("gzip").setContent(new ByteArrayInputStream(
              BaseEncoding.base64()
                  .decode("H4sIAAAAAAAAAPNIzcnJV3DPz0/PSVVwzskvTVEILskvSkxPVQQA/LySchsAAAA=")));
        }
      };
    }
  };
  MockGoogleClient client = new MockGoogleClient.Builder(transport, ROOT_URL, SERVICE_PATH,
      JSON_OBJECT_PARSER, null).setApplicationName(
      "Test Application").build();
  MockGoogleClientRequest<String> request = new MockGoogleClientRequest<String>(
      client, HttpMethods.GET, URI_TEMPLATE, null, String.class);
  request.setReturnRawInputStream(true);
  InputStream inputStream = request.executeAsInputStream();
  // The response will not be wrapped due to setReturnRawInputStream(true)
  assertTrue(inputStream instanceof ByteArrayInputStream);
}
 
Example #7
Source File: UserDataBuilder.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private String build(Platform cloudPlatform, byte[] cbSshKeyDer, String sshUser,
        PlatformParameters params, String saltBootPassword, String cbCert, CcmParameters ccmParameters, ProxyConfig proxyConfig) {
    Map<String, Object> model = new HashMap<>();
    model.put("cloudPlatform", cloudPlatform.value());
    model.put("platformDiskPrefix", params.scriptParams().getDiskPrefix());
    model.put("platformDiskStartLabel", params.scriptParams().getStartLabel());
    model.put("gateway", true);
    model.put("signaturePublicKey", BaseEncoding.base64().encode(cbSshKeyDer));
    model.put("sshUser", sshUser);
    model.put("customUserData", userDataBuilderParams.getCustomData());
    model.put("saltBootPassword", saltBootPassword);
    model.put("cbCert", cbCert);
    CcmParameters.addToTemplateModel(ccmParameters, model);
    extendModelWithProxyParams(proxyConfig, model);
    return build(model);
}
 
Example #8
Source File: DuoCookie.java    From guacamole-client with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the base64-encoded string representation of this DuoCookie. The
 * format used is identical to that required by the Duo service: the
 * username, integration key, and expiration timestamp separated by pipe
 * symbols ("|") and encoded with base64.
 *
 * @return
 *     The base64-encoded string representation of this DuoCookie.
 */
@Override
public String toString() {

    try {

        // Separate each cookie field with pipe symbols
        String data = username + "|" + integrationKey + "|" + expires;

        // Encode resulting cookie string with base64
        return BaseEncoding.base64().encode(data.getBytes("UTF-8"));

    }

    // Throw hard errors if standard pieces of Java are missing
    catch (UnsupportedEncodingException e) {
        throw new UnsupportedOperationException("Unexpected lack of UTF-8 support.", e);
    }

}
 
Example #9
Source File: MongoDBArtifactStoreTest.java    From hawkbit-extensions with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Verfies that artifacts with equal binary content are only stored once.")
public void storeSameArtifactMultipleTimes() throws NoSuchAlgorithmException, IOException {

    final byte[] bytes = new byte[128];
    new Random().nextBytes(bytes);

    final MessageDigest mdSHA1 = MessageDigest.getInstance("SHA1");
    final MessageDigest mdSHA256 = MessageDigest.getInstance("SHA-256");
    final MessageDigest mdMD5 = MessageDigest.getInstance("MD5");
    final DbArtifactHash hash = new DbArtifactHash(BaseEncoding.base16().lowerCase().encode(mdSHA1.digest(bytes)),
            BaseEncoding.base16().lowerCase().encode(mdMD5.digest(bytes)),
            BaseEncoding.base16().lowerCase().encode(mdSHA256.digest(bytes)));

    final AbstractDbArtifact artifact1 = storeArtifact(TENANT, "file1.txt", new ByteArrayInputStream(bytes), mdSHA1,
            mdMD5, hash);
    final AbstractDbArtifact artifact2 = storeArtifact(TENANT, "file2.bla", new ByteArrayInputStream(bytes), mdSHA1,
            mdMD5, hash);
    assertThat(artifact1.getArtifactId()).isEqualTo(artifact2.getArtifactId());

}
 
Example #10
Source File: TransportFrameUtil.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * Transform HTTP/2-compliant headers to the raw serialized format which can be deserialized by
 * metadata marshallers. It decodes the Base64-encoded binary headers.
 *
 * <p>Warning: This function may partially modify the headers in place by modifying the input
 * array (but not modifying any single byte), so the input reference {@code http2Headers} can not
 * be used again.
 *
 * @param http2Headers the interleaved keys and values of HTTP/2-compliant headers
 * @return the interleaved keys and values in the raw serialized format
 */
@CheckReturnValue
public static byte[][] toRawSerializedHeaders(byte[][] http2Headers) {
  for (int i = 0; i < http2Headers.length; i += 2) {
    byte[] key = http2Headers[i];
    byte[] value = http2Headers[i + 1];
    if (endsWith(key, binaryHeaderSuffixBytes)) {
      // Binary header
      for (int idx = 0; idx < value.length; idx++) {
        if (value[idx] == (byte) ',') {
          return serializeHeadersWithCommasInBin(http2Headers, i);
        }
      }
      byte[] decodedVal = BaseEncoding.base64().decode(new String(value, US_ASCII));
      http2Headers[i + 1] = decodedVal;
    } else {
      // Non-binary header
      // Nothing to do, the value is already in the right place.
    }
  }
  return http2Headers;
}
 
Example #11
Source File: AuthenticatorAttestationResponse.java    From webauthndemo with Apache License 2.0 6 votes vote down vote up
/**
 * @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, StandardCharsets.UTF_8),
      CollectedClientData.class);
  transports = parsedObject.transports;
}
 
Example #12
Source File: HTTPJwtAuthenticatorTest.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
@Test
public void testRolesMissing() throws Exception {



    Settings settings = Settings.builder()
            .put("signing_key", BaseEncoding.base64().encode(secretKey))
            .put("roles_key", "roles")
            .build();

    String jwsToken = Jwts.builder()
            .setSubject("Leonard McCoy")
            .signWith(SignatureAlgorithm.HS512, secretKey).compact();

    HTTPJwtAuthenticator jwtAuth = new HTTPJwtAuthenticator(settings, null);
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Authorization", jwsToken);

    AuthCredentials creds = jwtAuth.extractCredentials(new FakeRestRequest(headers, new HashMap<String, String>()), null);
    Assert.assertNotNull(creds);
    Assert.assertEquals("Leonard McCoy", creds.getUsername());
    Assert.assertEquals(0, creds.getBackendRoles().size());
}
 
Example #13
Source File: StreamPacketFixturesTest.java    From quilt with Apache License 2.0 6 votes vote down vote up
/**
 * When the test is run, this method reads the local fixtures resource and performs a checksum on the file contents to
 * ensure the integrity of the file and compares it with the expected {@code stream.packetFixtures.checksum} value in
 * the properties configuration located at {@code fixtures.properties}.
 *
 * <p>This test is present to ensure that in case the file is updated locally, we also update the corresponding
 * checksum of the file.</p>
 *
 * @return {@code false} if the fixtures have changed locally, else {@code true}.
 */
private static boolean checkLocalFixtureFileState() {
  Properties properties = readProperties();
  String expectedCheckSum = (String) properties.get("stream.packetFixtures.checksum");
  String fileName = (String) properties.get("stream.packetFixtures.fileName");

  try {
    Path path = Paths.get(StreamPacketFixturesTest.class.getClassLoader().getResource(fileName).toURI());
    byte[] buffer = Files.readAllBytes(path);
    Objects.requireNonNull(buffer);
    String computedCheckSum = BaseEncoding.base16().encode(checksum(buffer)).toLowerCase();
    return computedCheckSum.equals(expectedCheckSum);
  } catch (URISyntaxException | IOException e) {
    e.printStackTrace();
  }

  return false;
}
 
Example #14
Source File: HttpDownloaderTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddAuthenticationHeader() throws IOException, URISyntaxException {

  Capture<String> capturedAuth = EasyMock.newCapture();

  HttpURLConnection connection = EasyMock.createNiceMock(HttpsURLConnection.class);
  EasyMock.expect(connection.getResponseCode()).andStubReturn(HTTP_FORBIDDEN);
  connection.addRequestProperty(eq("Authorization"), capture(capturedAuth));
  EasyMock.expectLastCall();
  EasyMock.replay(connection);

  HttpDownloader downloader = getDownloader(connection);
  PasswordAuthentication credentials = new PasswordAuthentication("foo", "bar".toCharArray());
  boolean result =
      downloader.fetch(
          eventBus, new URI("https://example.com"), Optional.of(credentials), neverUsed);
  assertFalse(result);

  EasyMock.verify(connection);

  Matcher m = Pattern.compile("^Basic (.*)$").matcher(capturedAuth.getValue());
  assertTrue(m.matches());
  assertEquals(
      "foo:bar", new String(BaseEncoding.base64().decode(m.group(1)), StandardCharsets.UTF_8));
}
 
Example #15
Source File: TestDomainTranslator.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test
public void testExpressionConstantFolding()
{
    FunctionCall fromHex = new FunctionCallBuilder(metadata)
            .setName(QualifiedName.of("from_hex"))
            .addArgument(VARCHAR, stringLiteral("123456"))
            .build();
    Expression originalExpression = comparison(GREATER_THAN, C_VARBINARY.toSymbolReference(), fromHex);
    ExtractionResult result = fromPredicate(originalExpression);
    assertEquals(result.getRemainingExpression(), TRUE_LITERAL);
    Slice value = Slices.wrappedBuffer(BaseEncoding.base16().decode("123456"));
    assertEquals(result.getTupleDomain(), withColumnDomains(ImmutableMap.of(C_VARBINARY, Domain.create(ValueSet.ofRanges(Range.greaterThan(VARBINARY, value)), false))));

    Expression expression = toPredicate(result.getTupleDomain());
    assertEquals(expression, comparison(GREATER_THAN, C_VARBINARY.toSymbolReference(), varbinaryLiteral(value)));
}
 
Example #16
Source File: MinHash.java    From minhash with Apache License 2.0 6 votes vote down vote up
/**
 * Calculates MinHash value.
 * 
 * @param analyzer analyzer to parse a text
 * @param text a target text
 * @return MinHash value
 * @throws IOException
 */
public static byte[] calculate(final Analyzer analyzer, final String text)
        throws IOException {
    byte[] value = null;
    try (TokenStream stream = analyzer.tokenStream("minhash", text)) {
        final CharTermAttribute termAtt = stream
                .addAttribute(CharTermAttribute.class);
        stream.reset();
        if (stream.incrementToken()) {
            final String minhashValue = termAtt.toString();
            value = BaseEncoding.base64().decode(minhashValue);
        }
        stream.end();
    }
    return value;
}
 
Example #17
Source File: gson_common_serializer.java    From AndroidWallet with GNU General Public License v3.0 5 votes vote down vote up
@Override
public JsonElement serialize(ByteBuffer src,
                             Type typeOfSrc,
                             JsonSerializationContext context) {
    BaseEncoding encoding = BaseEncoding.base16().lowerCase();

    return new JsonPrimitive(encoding.encode(src.array()));
}
 
Example #18
Source File: HadoopUtils.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Serialize a {@link Writable} object into a string.
 *
 * @param writable the {@link Writable} object to be serialized
 * @return a string serialized from the {@link Writable} object
 * @throws IOException if there's something wrong with the serialization
 */
public static String serializeToString(Writable writable) throws IOException {
  try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream)) {
    writable.write(dataOutputStream);
    return BaseEncoding.base64().encode(byteArrayOutputStream.toByteArray());
  }
}
 
Example #19
Source File: SafeUrls.java    From safe-html-types with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@code data:text/html} URL whose content is populated from the given
 * {@code SafeHtml} object.
 *
 * <p>The resulting {@code data}-scheme URL's content is UTF-8-encoded, and further encoded using
 * base-64 transfer encoding.
 *
 * @see http://tools.ietf.org/html/rfc2397
 * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs
 */
public static SafeUrl createHtmlDataUrlBase64(SafeHtml html) {
  try {
    String dataUrl =
        "data:text/html;charset=UTF-8;base64,"
            + BaseEncoding.base64().encode(html.getSafeHtmlString().getBytes("UTF-8"));
    return create(dataUrl);
  } catch (UnsupportedEncodingException e) {
    // Should never happen.  We use getBytes(String) instead of getBytes(CharSet) because
    // there's no java.nio.charset.StandardCharsets in older Android SDKs.
    throw new RuntimeException(e);
  }
}
 
Example #20
Source File: GAEService.java    From security-samples with Apache License 2.0 5 votes vote down vote up
public String getSignResponseFromServer(AuthenticatorAssertionResponse response) {
    Log.d(TAG, "getSignResponseFromServer");
    try {
        if (fido2Service == null) {
            return null;
        }
        JSONObject responseJson = new JSONObject();
        String clientDataJSON = new String(response.getClientDataJSON(), "UTF-8");
        String authenticatorData = BaseEncoding.base64().encode(response.getAuthenticatorData());
        String credentialId = BaseEncoding.base64Url().encode(response.getKeyHandle());
        String signature = BaseEncoding.base64().encode(response.getSignature());
        responseJson.put(KEY_CLIENT_DATA_JSON, clientDataJSON);
        responseJson.put(KEY_AUTHENTICATOR_DATA, authenticatorData);
        responseJson.put(KEY_CREDENTIAL_ID, credentialId);
        responseJson.put(KEY_SIGNATURE, signature);

        // insert sessionId for the authenticated credential ID into result data in JSON format,
        // and pass it back to server.
        String sessionId = sessionIds.get(BaseEncoding.base64Url().encode(response.getKeyHandle()));
        responseJson.put(KEY_SESSION_ID, sessionId);

        List<String> signResponseContent =
                fido2Service.processSignResponse(responseJson.toString()).execute().getItems();
        if (signResponseContent == null || signResponseContent.isEmpty()) {
            Log.i(TAG, "signResponseContent is null or empty");
        } else {
            Log.i(TAG, "signResponseContent " + signResponseContent.get(0));
            JSONObject credential = new JSONObject(signResponseContent.get(0));
            // return string value of the authenticated credential
            return credential.toString();
        }

    } catch (IOException | JSONException e) {
        Log.e(TAG, "Error processing sign response", e);
    }

    return null;
}
 
Example #21
Source File: MrdExport.java    From bitshares_wallet with MIT License 5 votes vote down vote up
private static byte[] base64UrlDecode(String base64String) throws DecodingException {
   try {
      return BaseEncoding.base64Url().decode(base64String);
   } catch (IllegalArgumentException e) {
      throw new DecodingException();
   }
}
 
Example #22
Source File: BinaryLiteral.java    From presto with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example #23
Source File: compact_signature.java    From AndroidWallet with GNU General Public License v3.0 5 votes vote down vote up
@Override
public JsonElement serialize(compact_signature src, Type typeOfSrc,
                             JsonSerializationContext context) {
    BaseEncoding encoding = BaseEncoding.base16().lowerCase();

    return new JsonPrimitive(encoding.encode(src.data));
}
 
Example #24
Source File: CertificateCredentialImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
CertificateCredentialImpl(String name, HasCredential<?> parent) {
    super(new KeyCredentialInner()
            .withUsage("Verify")
            .withCustomKeyIdentifier(BaseEncoding.base64().encode(name.getBytes()).getBytes())
            .withStartDate(DateTime.now())
            .withEndDate(DateTime.now().plusYears(1)));
    this.name = name;
    this.parent = parent;
}
 
Example #25
Source File: BasicAuthenticationCredentialsInterceptor.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
@Override
public Response intercept(Chain chain) throws IOException {
    String auth = credentials.getUserName() + ":" + credentials.getPassword();
    auth = BaseEncoding.base64().encode(auth.getBytes("UTF8"));
    Request newRequest = chain.request().newBuilder()
            .header("Authorization", "Basic " + auth)
            .build();
    return chain.proceed(newRequest);
}
 
Example #26
Source File: Stratum1EthProxyProtocol.java    From besu with Apache License 2.0 5 votes vote down vote up
private void sendNewWork(final StratumConnection conn, final Object id) {
  byte[] dagSeed = DirectAcyclicGraphSeed.dagSeed(currentInput.getBlockNumber());
  final String[] result = {
    "0x" + BaseEncoding.base16().lowerCase().encode(currentInput.getPrePowHash()),
    "0x" + BaseEncoding.base16().lowerCase().encode(dagSeed),
    currentInput.getTarget().toHexString()
  };
  JsonRpcSuccessResponse req = new JsonRpcSuccessResponse(id, result);
  try {
    conn.send(mapper.writeValueAsString(req) + "\n");
  } catch (JsonProcessingException e) {
    LOG.debug(e.getMessage(), e);
  }
}
 
Example #27
Source File: FixedLengthBlobAccessor.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void put ( final IoBuffer data, String value )
{
    value = value.replaceAll ( "\\s", "" );
    value = value.toUpperCase ();
    data.put ( BaseEncoding.base16 ().decode ( value ) );
}
 
Example #28
Source File: SecurityModule.java    From emodb with Apache License 2.0 5 votes vote down vote up
/**
 * Supplier for generating uniquey IDs for API keys.  Note that, critically, the values returned will never
 * collide with the reserved IDs from {@link #provideAuthIdentityManagerWithDefaults(String, String, Optional, Set, AuthIdentityManager)}
 */
@Provides
@Singleton
@IdentityIdSupplier
Supplier<String> provideIdentityIdSupplier() {
    return () -> {
        // This is effectively a TimeUUID but condensed to a slightly smaller String representation.
        UUID uuid = TimeUUIDs.newUUID();
        byte[] b = new byte[16];
        System.arraycopy(Longs.toByteArray(uuid.getMostSignificantBits()), 0, b, 0, 8);
        System.arraycopy(Longs.toByteArray(uuid.getLeastSignificantBits()), 0, b, 8, 8);
        return BaseEncoding.base32().omitPadding().encode(b);
    };
}
 
Example #29
Source File: StashSplit.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    return BaseEncoding.base64Url().omitPadding().encode(
            new StringBuilder(_table.length() + _key.length() + 10)
                    .append(_table).append("\n")
                    .append(_key).append("\n")
                    .append(_size)
                    .reverse()
                    .toString()
                    .getBytes(Charsets.UTF_8));
}
 
Example #30
Source File: JacksonTokenManager.java    From dynein with Apache License 2.0 5 votes vote down vote up
@Override
public JobTokenPayload decodeToken(String token) throws InvalidTokenException {
  try {
    return objectMapper.readValue(BaseEncoding.base64Url().decode(token), JobTokenPayload.class);
  } catch (IOException e) {
    throw new InvalidTokenException(e);
  }
}