com.google.api.client.util.SecurityUtils Java Examples
The following examples show how to use
com.google.api.client.util.SecurityUtils.
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 |
/** * Verifies the signature of the content. * * <p>Currently only {@code "RS256"} and {@code "ES256"} algorithms are verified, but others may * be added in the future. For any other algorithm it returns {@code false}. * * @param publicKey public key * @return whether the algorithm is recognized and it is verified * @throws GeneralSecurityException */ public final boolean verifySignature(PublicKey publicKey) throws GeneralSecurityException { String algorithm = getHeader().getAlgorithm(); if ("RS256".equals(algorithm)) { return SecurityUtils.verify( SecurityUtils.getSha256WithRsaSignatureAlgorithm(), publicKey, signatureBytes, signedContentBytes); } else if ("ES256".equals(algorithm)) { return SecurityUtils.verify( SecurityUtils.getEs256SignatureAlgorithm(), publicKey, DerEncoder.encode(signatureBytes), signedContentBytes); } else { return false; } }
Example #2
Source File: GcpStackUtil.java From cloudbreak with Apache License 2.0 | 6 votes |
public static GoogleCredential buildCredential(CloudCredential gcpCredential, HttpTransport httpTransport) throws IOException, GeneralSecurityException { String credentialJson = getServiceAccountCredentialJson(gcpCredential); if (isNotEmpty(credentialJson)) { return GoogleCredential.fromStream(new ByteArrayInputStream(Base64.decodeBase64(credentialJson)), httpTransport, JSON_FACTORY) .createScoped(SCOPES); } else { try { PrivateKey pk = SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(), new ByteArrayInputStream(Base64.decodeBase64(getServiceAccountPrivateKey(gcpCredential))), "notasecret", "privatekey", "notasecret"); return new GoogleCredential.Builder().setTransport(httpTransport) .setJsonFactory(JSON_FACTORY) .setServiceAccountId(getServiceAccountId(gcpCredential)) .setServiceAccountScopes(SCOPES) .setServiceAccountPrivateKey(pk) .build(); } catch (IOException e) { throw new CredentialVerificationException("Can not read private key", e); } } }
Example #3
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 #4
Source File: GoogleAnalyticsUtils.java From wallride with Apache License 2.0 | 5 votes |
public static Analytics buildClient(GoogleAnalytics googleAnalytics) { Analytics analytics; try { PrivateKey privateKey= SecurityUtils.loadPrivateKeyFromKeyStore( SecurityUtils.getPkcs12KeyStore(), new ByteArrayInputStream(googleAnalytics.getServiceAccountP12FileContent()), "notasecret", "privatekey", "notasecret"); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); Set<String> scopes = new HashSet<>(); scopes.add(AnalyticsScopes.ANALYTICS_READONLY); final GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport) .setJsonFactory(jsonFactory) .setServiceAccountId(googleAnalytics.getServiceAccountId()) .setServiceAccountScopes(scopes) .setServiceAccountPrivateKey(privateKey) .build(); HttpRequestInitializer httpRequestInitializer = new HttpRequestInitializer() { @Override public void initialize(HttpRequest httpRequest) throws IOException { credential.initialize(httpRequest); httpRequest.setConnectTimeout(3 * 60000); // 3 minutes connect timeout httpRequest.setReadTimeout(3 * 60000); // 3 minutes read timeout } }; analytics = new Analytics.Builder(httpTransport, jsonFactory, httpRequestInitializer) .setApplicationName("WallRide") .build(); } catch (Exception e) { logger.warn("Failed to synchronize with Google Analytics", e); throw new GoogleAnalyticsException(e); } return analytics; }
Example #5
Source File: FirebaseTokenFactoryTest.java From firebase-admin-java with Apache License 2.0 | 5 votes |
@Override public byte[] sign(byte[] payload) throws IOException { try { return SecurityUtils.sign(SecurityUtils.getSha256WithRsaSignatureAlgorithm(), privateKey, payload); } catch (GeneralSecurityException e) { throw new IOException(e); } }
Example #6
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 #7
Source File: GoogleUtils.java From google-api-java-client with Apache License 2.0 | 5 votes |
/** * Returns the key store for trusted root certificates to use for Google APIs. * * <p>Value is cached, so subsequent access is fast. * * @since 1.14 */ public static synchronized KeyStore getCertificateTrustStore() throws IOException, GeneralSecurityException { if (certTrustStore == null) { certTrustStore = SecurityUtils.getJavaKeyStore(); InputStream keyStoreStream = GoogleUtils.class.getResourceAsStream("google.jks"); SecurityUtils.loadKeyStore(certTrustStore, keyStoreStream, "notasecret"); } return certTrustStore; }
Example #8
Source File: GooglePublicKeysManager.java From google-api-java-client with Apache License 2.0 | 5 votes |
/** * Forces a refresh of the public certificates downloaded from {@link #getPublicCertsEncodedUrl}. * * <p> * This method is automatically called from {@link #getPublicKeys()} if the public keys have not * yet been initialized or if the expiration time is very close, so normally this doesn't need to * be called. Only call this method to explicitly force the public keys to be updated. * </p> */ public GooglePublicKeysManager refresh() throws GeneralSecurityException, IOException { lock.lock(); try { publicKeys = new ArrayList<PublicKey>(); // HTTP request to public endpoint CertificateFactory factory = SecurityUtils.getX509CertificateFactory(); HttpResponse certsResponse = transport.createRequestFactory() .buildGetRequest(new GenericUrl(publicCertsEncodedUrl)).execute(); expirationTimeMilliseconds = clock.currentTimeMillis() + getCacheTimeInSec(certsResponse.getHeaders()) * 1000; // parse each public key in the JSON response JsonParser parser = jsonFactory.createJsonParser(certsResponse.getContent()); JsonToken currentToken = parser.getCurrentToken(); // token is null at start, so get next token if (currentToken == null) { currentToken = parser.nextToken(); } Preconditions.checkArgument(currentToken == JsonToken.START_OBJECT); try { while (parser.nextToken() != JsonToken.END_OBJECT) { parser.nextToken(); String certValue = parser.getText(); X509Certificate x509Cert = (X509Certificate) factory.generateCertificate( new ByteArrayInputStream(StringUtils.getBytesUtf8(certValue))); publicKeys.add(x509Cert.getPublicKey()); } publicKeys = Collections.unmodifiableList(publicKeys); } finally { parser.close(); } return this; } finally { lock.unlock(); } }
Example #9
Source File: CredentialFactory.java From hadoop-connectors with Apache License 2.0 | 5 votes |
private static PrivateKey privateKeyFromPkcs8(String privateKeyPem) throws IOException { Reader reader = new StringReader(privateKeyPem); Section section = PemReader.readFirstSectionAndClose(reader, "PRIVATE KEY"); if (section == null) { throw new IOException("Invalid PKCS8 data."); } byte[] bytes = section.getBase64DecodedBytes(); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes); try { KeyFactory keyFactory = SecurityUtils.getRsaKeyFactory(); return keyFactory.generatePrivate(keySpec); } catch (NoSuchAlgorithmException | InvalidKeySpecException exception) { throw new IOException("Unexpected exception reading PKCS data", exception); } }
Example #10
Source File: JsonWebSignature.java From google-http-java-client with Apache License 2.0 | 5 votes |
/** * {@link Beta} <br> * Verifies the signature of the content using the certificate chain embedded in the signature. * * <p>Currently only {@code "RS256"} and {@code "ES256"} algorithms are verified, but others may * be added in the future. For any other algorithm it returns {@code null}. * * <p>The leaf certificate of the certificate chain must be an SSL server certificate. * * @param trustManager trust manager used to verify the X509 certificate chain embedded in this * message * @return the signature certificate if the signature could be verified, null otherwise * @throws GeneralSecurityException * @since 1.19.1 */ @Beta public final X509Certificate verifySignature(X509TrustManager trustManager) throws GeneralSecurityException { List<String> x509Certificates = getHeader().getX509Certificates(); if (x509Certificates == null || x509Certificates.isEmpty()) { return null; } String algorithm = getHeader().getAlgorithm(); if ("RS256".equals(algorithm)) { return SecurityUtils.verify( SecurityUtils.getSha256WithRsaSignatureAlgorithm(), trustManager, x509Certificates, signatureBytes, signedContentBytes); } else if ("ES256".equals(algorithm)) { return SecurityUtils.verify( SecurityUtils.getEs256SignatureAlgorithm(), trustManager, x509Certificates, DerEncoder.encode(signatureBytes), signedContentBytes); } else { return null; } }
Example #11
Source File: SecurityTestUtils.java From google-http-java-client with Apache License 2.0 | 4 votes |
/** Returns a new sample RSA public key that matches {@link #newRsaPrivateKey()}. */ public static RSAPublicKey newRsaPublicKey() throws GeneralSecurityException { KeyFactory keyFactory = SecurityUtils.getRsaKeyFactory(); KeySpec keySpec = new X509EncodedKeySpec(ENCODED_PUBLIC_KEY); return (RSAPublicKey) keyFactory.generatePublic(keySpec); }
Example #12
Source File: SecurityTestUtils.java From google-http-java-client with Apache License 2.0 | 4 votes |
/** Returns a new sample RSA private key that matches {@link #newRsaPublicKey()}. */ public static RSAPrivateKey newRsaPrivateKey() throws GeneralSecurityException { KeyFactory keyFactory = SecurityUtils.getRsaKeyFactory(); KeySpec keySpec = new PKCS8EncodedKeySpec(ENCODED_PRIVATE_KEY); return (RSAPrivateKey) keyFactory.generatePrivate(keySpec); }
Example #13
Source File: TestCertificates.java From google-http-java-client with Apache License 2.0 | 4 votes |
public Certificate getCertfificate() throws IOException, CertificateException { byte[] bytes = getDer(); ByteArrayInputStream bis = new ByteArrayInputStream(bytes); return SecurityUtils.getX509CertificateFactory().generateCertificate(bis); }
Example #14
Source File: OAuthRsaSigner.java From google-oauth-java-client with Apache License 2.0 | 4 votes |
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 #15
Source File: NetHttpTransport.java From google-http-java-client with Apache License 2.0 | 3 votes |
/** * Sets the SSL socket factory based root certificates generated from the specified stream using * {@link CertificateFactory#generateCertificates(InputStream)}. * * <p>Example usage: * * <pre> * trustCertificatesFromStream(new FileInputStream("certs.pem")); * </pre> * * @param certificateStream certificate stream * @since 1.14 */ public Builder trustCertificatesFromStream(InputStream certificateStream) throws GeneralSecurityException, IOException { KeyStore trustStore = SecurityUtils.getJavaKeyStore(); trustStore.load(null, null); SecurityUtils.loadKeyStoreFromCertificates( trustStore, SecurityUtils.getX509CertificateFactory(), certificateStream); return trustCertificates(trustStore); }
Example #16
Source File: GoogleCredential.java From google-api-java-client with Apache License 2.0 | 3 votes |
/** * Sets the private key to use with the service account flow or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @param p12FileInputStream input stream to the p12 file. This file is closed at the end of * this method in a finally block. */ public Builder setServiceAccountPrivateKeyFromP12File(InputStream p12FileInputStream) throws GeneralSecurityException, IOException { serviceAccountPrivateKey = SecurityUtils.loadPrivateKeyFromKeyStore( SecurityUtils.getPkcs12KeyStore(), p12FileInputStream, "notasecret", "privatekey", "notasecret"); return this; }
Example #17
Source File: GoogleCredential.java From google-api-java-client with Apache License 2.0 | 3 votes |
/** * {@link Beta} <br/> * Sets the private key to use with the service account flow or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @param pemFile input stream to the PEM file (closed at the end of this method in a finally * block) * @since 1.13 */ @Beta public Builder setServiceAccountPrivateKeyFromPemFile(File pemFile) throws GeneralSecurityException, IOException { byte[] bytes = PemReader.readFirstSectionAndClose(new FileReader(pemFile), "PRIVATE KEY") .getBase64DecodedBytes(); serviceAccountPrivateKey = SecurityUtils.getRsaKeyFactory().generatePrivate(new PKCS8EncodedKeySpec(bytes)); return this; }
Example #18
Source File: NetHttpTransport.java From google-http-java-client with Apache License 2.0 | 3 votes |
/** * Sets the SSL socket factory based on root certificates in a Java KeyStore. * * <p>Example usage: * * <pre> * trustCertificatesFromJavaKeyStore(new FileInputStream("certs.jks"), "password"); * </pre> * * @param keyStoreStream input stream to the key store (closed at the end of this method in a * finally block) * @param storePass password protecting the key store file * @since 1.14 */ public Builder trustCertificatesFromJavaKeyStore(InputStream keyStoreStream, String storePass) throws GeneralSecurityException, IOException { KeyStore trustStore = SecurityUtils.getJavaKeyStore(); SecurityUtils.loadKeyStore(trustStore, keyStoreStream, storePass); return trustCertificates(trustStore); }
Example #19
Source File: ApacheHttpTransport.java From google-http-java-client with Apache License 2.0 | 3 votes |
/** * Sets the SSL socket factory based root certificates generated from the specified stream using * {@link CertificateFactory#generateCertificates(InputStream)}. * * <p>Example usage: * * <pre> * trustCertificatesFromStream(new FileInputStream("certs.pem")); * </pre> * * @param certificateStream certificate stream * @since 1.14 */ public Builder trustCertificatesFromStream(InputStream certificateStream) throws GeneralSecurityException, IOException { KeyStore trustStore = SecurityUtils.getJavaKeyStore(); trustStore.load(null, null); SecurityUtils.loadKeyStoreFromCertificates( trustStore, SecurityUtils.getX509CertificateFactory(), certificateStream); return trustCertificates(trustStore); }
Example #20
Source File: ApacheHttpTransport.java From google-http-java-client with Apache License 2.0 | 3 votes |
/** * Sets the SSL socket factory based on root certificates in a Java KeyStore. * * <p>Example usage: * * <pre> * trustCertificatesFromJavaKeyStore(new FileInputStream("certs.jks"), "password"); * </pre> * * @param keyStoreStream input stream to the key store (closed at the end of this method in a * finally block) * @param storePass password protecting the key store file * @since 1.14 */ public Builder trustCertificatesFromJavaKeyStore(InputStream keyStoreStream, String storePass) throws GeneralSecurityException, IOException { KeyStore trustStore = SecurityUtils.getJavaKeyStore(); SecurityUtils.loadKeyStore(trustStore, keyStoreStream, storePass); return trustCertificates(trustStore); }