com.google.api.client.util.Base64 Java Examples
The following examples show how to use
com.google.api.client.util.Base64.
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 |
/** * 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: GcpLocalRunTabTest.java From google-cloud-eclipse with Apache License 2.0 | 6 votes |
private static void setUpServiceKeyCreation( IGoogleApiFactory mockApiFactory, boolean throwException) throws IOException { Iam iam = Mockito.mock(Iam.class); Projects projects = Mockito.mock(Projects.class); ServiceAccounts serviceAccounts = Mockito.mock(ServiceAccounts.class); Keys keys = Mockito.mock(Keys.class); Create create = Mockito.mock(Create.class); ServiceAccountKey serviceAccountKey = new ServiceAccountKey(); byte[] keyContent = "key data in JSON format".getBytes(); serviceAccountKey.setPrivateKeyData(Base64.encodeBase64String(keyContent)); when(mockApiFactory.newIamApi(any(Credential.class))).thenReturn(iam); when(iam.projects()).thenReturn(projects); when(projects.serviceAccounts()).thenReturn(serviceAccounts); when(serviceAccounts.keys()).thenReturn(keys); when(keys.create(anyString(), Matchers.any(CreateServiceAccountKeyRequest.class))) .thenReturn(create); if (throwException) { when(create.execute()).thenThrow(new IOException("log from unit test")); } else { when(create.execute()).thenReturn(serviceAccountKey); } }
Example #3
Source File: ServiceAccountUtilTest.java From google-cloud-eclipse with Apache License 2.0 | 6 votes |
@Before public void setUp() throws IOException { keyFile = tempFolder.getRoot().toPath().resolve("key.json"); Iam iam = mock(Iam.class); Projects projects = mock(Projects.class); ServiceAccounts serviceAccounts = mock(ServiceAccounts.class); when(apiFactory.newIamApi(any(Credential.class))).thenReturn(iam); when(iam.projects()).thenReturn(projects); when(projects.serviceAccounts()).thenReturn(serviceAccounts); when(serviceAccounts.keys()).thenReturn(keys); when(keys.create( eq("projects/my-project/serviceAccounts/[email protected]"), any(CreateServiceAccountKeyRequest.class))).thenReturn(create); ServiceAccountKey serviceAccountKey = new ServiceAccountKey(); byte[] keyContent = "key data in JSON format".getBytes(StandardCharsets.UTF_8); serviceAccountKey.setPrivateKeyData(Base64.encodeBase64String(keyContent)); when(create.execute()).thenReturn(serviceAccountKey); }
Example #4
Source File: AuthenticatorDataTest.java From webauthndemo with Apache License 2.0 | 6 votes |
/** * 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 #5
Source File: JsonWebSignature.java From google-http-java-client with Apache License 2.0 | 6 votes |
/** * 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 #6
Source File: TestCertificates.java From google-http-java-client with Apache License 2.0 | 6 votes |
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 #7
Source File: FirebaseProjectManagementServiceImpl.java From firebase-admin-java with Apache License 2.0 | 6 votes |
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 #8
Source File: ActionStorageManager.java From android-uiconductor with Apache License 2.0 | 6 votes |
public Map<String, String> getUuidToBase64RefImgs(String uuidStr) throws UicdActionException { Map<String, String> uuidToBase64RefImgs = new HashMap<>(); BaseAction action = getActionByUUID(uuidStr); if (action instanceof CompoundAction) { CompoundAction cmpAction = (CompoundAction) action; for (BaseAction childAction : cmpAction.childrenActions) { uuidToBase64RefImgs.putAll(getUuidToBase64RefImgs(childAction.getActionId().toString())); } } else if (action instanceof ImageDiffValidationAction) { ImageDiffValidationAction imgValAction = (ImageDiffValidationAction) action; if (imgValAction.getRefImage() != null) { uuidToBase64RefImgs.put( imgValAction.getRefImageUuid(), Base64.encodeBase64String(imgValAction.getRefImage())); } else { uuidToBase64RefImgs.put( imgValAction.getRefImageUuid(), Base64.encodeBase64String( ImageStorageManager.getInstance().getImage(imgValAction.getRefImageUuid()))); } } return uuidToBase64RefImgs; }
Example #9
Source File: OAuthHmacSigner.java From google-oauth-java-client with Apache License 2.0 | 6 votes |
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 #10
Source File: BigQueryCredentialsSupplier.java From spark-bigquery-connector with Apache License 2.0 | 5 votes |
private static Credentials createCredentialsFromKey(String key) { try { return GoogleCredentials.fromStream(new ByteArrayInputStream(Base64.decodeBase64(key))); } catch (IOException e) { throw new UncheckedIOException("Failed to create Credentials from key", e); } }
Example #11
Source File: GoogleSpreadsheet.java From pdi-google-spreadsheet-plugin with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static String base64EncodePrivateKeyStore(KeyStore pks) throws GeneralSecurityException, IOException { if (pks != null && pks.containsAlias("privatekey")) { ByteArrayOutputStream privateKeyStream = new ByteArrayOutputStream(); pks.store(privateKeyStream, GoogleSpreadsheet.SECRET); return Base64.encodeBase64String(privateKeyStream.toByteArray()); } return ""; }
Example #12
Source File: OAuthRsaSignerTest.java From google-oauth-java-client with Apache License 2.0 | 5 votes |
public void testComputeSignature() throws GeneralSecurityException { OAuthRsaSigner signer = new OAuthRsaSigner(); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); signer.privateKey = keyPairGenerator.genKeyPair().getPrivate(); byte[] expected = SecurityUtils.sign( SecurityUtils.getSha1WithRsaSignatureAlgorithm(), signer.privateKey, StringUtils.getBytesUtf8("foo")); assertEquals(Base64.encodeBase64String(expected), signer.computeSignature("foo")); }
Example #13
Source File: ServiceAccountUtil.java From google-cloud-eclipse with Apache License 2.0 | 5 votes |
/** * 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 #14
Source File: StorageResourceController.java From pubsub with Apache License 2.0 | 5 votes |
/** 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 #15
Source File: FakeBigQueryServices.java From beam with Apache License 2.0 | 5 votes |
public static String encodeQueryResult(Table table, List<TableRow> rows) throws IOException { KvCoder<String, List<TableRow>> coder = KvCoder.of(StringUtf8Coder.of(), ListCoder.of(TableRowJsonCoder.of())); KV<String, List<TableRow>> kv = KV.of(BigQueryHelpers.toJsonString(table), rows); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); coder.encode(kv, outputStream); return Base64.encodeBase64String(outputStream.toByteArray()); }
Example #16
Source File: FakeBigQueryServices.java From beam with Apache License 2.0 | 5 votes |
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 #17
Source File: WorkerCustomSources.java From beam with Apache License 2.0 | 5 votes |
@VisibleForTesting static Source<?> deserializeFromCloudSource(Map<String, Object> spec) throws Exception { Source<?> source = (Source<?>) deserializeFromByteArray( Base64.decodeBase64(getString(spec, SERIALIZED_SOURCE)), "Source"); try { source.validate(); } catch (Exception e) { LOG.error("Invalid source: {}", source, e); throw e; } return source; }
Example #18
Source File: AuthorizationCodeFlow.java From google-oauth-java-client with Apache License 2.0 | 5 votes |
/** * 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 #19
Source File: IcannHttpReporterTest.java From nomulus with Apache License 2.0 | 5 votes |
@Test public void testSuccess() throws Exception { IcannHttpReporter reporter = createReporter(); reporter.send(FAKE_PAYLOAD, "test-transactions-201706.csv"); assertThat(mockRequest.getUrl()).isEqualTo("https://fake-transactions.url/test/2017-06"); Map<String, List<String>> headers = mockRequest.getHeaders(); String userPass = "test_ry:fakePass"; String expectedAuth = String.format("Basic %s", Base64.encodeBase64String(StringUtils.getBytesUtf8(userPass))); assertThat(headers.get("authorization")).containsExactly(expectedAuth); assertThat(headers.get("content-type")).containsExactly(CSV_UTF_8.toString()); }
Example #20
Source File: IcannHttpReporterTest.java From nomulus with Apache License 2.0 | 5 votes |
@Test public void testSuccess_internationalTld() throws Exception { IcannHttpReporter reporter = createReporter(); reporter.send(FAKE_PAYLOAD, "xn--abc123-transactions-201706.csv"); assertThat(mockRequest.getUrl()).isEqualTo("https://fake-transactions.url/xn--abc123/2017-06"); Map<String, List<String>> headers = mockRequest.getHeaders(); String userPass = "xn--abc123_ry:fakePass"; String expectedAuth = String.format("Basic %s", Base64.encodeBase64String(StringUtils.getBytesUtf8(userPass))); assertThat(headers.get("authorization")).containsExactly(expectedAuth); assertThat(headers.get("content-type")).containsExactly(CSV_UTF_8.toString()); }
Example #21
Source File: OAuthAuthenticator.java From che with Eclipse Public License 2.0 | 5 votes |
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 #22
Source File: OpenIdConnectAuthenticator.java From fess with Apache License 2.0 | 5 votes |
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 #23
Source File: GoogleSpreadsheet.java From pdi-google-spreadsheet-plugin with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 #24
Source File: JsonWebSignatureTest.java From google-http-java-client with Apache License 2.0 | 5 votes |
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 #25
Source File: JsonWebSignatureTest.java From google-http-java-client with Apache License 2.0 | 5 votes |
@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 #26
Source File: BigQueryBaseIndexedRecordConverter.java From components with Apache License 2.0 | 5 votes |
public BigQueryIndexedRecord(T row) { values = new Object[schema.getFields().size()]; for (Schema.Field field : schema.getFields()) { Object v = row.get(field.name()); // Need to decode base64 for bytes type, use avro bytes type is ok as only one bigquery bytes type mapping for avro bytes type. // But can be better if there is db type in avro schema. if (AvroUtils.isSameType(AvroUtils.unwrapIfNullable(field.schema()), AvroUtils._bytes())) { v = v == null ? null : ByteBuffer.wrap(Base64.decodeBase64((String) v)); } values[field.pos()] = fieldConverters.get(field.name()).convertToAvro(v); } }
Example #27
Source File: FirebaseProjectManagementServiceImplTest.java From firebase-admin-java with Apache License 2.0 | 5 votes |
@Test public void getAndroidConfig() throws Exception { firstRpcResponse.setContent(GET_ANDROID_CONFIG_RESPONSE); serviceImpl = initServiceImpl(firstRpcResponse, interceptor); String content = serviceImpl.getAndroidConfig(ANDROID_APP_ID); String expectedUrl = String.format( "%s/v1beta1/projects/-/androidApps/%s/config", FIREBASE_PROJECT_MANAGEMENT_URL, ANDROID_APP_ID); checkRequestHeader(expectedUrl, HttpMethod.GET); assertEquals(new String(Base64.decodeBase64(ANDROID_CONFIG_CONTENT), Charsets.UTF_8), content); }
Example #28
Source File: BigQueryCredentialsSupplier.java From presto with Apache License 2.0 | 5 votes |
private static Credentials createCredentialsFromKey(String key) { try { return GoogleCredentials.fromStream(new ByteArrayInputStream(Base64.decodeBase64(key))); } catch (IOException e) { throw new UncheckedIOException("Failed to create Credentials from key", e); } }
Example #29
Source File: WorkflowManager.java From android-uiconductor with Apache License 2.0 | 5 votes |
public String takeScreenshot() throws UicdException, IOException { String deviceId = devicesDriverManager.getSelectedAndroidDeviceDriver().getDeviceId(); String screenshotTmpPath = UicdConfig.getInstance().getTestOutputFolder(); screenshotTmpPath = Paths.get(screenshotTmpPath, deviceId, "tmpScreenCapture.png").toString(); ImageUtil.saveScreenshotToLocal(deviceId, screenshotTmpPath); BufferedImage bImage = ImageIO.read(new File(screenshotTmpPath)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(bImage, "png", bos); return Base64.encodeBase64String(bos.toByteArray()); }
Example #30
Source File: FirebaseTokenFactory.java From firebase-admin-java with Apache License 2.0 | 5 votes |
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; }