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

The following examples show how to use com.google.api.client.util.Base64#decodeBase64() . 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: FirebaseProjectManagementServiceImpl.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private CallableOperation<String, FirebaseProjectManagementException> getConfigOp(
    final String appId, final String platformResourceName) {
  return new CallableOperation<String, FirebaseProjectManagementException>() {
    @Override
    protected String execute() throws FirebaseProjectManagementException {
      String url = String.format(
          "%s/v1beta1/projects/-/%s/%s/config",
          FIREBASE_PROJECT_MANAGEMENT_URL,
          platformResourceName,
          appId);
      AppConfigResponse parsedResponse = new AppConfigResponse();
      httpHelper.makeGetRequest(url, parsedResponse, appId, "App ID");
      return new String(
          Base64.decodeBase64(parsedResponse.configFileContents), StandardCharsets.UTF_8);
    }
  };
}
 
Example 2
Source File: AuthenticatorDataTest.java    From webauthndemo with Apache License 2.0 6 votes vote down vote up
/**
 * Test method for {@link com.google.webauthn.gaedemo.objects.AuthenticatorData#decode(byte[])}.
 * 
 * @throws CborException
 * @throws ResponseException 
 */
@Test
public void testDecodeWithAttestation() throws CborException, ResponseException {
  byte[] randomRpIdHash = new byte[32];
  random.nextBytes(randomRpIdHash);
  byte[] flags = {1 << 6};
  AttestationData attData = new AttestationData();
  EccKey eccKey = new EccKey(Base64.decodeBase64("NNxD3LBXs6iF1jiBGZ4Qqhd997NKcmDLJyyILL49V90"),
      Base64.decodeBase64("MJtVZlRRfTscLy06DSHLBfA8O03pZJ1K01DbCILr0rA"));
  random.nextBytes(attData.aaguid);
  eccKey.alg = Algorithm.ES256;
  attData.publicKey = eccKey;
  int countUnsignedInt = Integer.parseUnsignedInt("" + (random.nextLong() & 0xffffffffL));
  byte[] count = ByteBuffer.allocate(4).putInt(countUnsignedInt).array();
  byte[] data = null;
  data = Bytes.concat(randomRpIdHash, flags, count, attData.encode());
  AuthenticatorData result = AuthenticatorData.decode(data);
  assertTrue(result.getAttData().getPublicKey().equals(eccKey));
  assertArrayEquals(randomRpIdHash, result.getRpIdHash());
  assertTrue(Integer.compareUnsigned(countUnsignedInt, result.getSignCount()) == 0);
}
 
Example 3
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 4
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 5
Source File: ServiceAccountUtil.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
/**
 * Creates and saves a service account key the App Engine default service account.
 *
 * @param credential credential to use to create a service account key
 * @param projectId GCP project ID for {@code serviceAccountId} 
 * @param destination path of a key file to be saved
 */
public static void createAppEngineDefaultServiceAccountKey(IGoogleApiFactory apiFactory,
    Credential credential, String projectId, Path destination)
        throws FileAlreadyExistsException, IOException {
  Preconditions.checkNotNull(credential, "credential not given");
  Preconditions.checkState(!projectId.isEmpty(), "project ID empty");
  Preconditions.checkArgument(destination.isAbsolute(), "destination not absolute");

  if (!Files.exists(destination.getParent())) {
    Files.createDirectories(destination.getParent());
  }

  Iam iam = apiFactory.newIamApi(credential);
  Keys keys = iam.projects().serviceAccounts().keys();
  
  String projectEmail = projectId;
  // The appengine service account for google.com:gcloud-for-eclipse-testing 
  // would be gcloud-for-eclipse-testing.google.com@appspot.gserviceaccount.com.
  if (projectId.contains(":")) {
    String[] parts = projectId.split(":");
    projectEmail = parts[1] + "." + parts[0];
  }
  String serviceAccountId = projectEmail + "@appspot.gserviceaccount.com";

  String keyId = "projects/" + projectId + "/serviceAccounts/" + serviceAccountId;
  CreateServiceAccountKeyRequest createRequest = new CreateServiceAccountKeyRequest();
  ServiceAccountKey key = keys.create(keyId, createRequest).execute();

  byte[] jsonKey = Base64.decodeBase64(key.getPrivateKeyData());
  Files.write(destination, jsonKey);
}
 
Example 6
Source File: OpenIdConnectAuthenticator.java    From fess with Apache License 2.0 5 votes vote down vote up
protected LoginCredential processCallback(final HttpServletRequest request, final String code) {
    try {
        final TokenResponse tr = getTokenUrl(code);

        final String[] jwt = ((String) tr.get("id_token")).split("\\.");
        final String jwtHeader = new String(Base64.decodeBase64(jwt[0]), Constants.UTF_8_CHARSET);
        final String jwtClaim = new String(Base64.decodeBase64(jwt[1]), Constants.UTF_8_CHARSET);
        final String jwtSigniture = new String(Base64.decodeBase64(jwt[2]), Constants.UTF_8_CHARSET);

        if (logger.isDebugEnabled()) {
            logger.debug("jwtHeader: {}", jwtHeader);
            logger.debug("jwtClaim: {}", jwtClaim);
            logger.debug("jwtSigniture: {}", jwtSigniture);
        }

        // TODO validate signiture

        final Map<String, Object> attributes = new HashMap<>();
        attributes.put("accesstoken", tr.getAccessToken());
        attributes.put("refreshtoken", tr.getRefreshToken() == null ? "null" : tr.getRefreshToken());
        attributes.put("tokentype", tr.getTokenType());
        attributes.put("expire", tr.getExpiresInSeconds());
        attributes.put("jwtheader", jwtHeader);
        attributes.put("jwtclaim", jwtClaim);
        attributes.put("jwtsign", jwtSigniture);

        if (logger.isDebugEnabled()) {
            logger.debug("attribute: {}", attributes);
        }
        parseJwtClaim(jwtClaim, attributes);

        return new OpenIdConnectCredential(attributes);
    } catch (final IOException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Failed to process callbacked request.", e);
        }
    }
    return null;
}
 
Example 7
Source File: GoogleSpreadsheet.java    From pdi-google-spreadsheet-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static KeyStore base64DecodePrivateKeyStore(String pks) throws GeneralSecurityException, IOException {
    if (pks != null && !pks.equals("")) {
        ByteArrayInputStream privateKeyStream = new ByteArrayInputStream(Base64.decodeBase64(pks));
        if (privateKeyStream.available() > 0) {
            KeyStore privateKeyStore = KeyStore.getInstance("PKCS12");
            privateKeyStore.load(privateKeyStream, GoogleSpreadsheet.SECRET);
            if (privateKeyStore.containsAlias("privatekey")) {
                return privateKeyStore;
            }
        }
    }
    return null;
}
 
Example 8
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 9
Source File: JsonWebSignatureTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
private PublicKey buildEs256PublicKey(String x, String y)
    throws NoSuchAlgorithmException, InvalidParameterSpecException, InvalidKeySpecException {
  AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
  parameters.init(new ECGenParameterSpec("secp256r1"));
  ECPublicKeySpec ecPublicKeySpec =
      new ECPublicKeySpec(
          new ECPoint(
              new BigInteger(1, Base64.decodeBase64(x)),
              new BigInteger(1, Base64.decodeBase64(y))),
          parameters.getParameterSpec(ECParameterSpec.class));
  KeyFactory keyFactory = KeyFactory.getInstance("EC");
  return keyFactory.generatePublic(ecPublicKeySpec);
}
 
Example 10
Source File: OAuthAuthenticator.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private PrivateKey getPrivateKey(String privateKey)
    throws NoSuchAlgorithmException, InvalidKeySpecException {
  byte[] privateKeyBytes = Base64.decodeBase64(privateKey);
  PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
  KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  return keyFactory.generatePrivate(keySpec);
}
 
Example 11
Source File: FakeBigQueryServices.java    From beam with Apache License 2.0 5 votes vote down vote up
public static KV<Table, List<TableRow>> decodeQueryResult(String queryResult) throws IOException {
  KvCoder<String, List<TableRow>> coder =
      KvCoder.of(StringUtf8Coder.of(), ListCoder.of(TableRowJsonCoder.of()));
  ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64.decodeBase64(queryResult));
  KV<String, List<TableRow>> kv = coder.decode(inputStream);
  Table table = BigQueryHelpers.fromJsonString(kv.getKey(), Table.class);
  List<TableRow> rows = kv.getValue();
  rows.forEach(FakeBigQueryServices::convertNumbers);
  return KV.of(table, rows);
}
 
Example 12
Source File: StorageResourceController.java    From pubsub with Apache License 2.0 5 votes vote down vote up
/** Uploads a given file to Google Storage. */
private void uploadFile(Path filePath) throws IOException {
  try {
    byte[] md5hash =
        Base64.decodeBase64(
            storage
                .objects()
                .get(bucketName(project), filePath.getFileName().toString())
                .execute()
                .getMd5Hash());
    try (InputStream inputStream = Files.newInputStream(filePath, StandardOpenOption.READ)) {
      if (Arrays.equals(md5hash, DigestUtils.md5(inputStream))) {
        log.info("File " + filePath.getFileName() + " is current, reusing.");
        return;
      }
    }
    log.info("File " + filePath.getFileName() + " is out of date, uploading new version.");
    storage.objects().delete(bucketName(project), filePath.getFileName().toString()).execute();
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() != HttpStatus.SC_NOT_FOUND) {
      throw e;
    }
  }

  storage
      .objects()
      .insert(
          bucketName(project),
          null,
          new FileContent("application/octet-stream", filePath.toFile()))
      .setName(filePath.getFileName().toString())
      .execute();
  log.info("File " + filePath.getFileName() + " created.");
}
 
Example 13
Source File: AttestationStatement.java    From android-play-safetynet with Apache License 2.0 5 votes vote down vote up
public byte[][] getApkCertificateDigestSha256() {
    byte[][] certs = new byte[apkCertificateDigestSha256.length][];
    for (int i = 0; i < apkCertificateDigestSha256.length; i++) {
        certs[i] = Base64.decodeBase64(apkCertificateDigestSha256[i]);
    }
    return certs;
}
 
Example 14
Source File: OnlineVerify.java    From android-play-safetynet with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts the data part from a JWS signature.
 */
private static byte[] extractJwsData(String jws) {
    // The format of a JWS is:
    // <Base64url encoded header>.<Base64url encoded JSON data>.<Base64url encoded signature>
    // Split the JWS into the 3 parts and return the JSON data part.
    String[] parts = jws.split("[.]");
    if (parts.length != 3) {
        System.err.println("Failure: Illegal JWS signature format. The JWS consists of "
                + parts.length + " parts instead of 3.");
        return null;
    }
    return Base64.decodeBase64(parts[1]);
}
 
Example 15
Source File: WorkflowManager.java    From android-uiconductor with Apache License 2.0 4 votes vote down vote up
public String addImage(String imgBase64Str) {
  String uuid = UUID.randomUUID().toString();
  byte[] imgBytes = Base64.decodeBase64(imgBase64Str);
  imageStorageManager.addImage(uuid, imgBytes);
  return uuid;
}
 
Example 16
Source File: AttestationStatement.java    From android-play-safetynet with Apache License 2.0 4 votes vote down vote up
public byte[] getApkDigestSha256() {
    return Base64.decodeBase64(apkDigestSha256);
}
 
Example 17
Source File: AttestationStatement.java    From android-play-safetynet with Apache License 2.0 4 votes vote down vote up
public byte[] getNonce() {
    return Base64.decodeBase64(nonce);
}
 
Example 18
Source File: OfflineVerify.java    From webauthndemo with Apache License 2.0 4 votes vote down vote up
public byte[] getApkDigestSha256() {
  return Base64.decodeBase64(apkDigestSha256);
}
 
Example 19
Source File: OfflineVerify.java    From webauthndemo with Apache License 2.0 4 votes vote down vote up
public byte[] getNonce() {
  return Base64.decodeBase64(nonce);
}
 
Example 20
Source File: WorkflowManager.java    From android-uiconductor with Apache License 2.0 4 votes vote down vote up
public void updateImage(String uuid, String imgBase64Str) {
  byte[] imgBytes = Base64.decodeBase64(imgBase64Str);
  imageStorageManager.updateImage(uuid, imgBytes);
}