List of usage examples for org.bouncycastle.util.encoders Base64 encode
public static byte[] encode(byte[] data)
From source file:com.eucalyptus.objectstorage.pipeline.handlers.ObjectStorageFormPOSTAuthenticationHandler.java
License:Open Source License
protected String checkSignature(final String queryKey, final String subject) throws AuthenticationException { SecretKeySpec signingKey = new SecretKeySpec(queryKey.getBytes(), Hmac.HmacSHA1.toString()); try {/*from w ww . ja va 2s . co m*/ Mac mac = Hmac.HmacSHA1.getInstance(); mac.init(signingKey); byte[] rawHmac = mac.doFinal(subject.getBytes()); return new String(Base64.encode(rawHmac)).replaceAll("=", ""); } catch (Exception e) { LOG.error(e, e); throw new AuthenticationException("Failed to compute signature"); } }
From source file:com.eucalyptus.objectstorage.pipeline.handlers.UploadPolicyChecker.java
License:Open Source License
public static void checkPolicy(Map<String, String> formFields) throws S3Exception { if (formFields.containsKey(ObjectStorageProperties.FormField.Policy.toString())) { String policy = new String( Base64.decode(formFields.get(ObjectStorageProperties.FormField.Policy.toString()))); String policyData;/*from w w w.ja va2 s.co m*/ try { policyData = new String(Base64.encode(policy.getBytes())); } catch (Exception ex) { LOG.warn("Denying POST upload due to inability to decode/read required upload Policy from request", ex); throw new InvalidPolicyDocumentException(policy, "Invalid policy content"); } //parse policy try { JsonSlurper jsonSlurper = new JsonSlurper(); JSONObject policyObject = (JSONObject) jsonSlurper.parseText(policy); String expiration = (String) policyObject .get(ObjectStorageProperties.PolicyHeaders.expiration.toString()); if (expiration != null) { Date expirationDate = DateUtils.parseIso8601DateTimeOrDate(expiration); if ((new Date()).getTime() > expirationDate.getTime()) { LOG.warn("Denying POST upload because included policy has expired."); throw new InvalidPolicyDocumentException(expiration, "Expired policy: " + expiration); } } List<String> policyItemNames = new ArrayList<String>(); JSONArray conditions = (JSONArray) policyObject .get(ObjectStorageProperties.PolicyHeaders.conditions.toString()); for (int i = 0; i < conditions.size(); ++i) { Object policyItem = conditions.get(i); if (policyItem instanceof JSONObject) { JSONObject jsonObject = (JSONObject) policyItem; if (!exactMatch(jsonObject, formFields, policyItemNames)) { LOG.warn( "Denying POST upload because Policy verification failed due to mismatch of conditions"); throw new InvalidPolicyDocumentException(jsonObject.toString(), "Policy conditions not met"); } } else if (policyItem instanceof JSONArray) { JSONArray jsonArray = (JSONArray) policyItem; if (!partialMatch(jsonArray, formFields, policyItemNames)) { LOG.warn( "Denying POST upload because Policy verification failed due to mismatch of conditions"); throw new InvalidPolicyDocumentException(jsonArray.toString(), "Policy conditions not met"); } } } Set<String> formFieldsKeys = formFields.keySet(); for (String formKey : formFieldsKeys) { if (formKey.startsWith(ObjectStorageProperties.IGNORE_PREFIX)) continue; boolean fieldOkay = false; for (ObjectStorageProperties.IgnoredFields field : ObjectStorageProperties.IgnoredFields .values()) { if (formKey.equals(field.toString())) { fieldOkay = true; break; } } if (fieldOkay) continue; if (policyItemNames.contains(formKey)) continue; if (ObjectStorageProperties.FormField.isHttpField(formKey)) { //Allow the http header fields if in the form but not in policy conditions. The S3 spec is ambiguous on this // but the behavior indicates content-type, in particular, is not required in the policy conditions. continue; } LOG.warn( "Denying POST upload due to: All fields except those marked with x-ignore- should be in policy. Form Key: " + formKey); throw new InvalidPolicyDocumentException(formKey, "All fields except those marked with x-ignore- should be in policy."); } } catch (S3Exception e) { //pass thru throw e; } catch (Exception ex) { //rethrow LOG.error("Denying POST upload due to: Unexpected exception during POST policy checks", ex); throw new InvalidPolicyDocumentException(policy, "Error processing the policy"); } } }
From source file:com.eucalyptus.objectstorage.pipeline.UploadPolicyChecker.java
License:Open Source License
public static void checkPolicy(MappingHttpRequest httpRequest, Map<String, String> formFields) throws AuthenticationException { if (formFields.containsKey(WalrusProperties.FormField.policy.toString())) { String authenticationHeader = ""; String policy = new String( Base64.decode(formFields.remove(WalrusProperties.FormField.policy.toString()))); String policyData;//w w w . j a va 2 s .c o m try { policyData = new String(Base64.encode(policy.getBytes())); } catch (Exception ex) { LOG.warn(ex, ex); throw new AuthenticationException("error reading policy data."); } //parse policy try { JsonSlurper jsonSlurper = new JsonSlurper(); JSONObject policyObject = (JSONObject) jsonSlurper.parseText(policy); String expiration = (String) policyObject.get(WalrusProperties.PolicyHeaders.expiration.toString()); if (expiration != null) { Date expirationDate = DateUtils.parseIso8601DateTimeOrDate(expiration); if ((new Date()).getTime() > expirationDate.getTime()) { LOG.warn("Policy has expired."); throw new AuthenticationException("Policy has expired."); } } List<String> policyItemNames = new ArrayList<String>(); JSONArray conditions = (JSONArray) policyObject .get(WalrusProperties.PolicyHeaders.conditions.toString()); for (int i = 0; i < conditions.size(); ++i) { Object policyItem = conditions.get(i); if (policyItem instanceof JSONObject) { JSONObject jsonObject = (JSONObject) policyItem; if (!exactMatch(jsonObject, formFields, policyItemNames)) { LOG.warn("Policy verification failed. "); throw new AuthenticationException("Policy verification failed."); } } else if (policyItem instanceof JSONArray) { JSONArray jsonArray = (JSONArray) policyItem; if (!partialMatch(jsonArray, formFields, policyItemNames)) { LOG.warn("Policy verification failed. "); throw new AuthenticationException("Policy verification failed."); } } } Set<String> formFieldsKeys = formFields.keySet(); for (String formKey : formFieldsKeys) { if (formKey.startsWith(WalrusProperties.IGNORE_PREFIX)) continue; boolean fieldOkay = false; for (WalrusProperties.IgnoredFields field : WalrusProperties.IgnoredFields.values()) { if (formKey.equals(field.toString())) { fieldOkay = true; break; } } if (fieldOkay) continue; if (policyItemNames.contains(formKey)) continue; LOG.error("All fields except those marked with x-ignore- should be in policy. Form Key: " + formKey); throw new AuthenticationException( "All fields except those marked with x-ignore- should be in policy."); } } catch (Exception ex) { //rethrow LOG.warn(ex); throw new AuthenticationException(ex); } //all form uploads without a policy are anonymous if (formFields.containsKey(WalrusProperties.FormField.AWSAccessKeyId.toString())) { String accessKeyId = formFields.remove(WalrusProperties.FormField.AWSAccessKeyId.toString()); authenticationHeader += "AWS" + " " + accessKeyId + ":"; } if (formFields.containsKey(WalrusProperties.FormField.signature.toString())) { String signature = formFields.remove(WalrusProperties.FormField.signature.toString()); authenticationHeader += signature; httpRequest.addHeader(WalrusPOSTAuthenticationHandler.SecurityParameter.Authorization.toString(), authenticationHeader); } httpRequest.addHeader(WalrusProperties.FormField.FormUploadPolicyData.toString(), policyData); } }
From source file:com.eucalyptus.objectstorage.util.OSGUtil.java
License:Open Source License
public static String encryptWithComponentPublicKey(Class<? extends ComponentId> componentClass, String data) throws EucalyptusCloudException { try {//from w w w . ja v a2s .c o m PublicKey clcPublicKey = SystemCredentials.lookup(componentClass).getCertificate().getPublicKey(); Cipher cipher = Ciphers.RSA_PKCS1.get(); cipher.init(Cipher.ENCRYPT_MODE, clcPublicKey); return new String(Base64.encode(cipher.doFinal(data.getBytes("UTF-8")))); } catch (Exception e) { throw new EucalyptusCloudException("Unable to encrypt data: " + e.getMessage(), e); } }
From source file:com.eucalyptus.sla.VmAdmissionControl.java
License:Open Source License
public VmAllocationInfo verify(RunInstancesType request) throws EucalyptusCloudException { //:: encapsulate the request into a VmAllocationInfo object and forward it on ::// VmAllocationInfo vmAllocInfo = new VmAllocationInfo(request); if (vmAllocInfo.getRequest().getInstanceType() == null || "".equals(vmAllocInfo.getRequest().getInstanceType())) { vmAllocInfo.getRequest().setInstanceType(VmInstance.DEFAULT_TYPE); }//from w w w . ja v a 2 s. co m vmAllocInfo.setReservationIndex(Counters.getIdBlock(request.getMaxCount())); byte[] userData = new byte[0]; if (vmAllocInfo.getRequest().getUserData() != null) { try { userData = Base64.decode(vmAllocInfo.getRequest().getUserData()); } catch (Exception e) { } } vmAllocInfo.setUserData(userData); vmAllocInfo.getRequest().setUserData(new String(Base64.encode(userData))); return vmAllocInfo; }
From source file:com.eucalyptus.util.BlockStorageUtil.java
License:Open Source License
public static String encryptNodeTargetPassword(String password) throws EucalyptusCloudException { try {/*from w w w .j a v a2 s.com*/ List<ServiceConfiguration> clusterList = ServiceConfigurations.listPartition(ClusterController.class, StorageProperties.NAME); if (clusterList.size() < 1) { String msg = "Failed to find a cluster with the corresponding partition name for this SC: " + StorageProperties.NAME + "\nFound: " + clusterList.toString().replaceAll(", ", ",\n"); throw new EucalyptusCloudException(msg); } else { ServiceConfiguration clusterConfig = clusterList.get(0); PublicKey ncPublicKey = Partitions.lookup(clusterConfig).getNodeCertificate().getPublicKey(); Cipher cipher = Ciphers.RSA_PKCS1.get(); cipher.init(Cipher.ENCRYPT_MODE, ncPublicKey); return new String(Base64.encode(cipher.doFinal(password.getBytes()))); } } catch (Exception e) { LOG.error("Unable to encrypt storage target password: " + e.getMessage(), e); throw new EucalyptusCloudException("Unable to encrypt storage target password: " + e.getMessage(), e); } }
From source file:com.eucalyptus.vm.VmInstance.java
License:Open Source License
public String getConsoleOutputString() { return new String(Base64.encode(this.getRuntimeState().getConsoleOutput().toString().getBytes())); }
From source file:com.geoxp.oss.client.OSSClient.java
License:Apache License
public static void genSecret(String ossURL, String secretName, String sshKeyFingerprint) throws OSSException { SSHAgentClient agent = null;//from www . j a va 2s .c o m HttpClient httpclient = null; try { agent = new SSHAgentClient(); List<SSHKey> sshkeys = agent.requestIdentities(); // // If no SSH Key fingerprint was provided, try all SSH keys available in the agent // List<String> fingerprints = new ArrayList<String>(); if (null == sshKeyFingerprint) { for (SSHKey key : sshkeys) { fingerprints.add(key.fingerprint); } } else { fingerprints.add(sshKeyFingerprint.toLowerCase().replaceAll("[^0-9a-f]", "")); } int idx = 0; for (String fingerprint : fingerprints) { idx++; // // Check if the signing key is available in the agent // byte[] keyblob = null; for (SSHKey key : sshkeys) { if (key.fingerprint.equals(fingerprint)) { keyblob = key.blob; break; } } // // Throw an exception if this condition is encountered as it can only happen if // there was a provided fingerprint which is not in the agent. // if (null == keyblob) { throw new OSSException("SSH Key " + sshKeyFingerprint + " was not found by your SSH agent."); } // // Build OSS Token // // <TS> <SECRET_NAME> <SSH Signing Key Blob> <SSH Signature Blob> // ByteArrayOutputStream token = new ByteArrayOutputStream(); byte[] tsdata = nowBytes(); token.write(CryptoHelper.encodeNetworkString(tsdata)); token.write(CryptoHelper.encodeNetworkString(secretName.getBytes("UTF-8"))); token.write(CryptoHelper.encodeNetworkString(keyblob)); // // Generate signature // byte[] sigblob = agent.sign(keyblob, token.toByteArray()); token.write(CryptoHelper.encodeNetworkString(sigblob)); String b64token = new String(Base64.encode(token.toByteArray()), "UTF-8"); // // Send request // httpclient = new DefaultHttpClient(); URIBuilder builder = new URIBuilder(ossURL + GuiceServletModule.SERVLET_PATH_GEN_SECRET); builder.addParameter("token", b64token); URI uri = builder.build(); String qs = uri.getRawQuery(); HttpPost post = new HttpPost( uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + uri.getPath()); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(new StringEntity(qs)); HttpResponse response = httpclient.execute(post); post.reset(); if (HttpServletResponse.SC_OK != response.getStatusLine().getStatusCode()) { // Only throw an exception if this is the last SSH key we could try if (idx == fingerprints.size()) { throw new OSSException("None of the provided keys (" + idx + ") could be used to generate secret. Latest error message was: " + response.getStatusLine().getReasonPhrase()); } else { continue; } } return; } } catch (OSSException osse) { throw osse; } catch (Exception e) { throw new OSSException(e); } finally { if (null != httpclient) { httpclient.getConnectionManager().shutdown(); } if (null != agent) { agent.close(); } } }
From source file:com.geoxp.oss.client.OSSClient.java
License:Apache License
public static byte[] getSecret(String ossURL, String secretName, String sshKeyFingerprint) throws OSSException { SSHAgentClient agent = null;/*from www. j a v a 2 s. c om*/ HttpClient httpclient = null; try { agent = new SSHAgentClient(); List<SSHKey> sshkeys = agent.requestIdentities(); // // If no SSH Key fingerprint was provided, try all SSH keys available in the agent // List<String> fingerprints = new ArrayList<String>(); if (null == sshKeyFingerprint) { for (SSHKey key : sshkeys) { fingerprints.add(key.fingerprint); } } else { fingerprints.add(sshKeyFingerprint.toLowerCase().replaceAll("[^0-9a-f]", "")); } int idx = 0; for (String fingerprint : fingerprints) { idx++; // // Check if the signing key is available in the agent // byte[] keyblob = null; for (SSHKey key : sshkeys) { if (key.fingerprint.equals(fingerprint)) { keyblob = key.blob; break; } } // // Throw an exception if this condition is encountered as it can only happen if // there was a provided fingerprint which is not in the agent. // if (null == keyblob) { throw new OSSException("SSH Key " + sshKeyFingerprint + " was not found by your SSH agent."); } // // Generate temporary RSA key pair // RSAKeyPairGenerator rsagen = new RSAKeyPairGenerator(); RSAKeyGenerationParameters params = new RSAKeyGenerationParameters(new BigInteger("65537"), CryptoHelper.getSecureRandom(), 2048, 64); rsagen.init(params); final AsymmetricCipherKeyPair keypair = rsagen.generateKeyPair(); RSAPrivateKey rsapriv = new RSAPrivateKey() { public BigInteger getModulus() { return ((RSAKeyParameters) keypair.getPrivate()).getModulus(); } public String getFormat() { return "PKCS#8"; } public byte[] getEncoded() { return null; } public String getAlgorithm() { return "RSA"; } public BigInteger getPrivateExponent() { return ((RSAKeyParameters) keypair.getPrivate()).getExponent(); } }; RSAPublicKey rsapub = new RSAPublicKey() { public BigInteger getModulus() { return ((RSAKeyParameters) keypair.getPublic()).getModulus(); } public String getFormat() { return "PKCS#8"; } public byte[] getEncoded() { return null; } public String getAlgorithm() { return "RSA"; } public BigInteger getPublicExponent() { return ((RSAKeyParameters) keypair.getPublic()).getExponent(); } }; // // Build OSS Token // // <TS> <<SECRET_NAME> <RSA_ENC_KEY>> <SSH Signing Key Blob> <SSH Signature Blob> // ByteArrayOutputStream token = new ByteArrayOutputStream(); byte[] tsdata = nowBytes(); token.write(CryptoHelper.encodeNetworkString(tsdata)); ByteArrayOutputStream subtoken = new ByteArrayOutputStream(); subtoken.write(CryptoHelper.encodeNetworkString(secretName.getBytes("UTF-8"))); subtoken.write(CryptoHelper.encodeNetworkString(CryptoHelper.sshKeyBlobFromPublicKey(rsapub))); token.write(CryptoHelper.encodeNetworkString(subtoken.toByteArray())); token.write(CryptoHelper.encodeNetworkString(keyblob)); // // Generate signature // byte[] sigblob = agent.sign(keyblob, token.toByteArray()); token.write(CryptoHelper.encodeNetworkString(sigblob)); String b64token = new String(Base64.encode(token.toByteArray()), "UTF-8"); // // Send request // httpclient = new DefaultHttpClient(); URIBuilder builder = new URIBuilder(ossURL + GuiceServletModule.SERVLET_PATH_GET_SECRET); builder.addParameter("token", b64token); URI uri = builder.build(); String qs = uri.getRawQuery(); HttpPost post = new HttpPost( uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + uri.getPath()); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(new StringEntity(qs)); HttpResponse response = httpclient.execute(post); HttpEntity resEntity = response.getEntity(); String content = EntityUtils.toString(resEntity, "UTF-8"); post.reset(); if (HttpServletResponse.SC_OK != response.getStatusLine().getStatusCode()) { // Only throw an exception if this is the last SSH key we could try if (idx == fingerprints.size()) { throw new OSSException("None of the provided keys (" + idx + ") could be used to retrieve secret. Latest error message was: " + response.getStatusLine().getReasonPhrase()); } else { continue; } } // // Extract encrypted secret and sealed key // byte[] secretandsealedkey = Base64.decode(content); byte[] encryptedsecret = CryptoHelper.decodeNetworkString(secretandsealedkey, 0); byte[] sealedkey = CryptoHelper.decodeNetworkString(secretandsealedkey, 4 + encryptedsecret.length); // // Unseal key // byte[] wrappingkey = CryptoHelper.decryptRSA(rsapriv, sealedkey); // // Unwrap secret // return CryptoHelper.unwrapAES(wrappingkey, encryptedsecret); } } catch (OSSException osse) { throw osse; } catch (Exception e) { throw new OSSException(e); } finally { if (null != httpclient) { httpclient.getConnectionManager().shutdown(); } if (null != agent) { agent.close(); } } return null; }
From source file:com.geoxp.oss.client.OSSClient.java
License:Apache License
public static boolean init(String ossURL, byte[] secret, String sshKeyFingerprint) throws OSSException { SSHAgentClient agent = null;// w ww .j a v a 2s.c o m HttpClient httpclient = null; try { agent = new SSHAgentClient(); List<SSHKey> sshkeys = agent.requestIdentities(); // // If no SSH Key fingerprint was provided, try all SSH keys available in the agent // List<String> fingerprints = new ArrayList<String>(); if (null == sshKeyFingerprint) { for (SSHKey key : sshkeys) { fingerprints.add(key.fingerprint); } } else { fingerprints.add(sshKeyFingerprint.toLowerCase().replaceAll("[^0-9a-f]", "")); } int idx = 0; for (String fingerprint : fingerprints) { idx++; // // Ask the SSH agent for the SSH key blob // byte[] keyblob = null; for (SSHKey key : sshkeys) { if (key.fingerprint.equals(fingerprint)) { keyblob = key.blob; break; } } // // Throw an exception if this condition is encountered as it can only happen if // there was a provided fingerprint which is not in the agent. // if (null == keyblob) { throw new OSSException("SSH Key " + sshKeyFingerprint + " was not found by your SSH agent."); } // // Retrieve OSS RSA key // RSAPublicKey pubkey = getOSSRSA(ossURL); // // Build the initialization token // // <TS> <SECRET> <SSH Signing Key Blob> <SSH Signature Blob> // ByteArrayOutputStream token = new ByteArrayOutputStream(); byte[] tsdata = nowBytes(); token.write(CryptoHelper.encodeNetworkString(tsdata)); token.write(CryptoHelper.encodeNetworkString(secret)); token.write(CryptoHelper.encodeNetworkString(keyblob)); byte[] sigblob = agent.sign(keyblob, token.toByteArray()); token.write(CryptoHelper.encodeNetworkString(sigblob)); // // Encrypt the token with a random AES256 key // byte[] aeskey = new byte[32]; CryptoHelper.getSecureRandom().nextBytes(aeskey); byte[] wrappedtoken = CryptoHelper.wrapAES(aeskey, token.toByteArray()); // // Encrypt the random key with OSS' RSA key // byte[] sealedaeskey = CryptoHelper.encryptRSA(pubkey, aeskey); // // Create the token // token.reset(); token.write(CryptoHelper.encodeNetworkString(wrappedtoken)); token.write(CryptoHelper.encodeNetworkString(sealedaeskey)); // // Base64 encode the encryptedtoken // String b64token = new String(Base64.encode(token.toByteArray()), "UTF-8"); // // Send request to OSS // URIBuilder builder = new URIBuilder(ossURL + GuiceServletModule.SERVLET_PATH_INIT); builder.addParameter("token", b64token); URI uri = builder.build(); String qs = uri.getRawQuery(); HttpPost post = new HttpPost( uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + uri.getPath()); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(new StringEntity(qs)); httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(post); HttpEntity resEntity = response.getEntity(); String content = EntityUtils.toString(resEntity, "UTF-8"); post.reset(); if (HttpServletResponse.SC_ACCEPTED == response.getStatusLine().getStatusCode()) { return false; } else if (HttpServletResponse.SC_OK != response.getStatusLine().getStatusCode()) { // Only throw an exception if this is the last SSH key we could try if (idx == fingerprints.size()) { throw new OSSException("None of the provided keys (" + idx + ") could be used to initialize this Open Secret Server. Latest error message was: " + response.getStatusLine().getReasonPhrase()); } else { continue; } } return true; } } catch (OSSException osse) { throw osse; } catch (Exception e) { throw new OSSException(e); } finally { if (null != httpclient) { httpclient.getConnectionManager().shutdown(); } if (null != agent) { agent.close(); } } return false; }