• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Java Base64类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中com.google.api.client.util.Base64的典型用法代码示例。如果您正苦于以下问题:Java Base64类的具体用法?Java Base64怎么用?Java Base64使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Base64类属于com.google.api.client.util包,在下文中一共展示了Base64类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: encrypt

import com.google.api.client.util.Base64; //导入依赖的package包/类
public PacketData encrypt(PacketData input){
    PacketData output = null;
    try {
        IvParameterSpec iv = new IvParameterSpec(mIV);
        SecretKeySpec skeySpec = new SecretKeySpec(mKey, "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        Log.d(TAG, "encrypt - before - length=" + input.getLength());

        byte[] encrypted = cipher.doFinal(input.getBuffer());
        System.out.println("encrypted string: "
                + Base64.encodeBase64String(encrypted));
        Log.d(TAG, "encrypt - after - length=" + input.getLength());
        output = new PacketData(encrypted, encrypted.length);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return output;
}
 
开发者ID:dmtan90,项目名称:Sense-Hub-Android-Things,代码行数:22,代码来源:BroadlinkConnector.java


示例2: decrypt

import com.google.api.client.util.Base64; //导入依赖的package包/类
public PacketData decrypt(PacketData input){
    PacketData output = null;
    try {
        IvParameterSpec iv = new IvParameterSpec(mIV);
        SecretKeySpec skeySpec = new SecretKeySpec(mKey, "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

        byte[] original = cipher.doFinal(Base64.decodeBase64(input.getBuffer()));

        output = new PacketData(original, original.length);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return output;
}
 
开发者ID:dmtan90,项目名称:Sense-Hub-Android-Things,代码行数:19,代码来源:BroadlinkConnector.java


示例3: setUp

import com.google.api.client.util.Base64; //导入依赖的package包/类
@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);
}
 
开发者ID:GoogleCloudPlatform,项目名称:google-cloud-eclipse,代码行数:23,代码来源:ServiceAccountUtilTest.java


示例4: setUpServiceKeyCreation

import com.google.api.client.util.Base64; //导入依赖的package包/类
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);
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:google-cloud-eclipse,代码行数:26,代码来源:GcpLocalRunTabTest.java


示例5: DevShopAccessService

import com.google.api.client.util.Base64; //导入依赖的package包/类
public DevShopAccessService(String shopAdminUrl, String apiKey, String password) {

		this.baseShopUrl = shopAdminUrl;
		this.apiKey = apiKey;
		this.password = password;
		
		// Initial Request Factory
		//
		_requestFactory =
		        HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
		            @Override
		          public void initialize(HttpRequest request) {	
		            	//request.getHeaders().put("Content-Type", "application/json");
		            	// Only an option if we plan to parse stream from the
		            	// stream.
		            	//request.setParser((new JsonObjectParser(JSON_FACTORY));
		          }
		        });
		
		String authStr = this.apiKey + ":" + this.password;
		encodedAuthentication = Base64.encodeBase64String(authStr.getBytes());
	
	}
 
开发者ID:ydorego,项目名称:ShopifyAPI-Java,代码行数:24,代码来源:DevShopAccessService.java


示例6: verifyIdentity

import com.google.api.client.util.Base64; //导入依赖的package包/类
@Override
protected boolean verifyIdentity(HttpServletRequest request) {
	String authHeader = request.getHeader("Authorization");
	if (authHeader != null) {
		StringTokenizer st = new StringTokenizer(authHeader);
		if (st.hasMoreTokens()) {
			String basic = st.nextToken();
			if (basic.equalsIgnoreCase("Basic")) {
				try {
					String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8");
					log.finest("Credentials: " + credentials);
					int p = credentials.indexOf(":");
					if (p != -1) {
						String login = credentials.substring(0, p).trim();
						String password = credentials.substring(p + 1).trim();
						if (AppConfiguration.USERNAME.equals(login) && AppConfiguration.PASSWORD.equals(password))
							return true;
						return false;
					} else {
						log.warning("Invalid authentication token from: " + request.getRemoteAddr());
						return false;
					}
				} catch (UnsupportedEncodingException e) {
					log.log(Level.WARNING, "Couldn't retrieve authentication", e);
					return false;
				}
			} else
				log.finest("Not basic auth " + basic + " from " + request.getRemoteAddr());
		} else
			log.finest("No tokens from: " + request.getRemoteAddr());
	} else
		log.finest("No auth header found from: " + request.getRemoteAddr());
	return false;
}
 
开发者ID:baldapps,项目名称:google-actions,代码行数:35,代码来源:DummyApiAiServlet.java


示例7: createMessageWithEmail

import com.google.api.client.util.Base64; //导入依赖的package包/类
private static Message createMessageWithEmail(MimeMessage emailContent) throws IOException, MessagingException  {
	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;
}
 
开发者ID:tburne,项目名称:blog-examples,代码行数:10,代码来源:ClientRequestAPI.java


示例8: calcSha1Hash

import com.google.api.client.util.Base64; //导入依赖的package包/类
private static String calcSha1Hash(String data)
{
	try
	{
		final MessageDigest crypt = MessageDigest.getInstance("SHA-1");
		crypt.reset();
		crypt.update(data.getBytes("UTF-8"));
		byte[] rawHmac = crypt.digest();
		return Base64.encodeBase64String(rawHmac);
	}
	catch( Exception e )
	{
		throw Throwables.propagate(e);
	}
}
 
开发者ID:equella,项目名称:Equella,代码行数:16,代码来源:LtiServiceImpl.java


示例9: extractJwsData

import com.google.api.client.util.Base64; //导入依赖的package包/类
/**
 * 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]);
}
 
开发者ID:googlesamples,项目名称:android-play-safetynet,代码行数:16,代码来源:OnlineVerify.java


示例10: getApkCertificateDigestSha256

import com.google.api.client.util.Base64; //导入依赖的package包/类
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;
}
 
开发者ID:googlesamples,项目名称:android-play-safetynet,代码行数:8,代码来源:AttestationStatement.java


示例11: createAppEngineDefaultServiceAccountKey

import com.google.api.client.util.Base64; //导入依赖的package包/类
/**
 * 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 [email protected]m.
  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);
}
 
开发者ID:GoogleCloudPlatform,项目名称:google-cloud-eclipse,代码行数:38,代码来源:ServiceAccountUtil.java


示例12: pubSubCloud

import com.google.api.client.util.Base64; //导入依赖的package包/类
@Bean
@Profile("cloud")
public PubSub pubSubCloud(Environment environment) throws Exception {
	String vcapServicesEnv = environment.getProperty("VCAP_SERVICES");
	JsonParser parser = JsonParserFactory.getJsonParser();
	Map<String, Object> services = parser.parseMap(vcapServicesEnv);
	List<Map<String, Object>> googlePubsub = (List<Map<String, Object>>) services.get("google-pubsub");
	Map<String, Object> credentials = (Map<String, Object>) googlePubsub.get(0).get("credentials");
	String privateKeyData = (String) credentials.get("PrivateKeyData");
	GoogleCredential googleCredential = GoogleCredential.fromStream(new ByteArrayInputStream(Base64.decodeBase64(privateKeyData)));

	return PubSubOptions.newBuilder().setAuthCredentials(AuthCredentials.createFor(googleCredential.getServiceAccountId(),
			googleCredential.getServiceAccountPrivateKey()))
			.setProjectId(pubSubBinderConfigurationProperties.getProjectName()).build().getService();
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-stream-binder-google-pubsub,代码行数:16,代码来源:PubSubServiceAutoConfiguration.java


示例13: uploadFile

import com.google.api.client.util.Base64; //导入依赖的package包/类
/**
 * Uploads a given file to Google Storage.
 */
private void uploadFile(Path filePath) throws IOException {
  try {
    byte[] md5hash =
        Base64.decodeBase64(
            storage
                .objects()
                .get(projectName + "-cloud-pubsub-loadtest", 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(projectName + "-cloud-pubsub-loadtest", filePath.getFileName().toString())
        .execute();
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() != NOT_FOUND) {
      throw e;
    }
  }

  storage
      .objects()
      .insert(
          projectName + "-cloud-pubsub-loadtest",
          null,
          new FileContent("application/octet-stream", filePath.toFile()))
      .setName(filePath.getFileName().toString())
      .execute();
  log.info("File " + filePath.getFileName() + " created.");
}
 
开发者ID:GoogleCloudPlatform,项目名称:pubsub,代码行数:40,代码来源:GCEController.java


示例14: rowsFromEncodedQuery

import com.google.api.client.util.Base64; //导入依赖的package包/类
static List<TableRow> rowsFromEncodedQuery(String query) throws IOException {
  ListCoder<TableRow> listCoder = ListCoder.of(TableRowJsonCoder.of());
  ByteArrayInputStream input = new ByteArrayInputStream(Base64.decodeBase64(query));
  List<TableRow> rows = listCoder.decode(input, Context.OUTER);
  for (TableRow row : rows) {
    convertNumbers(row);
  }
  return rows;
}
 
开发者ID:apache,项目名称:beam,代码行数:10,代码来源:FakeBigQueryServices.java


示例15: testSuccess

import com.google.api.client.util.Base64; //导入依赖的package包/类
@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());
}
 
开发者ID:google,项目名称:nomulus,代码行数:14,代码来源:IcannHttpReporterTest.java


示例16: testSuccess_internationalTld

import com.google.api.client.util.Base64; //导入依赖的package包/类
@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());
}
 
开发者ID:google,项目名称:nomulus,代码行数:14,代码来源:IcannHttpReporterTest.java


示例17: createMessageWithEmail

import com.google.api.client.util.Base64; //导入依赖的package包/类
/**
 * Create a Message from an email
 *
 * @param email Email to be set to raw of message
 * @return Message containing base64url encoded email.
 * @throws IOException
 * @throws MessagingException
 */
private static Message createMessageWithEmail(MimeMessage email)
    throws MessagingException, IOException {
  ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  email.writeTo(bytes);
  String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());
  Message message = new Message();
  message.setRaw(encodedEmail);
  return message;
}
 
开发者ID:kinneerc,项目名称:giv-planner,代码行数:18,代码来源:GmailAPI.java


示例18: getPrivateKey

import com.google.api.client.util.Base64; //导入依赖的package包/类
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);
}
 
开发者ID:eclipse,项目名称:che,代码行数:8,代码来源:OAuthAuthenticator.java


示例19: deserialize

import com.google.api.client.util.Base64; //导入依赖的package包/类
public String deserialize(String tokenString) {
	String[] pieces = splitTokenString(tokenString);
	String jwtPayloadSegment = pieces[1];
	JsonParser parser = new JsonParser();
	JsonElement payload = parser.parse(StringUtils.newStringUtf8(Base64
			.decodeBase64(jwtPayloadSegment)));
	return payload.toString();
}
 
开发者ID:dhaselhan,项目名称:rpgtables-server,代码行数:9,代码来源:UserWebService.java


示例20: BigQueryIndexedRecord

import com.google.api.client.util.Base64; //导入依赖的package包/类
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);
    }
}
 
开发者ID:Talend,项目名称:components,代码行数:13,代码来源:BigQueryBaseIndexedRecordConverter.java



注:本文中的com.google.api.client.util.Base64类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java IDSorter类代码示例发布时间:2022-05-21
下一篇:
Java DiskCacheUtils类代码示例发布时间:2022-05-21
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap