Java Code Examples for com.google.api.client.util.StringUtils#getBytesUtf8()

The following examples show how to use com.google.api.client.util.StringUtils#getBytesUtf8() . 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: OAuthHmacSigner.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
public String computeSignature(String signatureBaseString) throws GeneralSecurityException {
  // compute key
  StringBuilder keyBuf = new StringBuilder();
  String clientSharedSecret = this.clientSharedSecret;
  if (clientSharedSecret != null) {
    keyBuf.append(OAuthParameters.escape(clientSharedSecret));
  }
  keyBuf.append('&');
  String tokenSharedSecret = this.tokenSharedSecret;
  if (tokenSharedSecret != null) {
    keyBuf.append(OAuthParameters.escape(tokenSharedSecret));
  }
  String key = keyBuf.toString();
  // sign
  SecretKey secretKey = new SecretKeySpec(StringUtils.getBytesUtf8(key), "HmacSHA1");
  Mac mac = Mac.getInstance("HmacSHA1");
  mac.init(secretKey);
  return Base64.encodeBase64String(mac.doFinal(StringUtils.getBytesUtf8(signatureBaseString)));
}
 
Example 2
Source File: JsonWebSignature.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Parses a JWS token into a parsed {@link JsonWebSignature}.
 *
 * @param tokenString JWS token string
 * @return parsed {@link JsonWebSignature}
 */
public JsonWebSignature parse(String tokenString) throws IOException {
  // split on the dots
  int firstDot = tokenString.indexOf('.');
  Preconditions.checkArgument(firstDot != -1);
  byte[] headerBytes = Base64.decodeBase64(tokenString.substring(0, firstDot));
  int secondDot = tokenString.indexOf('.', firstDot + 1);
  Preconditions.checkArgument(secondDot != -1);
  Preconditions.checkArgument(tokenString.indexOf('.', secondDot + 1) == -1);
  // decode the bytes
  byte[] payloadBytes = Base64.decodeBase64(tokenString.substring(firstDot + 1, secondDot));
  byte[] signatureBytes = Base64.decodeBase64(tokenString.substring(secondDot + 1));
  byte[] signedContentBytes = StringUtils.getBytesUtf8(tokenString.substring(0, secondDot));
  // parse the header and payload
  Header header =
      jsonFactory.fromInputStream(new ByteArrayInputStream(headerBytes), headerClass);
  Preconditions.checkArgument(header.getAlgorithm() != null);
  Payload payload =
      jsonFactory.fromInputStream(new ByteArrayInputStream(payloadBytes), payloadClass);
  return new JsonWebSignature(header, payload, signatureBytes, signedContentBytes);
}
 
Example 3
Source File: JsonWebSignature.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Signs a given JWS header and payload based on the given private key using RSA and SHA-256 as
 * described in <a
 * href="http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-11#appendix-A.2">JWS using
 * RSA SHA-256</a>.
 *
 * @param privateKey private key
 * @param jsonFactory JSON factory
 * @param header JWS header
 * @param payload JWS payload
 * @return signed JWS string
 * @since 1.14 (since 1.7 as com.google.api.client.auth.jsontoken.RsaSHA256Signer)
 */
public static String signUsingRsaSha256(
    PrivateKey privateKey,
    JsonFactory jsonFactory,
    JsonWebSignature.Header header,
    JsonWebToken.Payload payload)
    throws GeneralSecurityException, IOException {
  String content =
      Base64.encodeBase64URLSafeString(jsonFactory.toByteArray(header))
          + "."
          + Base64.encodeBase64URLSafeString(jsonFactory.toByteArray(payload));
  byte[] contentBytes = StringUtils.getBytesUtf8(content);
  byte[] signature =
      SecurityUtils.sign(
          SecurityUtils.getSha256WithRsaSignatureAlgorithm(), privateKey, contentBytes);
  return content + "." + Base64.encodeBase64URLSafeString(signature);
}
 
Example 4
Source File: TestCertificates.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public static JsonWebSignature getJsonWebSignature() throws IOException {
  if (jsonWebSignature == null) {
    JsonWebSignature.Header header = new JsonWebSignature.Header();
    header.setAlgorithm("RS256");
    List<String> certificates = Lists.newArrayList();
    certificates.add(FOO_BAR_COM_CERT.getBase64Der());
    certificates.add(CA_CERT.getBase64Der());
    header.setX509Certificates(certificates);
    JsonWebToken.Payload payload = new JsonWebToken.Payload();
    payload.set("foo", "bar");
    int firstDot = JWS_SIGNATURE.indexOf('.');
    int secondDot = JWS_SIGNATURE.indexOf('.', firstDot + 1);
    byte[] signatureBytes = Base64.decodeBase64(JWS_SIGNATURE.substring(secondDot + 1));
    byte[] signedContentBytes = StringUtils.getBytesUtf8(JWS_SIGNATURE.substring(0, secondDot));
    JsonWebSignature signature =
        new JsonWebSignature(header, payload, signatureBytes, signedContentBytes);
    jsonWebSignature = signature;
  }
  return jsonWebSignature;
}
 
Example 5
Source File: HttpRequestTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testExecute_redirectWithIncorrectContentRetryableSetting() throws Exception {
  // TODO(yanivi): any way we can warn user about this?
  RedirectTransport fakeTransport = new RedirectTransport();
  String contentValue = "hello";
  fakeTransport.expectedContent = new String[] {contentValue, ""};
  byte[] bytes = StringUtils.getBytesUtf8(contentValue);
  InputStreamContent content =
      new InputStreamContent(
          new HttpMediaType("text/plain").setCharsetParameter(Charsets.UTF_8).build(),
          new ByteArrayInputStream(bytes));
  content.setRetrySupported(true);
  HttpRequest request =
      fakeTransport
          .createRequestFactory()
          .buildPostRequest(HttpTesting.SIMPLE_GENERIC_URL, content);
  HttpResponse resp = request.execute();
  assertEquals(200, resp.getStatusCode());
  assertEquals(2, fakeTransport.lowLevelExecCalls);
}
 
Example 6
Source File: NetHttpTransportTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testAbruptTerminationIsNoticedWithContentLengthWithReadToBuf() throws Exception {
  String incompleteBody = "" + "Fixed size body test.\r\n" + "Incomplete response.";
  byte[] buf = StringUtils.getBytesUtf8(incompleteBody);
  MockHttpURLConnection connection =
      new MockHttpURLConnection(new URL(HttpTesting.SIMPLE_URL))
          .setResponseCode(200)
          .addHeader("Content-Length", "205")
          .setInputStream(new ByteArrayInputStream(buf));
  connection.setRequestMethod("GET");
  NetHttpRequest request = new NetHttpRequest(connection);
  setContent(request, null, "");
  NetHttpResponse response = (NetHttpResponse) (request.execute());

  InputStream in = response.getContent();
  boolean thrown = false;
  try {
    while (in.read(new byte[100]) != -1) {
      // This space is intentionally left blank.
    }
  } catch (IOException ioe) {
    thrown = true;
  }
  assertTrue(thrown);
}
 
Example 7
Source File: NetHttpTransportTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testAbruptTerminationIsNoticedWithContentLength() throws Exception {
  String incompleteBody = "" + "Fixed size body test.\r\n" + "Incomplete response.";
  byte[] buf = StringUtils.getBytesUtf8(incompleteBody);
  MockHttpURLConnection connection =
      new MockHttpURLConnection(new URL(HttpTesting.SIMPLE_URL))
          .setResponseCode(200)
          .addHeader("Content-Length", "205")
          .setInputStream(new ByteArrayInputStream(buf));
  connection.setRequestMethod("GET");
  NetHttpRequest request = new NetHttpRequest(connection);
  setContent(request, null, "");
  NetHttpResponse response = (NetHttpResponse) (request.execute());

  InputStream in = response.getContent();
  boolean thrown = false;
  try {
    while (in.read() != -1) {
      // This space is intentionally left blank.
    }
  } catch (IOException ioe) {
    thrown = true;
  }
  assertTrue(thrown);
}
 
Example 8
Source File: GoogleIdTokenAuth.java    From styx with Apache License 2.0 5 votes vote down vote up
private String getServiceAccountIdTokenUsingAccessToken(GoogleCredentials credentials,
                                                        String serviceAccount, String targetAudience)
    throws IOException {
  final String tokenServerUrl = "https://oauth2.googleapis.com/token";
  final Header header = jwtHeader();
  final JsonWebToken.Payload payload = jwtPayload(
      targetAudience, serviceAccount, tokenServerUrl);
  final Iam iam = new Iam.Builder(httpTransport, JSON_FACTORY,
      new HttpCredentialsAdapter(withScopes(credentials, IamScopes.all()))).build();
  final String content = Base64.encodeBase64URLSafeString(JSON_FACTORY.toByteArray(header)) + "."
                         + Base64.encodeBase64URLSafeString(JSON_FACTORY.toByteArray(payload));
  byte[] contentBytes = StringUtils.getBytesUtf8(content);
  final SignBlobResponse signResponse;
  try {
    signResponse = iam.projects().serviceAccounts()
        .signBlob("projects/-/serviceAccounts/" + serviceAccount, new SignBlobRequest()
            .encodeBytesToSign(contentBytes))
        .execute();
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() == 403) {
      throw new IOException(
          "Unable to sign request for id token, missing Service Account Token Creator role for self on "
          + serviceAccount + " or IAM api not enabled?", e);
    }
    throw e;
  }
  final String assertion = content + "." + signResponse.getSignature();
  final TokenRequest request = new TokenRequest(
      httpTransport, JSON_FACTORY,
      new GenericUrl(tokenServerUrl),
      "urn:ietf:params:oauth:grant-type:jwt-bearer");
  request.put("assertion", assertion);
  final TokenResponse tokenResponse = request.execute();
  return (String) tokenResponse.get("id_token");
}
 
Example 9
Source File: MockLowLevelHttpRequestTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void subtestGetContentAsString(String expected, String content) throws Exception {
  MockLowLevelHttpRequest request = new MockLowLevelHttpRequest();
  if (content != null) {
    byte[] bytes = StringUtils.getBytesUtf8(content);
    request.setStreamingContent(new ByteArrayStreamingContent(bytes));
  }
  assertEquals(expected, request.getContentAsString());
}
 
Example 10
Source File: HttpRequestTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testExecute_curlLoggerWithContentEncoding() throws Exception {
  LogRecordingHandler recorder = new LogRecordingHandler();
  HttpTransport.LOGGER.setLevel(Level.CONFIG);
  HttpTransport.LOGGER.addHandler(recorder);

  String contentValue = "hello";
  byte[] bytes = StringUtils.getBytesUtf8(contentValue);
  InputStreamContent content =
      new InputStreamContent(
          new HttpMediaType("text/plain").setCharsetParameter(Charsets.UTF_8).build(),
          new ByteArrayInputStream(bytes));

  new MockHttpTransport()
      .createRequestFactory()
      .buildPostRequest(new GenericUrl("http://google.com/#q=a'b'c"), content)
      .setEncoding(new GZipEncoding())
      .execute();

  boolean found = false;
  for (String message : recorder.messages()) {
    if (message.startsWith("curl")) {
      found = true;
      assertTrue(message.contains("curl -v --compressed -X POST -H 'Accept-Encoding: gzip'"));
      assertTrue(message.contains("-H 'User-Agent: " + HttpRequest.USER_AGENT_SUFFIX + "'"));
      assertTrue(
          message.contains(
              "-H 'Content-Type: text/plain; charset=UTF-8' -H 'Content-Encoding: gzip'"));
      assertTrue(message.contains("-d '@-' -- 'http://google.com/#q=a'\"'\"'b'\"'\"'c' << $$$"));
    }
  }
  assertTrue(found);
}
 
Example 11
Source File: NetHttpTransportTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testExecute_methodUnchanged() throws Exception {
  String body = "Arbitrary body";
  byte[] buf = StringUtils.getBytesUtf8(body);
  for (String method : METHODS) {
    HttpURLConnection connection =
        new MockHttpURLConnection(new URL(HttpTesting.SIMPLE_URL))
            .setResponseCode(200)
            .setInputStream(new ByteArrayInputStream(buf));
    connection.setRequestMethod(method);
    NetHttpRequest request = new NetHttpRequest(connection);
    setContent(request, "text/html", "");
    request.execute().getContent().close();
    assertEquals(method, connection.getRequestMethod());
  }
}
 
Example 12
Source File: HttpEncodingStreamingContentTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void test() throws IOException {
  GZipEncoding encoding = new GZipEncoding();
  ByteArrayStreamingContent content =
      new ByteArrayStreamingContent(StringUtils.getBytesUtf8("oooooooooooooooooooooooooooo"));
  TestableByteArrayOutputStream out = new TestableByteArrayOutputStream();
  HttpEncodingStreamingContent encodingContent =
      new HttpEncodingStreamingContent(content, encoding);
  encodingContent.writeTo(out);
  assertFalse(out.isClosed());
  Assert.assertArrayEquals(EXPECED_ZIPPED, out.getBuffer());
}
 
Example 13
Source File: GZipEncodingTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void test() throws IOException {
  GZipEncoding encoding = new GZipEncoding();
  ByteArrayStreamingContent content =
      new ByteArrayStreamingContent(StringUtils.getBytesUtf8("oooooooooooooooooooooooooooo"));
  TestableByteArrayOutputStream out = new TestableByteArrayOutputStream();
  encoding.encode(content, out);
  assertFalse(out.isClosed());
  Assert.assertArrayEquals(EXPECED_ZIPPED, out.getBuffer());
}
 
Example 14
Source File: JsonWebSignatureTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testVerifyES256() throws Exception {
  PublicKey publicKey = buildEs256PublicKey(GOOGLE_ES256_X, GOOGLE_ES256_Y);
  JsonWebSignature.Header header = new JsonWebSignature.Header();
  header.setAlgorithm("ES256");
  JsonWebSignature.Payload payload = new JsonWebToken.Payload();
  byte[] signatureBytes = Base64.decodeBase64(ES256_SIGNATURE);
  byte[] signedContentBytes = StringUtils.getBytesUtf8(ES256_CONTENT);
  JsonWebSignature jsonWebSignature =
      new JsonWebSignature(header, payload, signatureBytes, signedContentBytes);
  Assert.assertTrue(jsonWebSignature.verifySignature(publicKey));
}
 
Example 15
Source File: FirebaseTokenFactory.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private String signPayload(JsonWebSignature.Header header,
    FirebaseCustomAuthToken.Payload payload) throws IOException {
  String headerString = Base64.encodeBase64URLSafeString(jsonFactory.toByteArray(header));
  String payloadString = Base64.encodeBase64URLSafeString(jsonFactory.toByteArray(payload));
  String content = headerString + "." + payloadString;
  byte[] contentBytes = StringUtils.getBytesUtf8(content);
  String signature = Base64.encodeBase64URLSafeString(signer.sign(contentBytes));
  return content + "." + signature;
}
 
Example 16
Source File: NetHttpTransportTest.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
private void setContent(NetHttpRequest request, String type, String value) throws Exception {
  byte[] bytes = StringUtils.getBytesUtf8(value);
  request.setStreamingContent(new ByteArrayStreamingContent(bytes));
  request.setContentType(type);
  request.setContentLength(bytes.length);
}
 
Example 17
Source File: OAuthRsaSigner.java    From google-oauth-java-client with Apache License 2.0 4 votes vote down vote up
public String computeSignature(String signatureBaseString) throws GeneralSecurityException {
  Signature signer = SecurityUtils.getSha1WithRsaSignatureAlgorithm();
  byte[] data = StringUtils.getBytesUtf8(signatureBaseString);
  return Base64.encodeBase64String(SecurityUtils.sign(signer, privateKey, data));
}
 
Example 18
Source File: ByteArrayContent.java    From google-http-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a new instance with the UTF-8 encoding (using {@link StringUtils#getBytesUtf8(String)})
 * of the given content string.
 *
 * <p>Sample use:
 *
 * <pre>
 * <code>
 * static void setJsonContent(HttpRequest request, String json) {
 * request.setContent(ByteArrayContent.fromString("application/json", json));
 * }
 * </code>
 * </pre>
 *
 * @param type content type or {@code null} for none
 * @param contentString content string
 * @since 1.5
 */
public static ByteArrayContent fromString(String type, String contentString) {
  return new ByteArrayContent(type, StringUtils.getBytesUtf8(contentString));
}