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: 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 #2
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 #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: 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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
Source File: CronetClientStream.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Override
public void writeHeaders(Metadata metadata, byte[] payload) {
  startCallback.run();

  BidirectionalStreamCallback callback = new BidirectionalStreamCallback();
  String path = url;
  if (payload != null) {
    path += "?" + BaseEncoding.base64().encode(payload);
  }
  BidirectionalStream.Builder builder =
      streamFactory.newBidirectionalStreamBuilder(path, callback, executor);
  if (payload != null) {
    builder.setHttpMethod("GET");
  } else if (idempotent) {
    builder.setHttpMethod("PUT");
  }
  if (delayRequestHeader) {
    builder.delayRequestHeadersUntilFirstFlush(true);
  }
  if (annotation != null) {
    ((ExperimentalBidirectionalStream.Builder) builder).addRequestAnnotation(annotation);
  }
  if (annotations != null) {
    for (Object o : annotations) {
      ((ExperimentalBidirectionalStream.Builder) builder).addRequestAnnotation(o);
    }
  }
  setGrpcHeaders(builder);
  stream = builder.build();
  stream.start();
}
 
Example #19
Source File: CredentialEncrypter.java    From emodb with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the provided String _could_ be encrypted credentials, even if it can't be decrypted
 * by a specific instance.
 */
public static boolean isPotentiallyEncryptedString(String string) {
    checkNotNull(string, "string");

    // String is base64 encoded
    byte[] encryptedBytes;
    try {
        encryptedBytes = BaseEncoding.base64().omitPadding().decode(string);
    } catch (IllegalArgumentException e) {
        return false;
    }

    return isPotentiallyEncryptedBytes(encryptedBytes);
}
 
Example #20
Source File: EncrypterImpl.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
@Override
public String encrypt(String data) {
  try {
    Cipher cipher;
    switch (transformation) {
      case AES_CBC_NOPADDING:
        cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, key, generateIv(cipher));
        break;
      case RSA_ECB_PKCS1:
        cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);        
        break;
      default:
        throw new AssertionError("How could this happen...");
    }
    // we use a salt the size of the first block
    // so that we don't need to know IV for AES/CBC
    byte[] salt = new byte[cipher.getBlockSize()];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.nextBytes(salt);
    cipher.update(salt);
    byte[] encrypted = cipher.doFinal(data.getBytes(Charsets.UTF_8));
    return BaseEncoding.base64Url().encode(encrypted);
  } catch (BadPaddingException
      | IllegalBlockSizeException
      | InvalidAlgorithmParameterException
      | InvalidKeyException
      | NoSuchAlgorithmException
      | NoSuchPaddingException e) {
    monitor.severe(() -> format("Exception encrypting data, length: %s", data.length()), e);
    throw new RuntimeException(e);
  }
}
 
Example #21
Source File: GAEService.java    From android-fido 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 #22
Source File: AbstrDockerCmdExec.java    From docker-java with Apache License 2.0 5 votes vote down vote up
protected String registryAuth(@Nonnull AuthConfig authConfig) {
    try {
        return BaseEncoding.base64Url().encode(dockerClientConfig.getObjectMapper().writeValueAsString(authConfig).getBytes());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #23
Source File: RepositoryFunction.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Convert to a @{link com.google.devtools.build.lib.skyframe.FileValue} to a String appropriate
 * for placing in a repository marker file.
 *
 * @param fileValue The value to convert. It must correspond to a regular file.
 */
public static String fileValueToMarkerValue(FileValue fileValue) throws IOException {
  Preconditions.checkArgument(fileValue.isFile() && !fileValue.isSpecialFile());
  // Return the file content digest in hex. fileValue may or may not have the digest available.
  byte[] digest = ((RegularFileStateValue) fileValue.realFileStateValue()).getDigest();
  if (digest == null) {
    digest = fileValue.realRootedPath().asPath().getDigest();
  }
  return BaseEncoding.base16().lowerCase().encode(digest);
}
 
Example #24
Source File: ArrayByteSourceTest.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Test
public void test_base64String() {
  byte[] bytes = new byte[] {65, 66, 67, 99};
  @SuppressWarnings("deprecation")
  String base64 = BaseEncoding.base64().encode(bytes);
  ArrayByteSource test = ArrayByteSource.copyOf(bytes);
  assertThat(test.toBase64String()).isEqualTo(base64);
  ArrayByteSource roundtrip = ArrayByteSource.fromBase64(base64);
  assertThat(roundtrip).isEqualTo(test);
  assertThat(test.toBase64String()).isEqualTo(test.toBase64().readUtf8());
}
 
Example #25
Source File: PasswordCredentialImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
PasswordCredentialImpl(String name, HasCredential<?> parent) {
    super(new PasswordCredentialInner()
            .withCustomKeyIdentifier(BaseEncoding.base64().encode(name.getBytes()))
            .withStartDate(DateTime.now())
            .withEndDate(DateTime.now().plusYears(1)));
    this.name = name;
    this.parent = parent;
}
 
Example #26
Source File: Sha512Hasher.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
/** Creates a SHA-512 hash of the given String. */
@VisibleForTesting
static String sha512(final String input) {
  try {
    return BaseEncoding.base16()
        .encode(MessageDigest.getInstance(SHA_512).digest(input.getBytes(StandardCharsets.UTF_8)))
        .toLowerCase();
  } catch (final NoSuchAlgorithmException e) {
    throw new IllegalStateException(SHA_512 + " is not supported!", e);
  }
}
 
Example #27
Source File: TlsSecurityService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void setClientKeys(SecurityConfig securityConfig, KeyPair identity, KeyPair signKey) {
    X509Certificate cert = PkiUtil.cert(identity, "cloudbreak", signKey);

    String clientPrivateKey = PkiUtil.convert(identity.getPrivate());
    String clientCert = PkiUtil.convert(cert);

    securityConfig.setClientKey(BaseEncoding.base64().encode(clientPrivateKey.getBytes()));
    securityConfig.setClientCert(BaseEncoding.base64().encode(clientCert.getBytes()));
}
 
Example #28
Source File: TinkUtils.java    From JavaSecurity with Apache License 2.0 5 votes vote down vote up
public static void printHybridEncryptionData(KeysetHandle privateKeysetHandle, KeysetHandle publicKeysetHandle, String initialText, byte[] cipherText, byte[] plainText) {
    log.info("initial text: {}", initialText);
    log.info("cipher text: {}", BaseEncoding.base16().encode(cipherText));
    log.info("plain text: {}", new String(plainText, StandardCharsets.UTF_8));

    printKeyset("private key set data", privateKeysetHandle);
    printKeyset("public key set data", publicKeysetHandle);
}
 
Example #29
Source File: B64TOHEX.java    From warp10-platform with Apache License 2.0 5 votes vote down vote up
@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
  Object o = stack.pop();
  
  if (!(o instanceof String)) {
    throw new WarpScriptException(getName() + " operates on a String.");
  }
  
  stack.push(new String(Hex.encode(BaseEncoding.base64().decode(o.toString())), StandardCharsets.UTF_8));
  
  return stack;
}
 
Example #30
Source File: DefaultRestClientRequest.java    From vertx-rest-client with Apache License 2.0 5 votes vote down vote up
@Override
public String getBasicAuth() {
    final String base64UserPassCombination = bufferedHttpOutputMessage.getHeaders().get(HttpHeaders.AUTHORIZATION);
    if (base64UserPassCombination != null && base64UserPassCombination.startsWith("Basic")) {
        return new String(BaseEncoding.base64().decode(base64UserPassCombination), Charsets.UTF_8).replaceFirst("Basic", "").trim();
    } else {
        return null;
    }
}