List of usage examples for java.security KeyStore getKey
public final Key getKey(String alias, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException
From source file:test.integ.be.e_contract.mycarenet.cxf.EHealthSTSClientTest.java
@Test public void testClient() throws Exception { EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService"); Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null);/*w w w .j a va2 s.com*/ PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication"); KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12"); FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path()); eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray()); Enumeration<String> aliasesEnum = eHealthKeyStore.aliases(); String alias = aliasesEnum.nextElement(); X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias); PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias, this.config.getEHealthPKCS12Password().toCharArray()); List<Attribute> attributes = new LinkedList<Attribute>(); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>(); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributeDesignators .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth", "urn:be:fgov:person:ssin:nurse:boolean")); Element assertionElement = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate, eHealthPrivateKey, attributes, attributeDesignators); assertNotNull(assertionElement); LOG.debug("assertion: " + toString(assertionElement)); LOG.debug("not after: " + client.getNotAfter(assertionElement)); }
From source file:test.integ.be.e_contract.mycarenet.cxf.SyncClientTest.java
@Test public void testEchoViaInvoke() throws Exception { // setup/*ww w. jav a 2 s . c o m*/ String xkms2Location = "https://pilot.mycarenet.be/mycarenet-ws/care-provider/xkms2"; XKMS2Client xkms2Client = new XKMS2Client(xkms2Location); SessionKey sessionKey = new SessionKey(); Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null); PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication"); // operate xkms2Client.registerSessionKey(sessionKey, authnPrivateKey, authnCertificate); // verify assertTrue(sessionKey.isValid()); try { // setup Config config = new Config(); PackageLicenseKey packageLicenseKey = config.getPackageLicenseKey(); LOG.debug("package license key username: " + packageLicenseKey.getUsername()); LOG.debug("package license key password: " + packageLicenseKey.getPassword()); SyncClient syncClient = new SyncClient("https://pilot.mycarenet.be/services/care-provider/sync", sessionKey, packageLicenseKey); String result = syncClient .invoke("<EchoRequest xmlns=\"urn:be:cin:mycarenet:1.0:sync:types\" xml:lang=\"en\">" + "<test/>" + "</EchoRequest>"); // verify LOG.debug("result: " + result); } finally { // operate xkms2Client.revokeSessionKey(sessionKey, authnPrivateKey, authnCertificate); // verify assertFalse(sessionKey.isValid()); } }
From source file:test.integ.be.e_contract.mycarenet.cxf.CXFTest.java
@Test public void testRegisterRevokeSessionKey() throws Exception { // setup/* w w w. j a v a 2 s.c o m*/ String xkms2Location = "https://pilot.mycarenet.be/mycarenet-ws/care-provider/xkms2"; XKMS2Client xkms2Client = new XKMS2Client(xkms2Location); SessionKey sessionKey = new SessionKey(); Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null); PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication"); // operate xkms2Client.registerSessionKey(sessionKey, authnPrivateKey, authnCertificate); // verify assertTrue(sessionKey.isValid()); // operate xkms2Client.revokeSessionKey(sessionKey, authnPrivateKey, authnCertificate); // verify assertFalse(sessionKey.isValid()); }
From source file:test.integ.be.e_contract.mycarenet.cxf.CXFTest.java
@Test public void testRegisterViaXKMS2RevokeViaXKMS1() throws Exception { // setup//from ww w . java 2 s .c om String xkms2Location = "https://pilot.mycarenet.be/mycarenet-ws/care-provider/xkms2"; XKMS2Client xkms2Client = new XKMS2Client(xkms2Location); SessionKey sessionKey = new SessionKey(); String xkmsLocation = "https://pilot.mycarenet.be/mycarenet-ws/care-provider/xkms"; XKMSClient xkmsClient = new XKMSClient(xkmsLocation); Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null); PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication"); // operate xkms2Client.registerSessionKey(sessionKey, authnPrivateKey, authnCertificate); // verify assertTrue(sessionKey.isValid()); // operate xkmsClient.revokeSessionKey(sessionKey); // verify assertFalse(sessionKey.isValid()); }
From source file:service.GoogleCalendarAuth.java
public GoogleCalendarAuth(String client_id, String key) { final long now = System.currentTimeMillis() / 1000L; final long exp = now + 3600; final char[] password = "notasecret".toCharArray(); final String claim = "{\"iss\":\"" + client_id + "\"," + "\"scope\":\"" + SCOPE + "\"," + "\"aud\":\"https://accounts.google.com/o/oauth2/token\"," + "\"exp\":" + exp + "," + // "\"prn\":\"some.user@somecorp.com\"," + // This require some.user to have their email served from a googlemail domain? "\"iat\":" + now + "}"; try {// w w w . j a va2 s .c om final String jwt = Base64.encodeBase64URLSafeString(jwt_header.getBytes()) + "." + Base64.encodeBase64URLSafeString(claim.getBytes("UTF-8")); final byte[] jwt_data = jwt.getBytes("UTF8"); final Signature sig = Signature.getInstance("SHA256WithRSA"); final KeyStore ks = java.security.KeyStore.getInstance("PKCS12"); ks.load(new FileInputStream(key), password); sig.initSign((PrivateKey) ks.getKey("privatekey", password)); sig.update(jwt_data); final byte[] signatureBytes = sig.sign(); final String b64sig = Base64.encodeBase64URLSafeString(signatureBytes); final String assertion = jwt + "." + b64sig; //System.out.println("Assertion: " + assertion); final String data = "grant_type=assertion" + "&assertion_type=" + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8") + "&assertion=" + URLEncoder.encode(assertion, "UTF-8"); // Make the Access Token Request URLConnection conn = null; try { final URL url = new URL("https://accounts.google.com/o/oauth2/token"); conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (line.split(":").length > 0) if (line.split(":")[0].trim().equals("\"access_token\"")) access_token = line.split(":")[1].trim().replace("\"", "").replace(",", ""); System.out.println(line); } wr.close(); rd.close(); } catch (Exception ex) { final InputStream error = ((HttpURLConnection) conn).getErrorStream(); final BufferedReader br = new BufferedReader(new InputStreamReader(error)); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) sb.append(line); System.out.println("Error: " + ex + "\n " + sb.toString()); } System.out.println("access_token=" + access_token); } catch (Exception ex) { System.out.println("Error: " + ex); } }
From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImplIT.java
/** * @throws java.lang.Exception/*from w w w . j a v a 2 s . c om*/ */ @BeforeClass @Ignore public static void setUpBeforeCLass() throws Exception { Security.addProvider(new BouncyCastleProvider()); // Create some test username and passwords for services serviceURI = new URI("http://someservice"); usernamePassword = new UsernamePassword("testuser", "testpasswd"); serviceURI2 = new URI("http://someservice2"); usernamePassword2 = new UsernamePassword("testuser2", "testpasswd2"); serviceURI3 = new URI("http://someservice3"); usernamePassword3 = new UsernamePassword("testuser3", "testpasswd3"); // Load the test private key and its certificate File privateKeyCertFile = new File(privateKeyFileURL.getPath()); KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!! FileInputStream inStream = new FileInputStream(privateKeyCertFile); pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray()); // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword); Enumeration<String> aliases = pkcs12Keystore.aliases(); while (aliases.hasMoreElements()) { // The test-private-key-cert.p12 file contains only one private key // and corresponding certificate entry String alias = aliases.nextElement(); if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry? privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray()); privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias); break; } } inStream.close(); // Load the test trusted certificate (belonging to *.Google.com) File trustedCertFile = new File(trustedCertficateGoogleFileURL.getPath()); inStream = new FileInputStream(trustedCertFile); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); trustedCertficateGoogle = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } // Load the test trusted certificate (belonging to heater.cs.man.ac.uk) File trustedCertFile2 = new File(trustedCertficateHeaterFileURL.getPath()); inStream = new FileInputStream(trustedCertFile2); trustedCertficateHeater = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } credentialManager = new CredentialManagerImpl(); // // The code below sets up the Keystore and Truststore files and loads some data into them // // and saves them into a temp directory. These files can later be used for testing the Credential // // Manager with non-empty keystores. // Random randomGenerator = new Random(); // String credentialManagerDirectoryPath = System // .getProperty("java.io.tmpdir") // + System.getProperty("file.separator") // + "taverna-security-" // + randomGenerator.nextInt(1000000); // System.out.println("Credential Manager's directory path: " // + credentialManagerDirectoryPath); // credentialManagerDirectory = new File(credentialManagerDirectoryPath); // credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory); // // // Create the dummy master password provider // masterPasswordProvider = new DummyMasterPasswordProvider(); // masterPasswordProvider.setMasterPassword(masterPassword); // List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>(); // masterPasswordProviders.add(masterPasswordProvider); // credentialManager.setMasterPasswordProviders(masterPasswordProviders); // // // Add some stuff into Credential Manager // credentialManager.addUsernameAndPasswordForService(usernamePassword, serviceURI); // credentialManager.addUsernameAndPasswordForService(usernamePassword2, serviceURI2); // credentialManager.addUsernameAndPasswordForService(usernamePassword3, serviceURI3); // credentialManager.addKeyPair(privateKey, privateKeyCertChain); // credentialManager.addTrustedCertificate(trustedCertficate); // Set up a random temp directory and copy the test keystore files // from resources/security Random randomGenerator = new Random(); String credentialManagerDirectoryPath = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "taverna-security-" + randomGenerator.nextInt(1000000); System.out.println("Credential Manager's directory path: " + credentialManagerDirectoryPath); credentialManagerDirectory = new File(credentialManagerDirectoryPath); if (!credentialManagerDirectory.exists()) { credentialManagerDirectory.mkdir(); } URL keystoreFileURL = CredentialManagerImplIT.class.getResource("/security/t2keystore.ubr"); File keystoreFile = new File(keystoreFileURL.getPath()); File keystoreDestFile = new File(credentialManagerDirectory, "taverna-keystore.ubr"); URL truststroreFileURL = CredentialManagerImplIT.class.getResource("/security/t2truststore.ubr"); File truststoreFile = new File(truststroreFileURL.getPath()); File truststoreDestFile = new File(credentialManagerDirectory, "taverna-truststore.ubr"); FileUtils.copyFile(keystoreFile, keystoreDestFile); FileUtils.copyFile(truststoreFile, truststoreDestFile); credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory.toPath()); // Create the dummy master password provider masterPasswordProvider = new DummyMasterPasswordProvider(); masterPasswordProvider.setMasterPassword(masterPassword); List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>(); masterPasswordProviders.add(masterPasswordProvider); credentialManager.setMasterPasswordProviders(masterPasswordProviders); // Set an empty list for trust confirmation providers credentialManager.setTrustConfirmationProviders(new ArrayList<TrustConfirmationProvider>()); keystoreChangedObserver = new Observer<KeystoreChangedEvent>() { @Override public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message) throws Exception { // TODO Auto-generated method stub } }; credentialManager.addObserver(keystoreChangedObserver); }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplIT.java
/** * @throws java.lang.Exception/* w ww .j a va2 s . c om*/ */ @BeforeClass @Ignore public static void setUpBeforeCLass() throws Exception { Security.addProvider(new BouncyCastleProvider()); // Create some test username and passwords for services serviceURI = new URI("http://someservice"); usernamePassword = new UsernamePassword("testuser", "testpasswd"); serviceURI2 = new URI("http://someservice2"); usernamePassword2 = new UsernamePassword("testuser2", "testpasswd2"); serviceURI3 = new URI("http://someservice3"); usernamePassword3 = new UsernamePassword("testuser3", "testpasswd3"); // Load the test private key and its certificate File privateKeyCertFile = new File(privateKeyFileURL.getPath()); KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!! FileInputStream inStream = new FileInputStream(privateKeyCertFile); pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray()); // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword); Enumeration<String> aliases = pkcs12Keystore.aliases(); while (aliases.hasMoreElements()) { // The test-private-key-cert.p12 file contains only one private key // and corresponding certificate entry String alias = aliases.nextElement(); if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry? privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray()); privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias); break; } } inStream.close(); // Load the test trusted certificate (belonging to *.Google.com) File trustedCertFile = new File(trustedCertficateGoogleFileURL.getPath()); inStream = new FileInputStream(trustedCertFile); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); trustedCertficateGoogle = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } // Load the test trusted certificate (belonging to heater.cs.man.ac.uk) File trustedCertFile2 = new File(trustedCertficateHeaterFileURL.getPath()); inStream = new FileInputStream(trustedCertFile2); trustedCertficateHeater = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } credentialManager = new CredentialManagerImpl(); // // The code below sets up the Keystore and Truststore files and loads some data into them // // and saves them into a temp directory. These files can later be used for testing the Credential // // Manager with non-empty keystores. // Random randomGenerator = new Random(); // String credentialManagerDirectoryPath = System // .getProperty("java.io.tmpdir") // + System.getProperty("file.separator") // + "taverna-security-" // + randomGenerator.nextInt(1000000); // System.out.println("Credential Manager's directory path: " // + credentialManagerDirectoryPath); // credentialManagerDirectory = new File(credentialManagerDirectoryPath); // credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory); // // // Create the dummy master password provider // masterPasswordProvider = new DummyMasterPasswordProvider(); // masterPasswordProvider.setMasterPassword(masterPassword); // List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>(); // masterPasswordProviders.add(masterPasswordProvider); // credentialManager.setMasterPasswordProviders(masterPasswordProviders); // // // Add some stuff into Credential Manager // credentialManager.addUsernameAndPasswordForService(usernamePassword, serviceURI); // credentialManager.addUsernameAndPasswordForService(usernamePassword2, serviceURI2); // credentialManager.addUsernameAndPasswordForService(usernamePassword3, serviceURI3); // credentialManager.addKeyPair(privateKey, privateKeyCertChain); // credentialManager.addTrustedCertificate(trustedCertficate); // Set up a random temp directory and copy the test keystore files // from resources/security Random randomGenerator = new Random(); String credentialManagerDirectoryPath = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "taverna-security-" + randomGenerator.nextInt(1000000); System.out.println("Credential Manager's directory path: " + credentialManagerDirectoryPath); credentialManagerDirectory = new File(credentialManagerDirectoryPath); if (!credentialManagerDirectory.exists()) { credentialManagerDirectory.mkdir(); } URL keystoreFileURL = CredentialManagerImplIT.class.getResource("/security/t2keystore.ubr"); File keystoreFile = new File(keystoreFileURL.getPath()); File keystoreDestFile = new File(credentialManagerDirectory, "taverna-keystore.ubr"); URL truststroreFileURL = CredentialManagerImplIT.class.getResource("/security/t2truststore.ubr"); File truststoreFile = new File(truststroreFileURL.getPath()); File truststoreDestFile = new File(credentialManagerDirectory, "taverna-truststore.ubr"); FileUtils.copyFile(keystoreFile, keystoreDestFile); FileUtils.copyFile(truststoreFile, truststoreDestFile); credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory); // Create the dummy master password provider masterPasswordProvider = new DummyMasterPasswordProvider(); masterPasswordProvider.setMasterPassword(masterPassword); List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>(); masterPasswordProviders.add(masterPasswordProvider); credentialManager.setMasterPasswordProviders(masterPasswordProviders); // Set an empty list for trust confirmation providers credentialManager.setTrustConfirmationProviders(new ArrayList<TrustConfirmationProvider>()); keystoreChangedObserver = new Observer<KeystoreChangedEvent>() { @Override public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message) throws Exception { // TODO Auto-generated method stub } }; credentialManager.addObserver(keystoreChangedObserver); }
From source file:test.integ.be.e_contract.mycarenet.cxf.SyncClientTest.java
@Test public void testEcho() throws Exception { // setup// w ww . jav a2 s.c o m String xkms2Location = "https://pilot.mycarenet.be/mycarenet-ws/care-provider/xkms2"; XKMS2Client xkms2Client = new XKMS2Client(xkms2Location); SessionKey sessionKey = new SessionKey(); Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null); PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication"); // operate xkms2Client.registerSessionKey(sessionKey, authnPrivateKey, authnCertificate); // verify assertTrue(sessionKey.isValid()); try { // setup Config config = new Config(); PackageLicenseKey packageLicenseKey = config.getPackageLicenseKey(); LOG.debug("package license key username: " + packageLicenseKey.getUsername()); LOG.debug("package license key password: " + packageLicenseKey.getPassword()); SyncClient syncClient = new SyncClient("https://pilot.mycarenet.be/services/care-provider/sync", sessionKey, packageLicenseKey); ObjectFactory objectFactory = new ObjectFactory(); XmlDocumentWrapperType request = objectFactory.createXmlDocumentWrapperType(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element element = document.createElement("test"); request.setAny(element); request.setLang("en"); // operate XmlDocumentWrapperType result; try { result = syncClient.echo(request); } finally { LOG.debug("payload: " + syncClient.getPayload()); } // verify assertEquals(result.getAny().getNodeName(), "test"); } finally { // operate xkms2Client.revokeSessionKey(sessionKey, authnPrivateKey, authnCertificate); // verify assertFalse(sessionKey.isValid()); } }
From source file:cloud.google.oauth2.MyWayAuthentication.java
/** * Load p12 file get private key/*from w ww. j a v a 2s . c om*/ * */ private PrivateKey getPrivateKey(String keyFile, String password) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException { KeyStore keystore = KeyStore.getInstance("PKCS12"); keystore.load(new FileInputStream(keyFile), password.toCharArray()); PrivateKey privateKey = (PrivateKey) keystore.getKey(GCDStatic.getKeyAlias(), password.toCharArray()); return privateKey; }
From source file:GCS_Auth.java
public GCS_Auth(String client_id, String key) { String SCOPE = "https://www.googleapis.com/auth/shoppingapi"; SCOPE = SCOPE + " " + "https://www.googleapis.com/auth/structuredcontent"; try {/*from www.ja v a 2 s . c om*/ String jwt_header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}"; long now = System.currentTimeMillis() / 1000L; long exp = now + 3600; String iss = client_id; String claim = "{\"iss\":\"" + iss + "\",\"scope\":\"" + SCOPE + "\",\"aud\":\"https://accounts.google.com/o/oauth2/token\",\"exp\":" + exp + ",\"iat\":" + now + "}"; String jwt = Base64.encodeBase64URLSafeString(jwt_header.getBytes()) + "." + Base64.encodeBase64URLSafeString(claim.getBytes("UTF-8")); byte[] jwt_data = jwt.getBytes("UTF8"); Signature sig = Signature.getInstance("SHA256WithRSA"); KeyStore ks = java.security.KeyStore.getInstance("PKCS12"); ks.load(new FileInputStream(key), "notasecret".toCharArray()); sig.initSign((PrivateKey) ks.getKey("privatekey", "notasecret".toCharArray())); sig.update(jwt_data); byte[] signatureBytes = sig.sign(); String b64sig = Base64.encodeBase64URLSafeString(signatureBytes); String assertion = jwt + "." + b64sig; //System.out.println("Assertion: " + assertion); String data = "grant_type=assertion"; data += "&" + "assertion_type" + "=" + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8"); data += "&" + "assertion=" + URLEncoder.encode(assertion, "UTF-8"); URLConnection conn = null; try { URL url = new URL("https://accounts.google.com/o/oauth2/token"); conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (line.split(":").length > 0) if (line.split(":")[0].trim().equals("\"access_token\"")) access_token = line.split(":")[1].trim().replace("\"", "").replace(",", ""); System.out.println(line); } wr.close(); rd.close(); } catch (Exception ex) { InputStream error = ((HttpURLConnection) conn).getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(error)); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } System.out.println("Error: " + ex + "\n " + sb.toString()); } //System.out.println(access_token); } catch (Exception ex) { System.out.println("Error: " + ex); } }