Java Code Examples for com.google.api.client.util.Base64#encodeBase64URLSafeString()

The following examples show how to use com.google.api.client.util.Base64#encodeBase64URLSafeString() . 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: 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 2
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 3
Source File: SendMailWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public static Message createMessageWithEmail(MimeMessage emailContent)
        throws MessagingException, IOException {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    emailContent.writeTo(buffer);
    byte[] bytes = buffer.toByteArray();
    String encodedEmail = Base64.encodeBase64URLSafeString(bytes);
    Message message = new Message();
    message.setRaw(encodedEmail);
    return message;
}
 
Example 4
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 5
Source File: AuthorizationCodeFlow.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Create the PKCE code verifier. It uses the S256 method but
 * falls back to using the 'plain' method in the unlikely case
 * that the SHA-256 MessageDigest algorithm implementation can't be
 * loaded.
 */
private void generateChallenge(String verifier) {
  try {
    byte[] bytes = verifier.getBytes();
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(bytes, 0, bytes.length);
    byte[] digest = md.digest();
    challenge = Base64.encodeBase64URLSafeString(digest);
    challengeMethod = "S256";
  } catch (NoSuchAlgorithmException e) {
    challenge = verifier;
    challengeMethod = "plain";
  }
}
 
Example 6
Source File: GmailSendEmailCustomizer.java    From syndesis with Apache License 2.0 4 votes vote down vote up
private static com.google.api.services.gmail.model.Message createMessage(String to, String from, String subject,
        String bodyText, String cc, String bcc) throws MessagingException, IOException {

    if (ObjectHelper.isEmpty(to)) {
        throw new RuntimeCamelException("Cannot create gmail message as no 'to' address is available");
    }

    if (ObjectHelper.isEmpty(from)) {
        throw new RuntimeCamelException("Cannot create gmail message as no 'from' address is available");
    }

    if (ObjectHelper.isEmpty(subject)) {
        LOG.warn("New gmail message wil have no 'subject'. This may not be want you wanted?");
    }

    if (ObjectHelper.isEmpty(bodyText)) {
        LOG.warn("New gmail message wil have no 'body text'. This may not be want you wanted?");
    }

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);

    email.setFrom(new InternetAddress(from));
    email.addRecipients(javax.mail.Message.RecipientType.TO, getAddressesList(to));
    email.setSubject(subject);
    email.setText(bodyText);
    if (ObjectHelper.isNotEmpty(cc)) {
        email.addRecipients(javax.mail.Message.RecipientType.CC, getAddressesList(cc));
    }
    if (ObjectHelper.isNotEmpty(bcc)) {
        email.addRecipients(javax.mail.Message.RecipientType.BCC, getAddressesList(bcc));
    }

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    email.writeTo(buffer);
    byte[] bytes = buffer.toByteArray();
    String encodedEmail = Base64.encodeBase64URLSafeString(bytes);
    com.google.api.services.gmail.model.Message message = new com.google.api.services.gmail.model.Message();
    message.setRaw(encodedEmail);
    return message;
}
 
Example 7
Source File: AuthorizationCodeFlow.java    From google-oauth-java-client with Apache License 2.0 4 votes vote down vote up
private static String generateVerifier() {
  SecureRandom sr = new SecureRandom();
  byte[] code = new byte[32];
  sr.nextBytes(code);
  return Base64.encodeBase64URLSafeString(code);
}