List of usage examples for org.bouncycastle.util.encoders Base64 encode
public static byte[] encode(byte[] data)
From source file:edu.amrita.selabs.cumulus.lib.test.CryptoTest.java
License:Open Source License
@Test public void testRSAEncoded() throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(2048);//from ww w .j a v a 2 s. c o m KeyPair kp = kpg.genKeyPair(); Key publicKey = kp.getPublic(); Key privateKey = kp.getPrivate(); KeyFactory fact = KeyFactory.getInstance("RSA"); X509EncodedKeySpec pub = fact.getKeySpec(publicKey, X509EncodedKeySpec.class); PKCS8EncodedKeySpec priv = fact.getKeySpec(privateKey, PKCS8EncodedKeySpec.class); String pubString = new String(Base64.encode(pub.getEncoded())); String privString = new String(Base64.encode(priv.getEncoded())); System.out.println("public-key:" + pubString); System.out.println("private-key:" + privString); System.out.println("public key length: " + pubString.length()); X509EncodedKeySpec pubNew = new X509EncodedKeySpec(Base64.decode(pubString)); PKCS8EncodedKeySpec privNew = new PKCS8EncodedKeySpec(Base64.decode(privString)); RSAPublicKey publicKeyNew = (RSAPublicKey) fact.generatePublic(pubNew); RSAPrivateKey privateKeyNew = (RSAPrivateKey) fact.generatePrivate(privNew); Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); String text = "Aum Amriteswaryai Namah"; byte[] cipherData = cipher.doFinal(text.getBytes()); System.out.println("encData:" + StringUtil.toHexString(cipherData)); cipher.init(Cipher.DECRYPT_MODE, publicKeyNew); byte[] decData = cipher.doFinal(cipherData); System.out.println("decData:" + StringUtil.toHexString(decData)); String decText = new String(decData, decData.length - text.length(), text.length()); System.out.println("text bytes:" + StringUtil.toHexString(text.getBytes())); System.out.println("decText:" + decText); assertTrue(decText.equals(text)); }
From source file:edu.ucsb.eucalyptus.cloud.cluster.ConsoleOutputCallback.java
License:Open Source License
public void process(final Client cluster, final GetConsoleOutputType msg) throws Exception { GetConsoleOutputResponseType reply = (GetConsoleOutputResponseType) cluster.send(msg); VmInstance vm = VmInstances.getInstance().lookup(msg.getInstanceId()); String output = null;//from w w w . jav a 2s. c o m try { output = new String(Base64.decode(reply.getOutput().getBytes())); if (!"EMPTY".equals(output)) vm.getConsoleOutput().append(output); } catch (ArrayIndexOutOfBoundsException e1) { } reply.setInstanceId(msg.getInstanceId()); reply.setTimestamp(new Date()); reply.setOutput(new String(Base64.encode(vm.getConsoleOutput().toString().getBytes()))); Messaging.dispatch("vm://ReplyQueue", reply); }
From source file:edu.ucsb.eucalyptus.cloud.ws.HttpTransfer.java
License:Open Source License
public HttpMethodBase constructHttpMethod(String verb, String addr, String eucaOperation, String eucaHeader) { String date = new Date().toString(); String httpVerb = verb;// w w w .j a va 2s . c o m String addrPath; try { java.net.URI addrUri = new URL(addr).toURI(); addrPath = addrUri.getPath().toString(); String query = addrUri.getQuery(); if (query != null) { addrPath += "?" + query; } } catch (Exception ex) { LOG.error(ex, ex); return null; } String data = httpVerb + "\n" + date + "\n" + addrPath + "\n"; HttpMethodBase method = null; if (httpVerb.equals("PUT")) { method = new PutMethodWithProgress(addr); } else if (httpVerb.equals("DELETE")) { method = new DeleteMethod(addr); } else { method = new GetMethod(addr); } method.setRequestHeader("Authorization", "Euca"); method.setRequestHeader("Date", date); //method.setRequestHeader("Expect", "100-continue"); method.setRequestHeader(StorageProperties.EUCALYPTUS_OPERATION, eucaOperation); if (eucaHeader != null) { method.setRequestHeader(StorageProperties.EUCALYPTUS_HEADER, eucaHeader); } try { PrivateKey ccPrivateKey = SystemCredentials.lookup(Storage.class).getPrivateKey(); Signature sign = Signature.getInstance("SHA1withRSA"); sign.initSign(ccPrivateKey); sign.update(data.getBytes()); byte[] sig = sign.sign(); method.setRequestHeader("EucaSignature", new String(Base64.encode(sig))); } catch (Exception ex) { LOG.error(ex, ex); } return method; }
From source file:edu.ucsb.eucalyptus.cloud.ws.KeyPairBroker.java
License:Open Source License
public CreateKeyPairResponseType CreateKeyPair(CreateKeyPairType request) throws EucalyptusCloudException { if (request.getKeyName() == null) throw new EucalyptusCloudException("KeyPair generation error. Key name must be specified."); String userId = request.getUserId(); String newKeyName = request.getKeyName(); /** generate the key information **/ String privKey;/*w w w.j ava 2 s . c om*/ String fingerPrint; EntityWrapper<UserInfo> db = new EntityWrapper<UserInfo>(); UserInfo user = null; try { user = db.getUnique(new UserInfo(request.getUserId())); if (user.getKeyPairs().contains(new SSHKeyPair(newKeyName))) throw new EucalyptusCloudException( "KeyPair generation error. Key pair: " + newKeyName + " already exists."); //:: get the new key pair ::// KeyTool keyTool = new KeyTool(); KeyPair newKeys = keyTool.getKeyPair(); //:: convert public key into an OpenSSH encoded public key ::// RSAPublicKey publicKey = (RSAPublicKey) newKeys.getPublic(); byte[] keyType = "ssh-rsa".getBytes(); byte[] expBlob = publicKey.getPublicExponent().toByteArray(); byte[] modBlob = publicKey.getModulus().toByteArray(); byte[] authKeyBlob = new byte[3 * 4 + keyType.length + expBlob.length + modBlob.length]; byte[] lenArray = null; lenArray = BigInteger.valueOf(keyType.length).toByteArray(); System.arraycopy(lenArray, 0, authKeyBlob, 4 - lenArray.length, lenArray.length); System.arraycopy(keyType, 0, authKeyBlob, 4, keyType.length); lenArray = BigInteger.valueOf(expBlob.length).toByteArray(); System.arraycopy(lenArray, 0, authKeyBlob, 4 + keyType.length + 4 - lenArray.length, lenArray.length); System.arraycopy(expBlob, 0, authKeyBlob, 4 + (4 + keyType.length), expBlob.length); lenArray = BigInteger.valueOf(modBlob.length).toByteArray(); System.arraycopy(lenArray, 0, authKeyBlob, 4 + expBlob.length + 4 + keyType.length + 4 - lenArray.length, lenArray.length); System.arraycopy(modBlob, 0, authKeyBlob, 4 + (4 + expBlob.length + (4 + keyType.length)), modBlob.length); String authKeyString = String.format("%s %s %s@eucalyptus", new String(keyType), new String(Base64.encode(authKeyBlob)), request.getUserId()); //:: convert the private key into a PEM encoded string ::// ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PEMWriter privOut = new PEMWriter(new OutputStreamWriter(byteOut)); try { privOut.writeObject(newKeys.getPrivate()); privOut.close(); } catch (IOException e) { LOG.error(e); throw new EucalyptusCloudException(e); } privKey = byteOut.toString(); //:: get the fingerprint for the private key ::// fingerPrint = Hashes.getFingerPrint(newKeys.getPrivate()); LOG.info("Generated new key pair for entities: " + userId + " keypair name=" + newKeyName); user.getKeyPairs().add(new SSHKeyPair(newKeyName, fingerPrint, authKeyString)); db.commit(); } catch (EucalyptusCloudException e) { LOG.error(e); LOG.debug(e, e); db.rollback(); throw e; } CreateKeyPairResponseType reply = (CreateKeyPairResponseType) request.getReply(); reply.setKeyFingerprint(fingerPrint); reply.setKeyMaterial(privKey); reply.setKeyName(newKeyName); return reply; }
From source file:edu.ucsb.eucalyptus.cloud.ws.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); vmAllocInfo.setReservationIndex(Counters.getIdBlock(request.getMaxCount())); String userData = vmAllocInfo.getRequest().getUserData(); if (userData != null) { try {/*from www . j a v a 2s . co m*/ userData = new String(Base64.decode(vmAllocInfo.getRequest().getUserData())); } catch (Exception e) { userData = ""; } } else { userData = ""; } vmAllocInfo.setUserData(userData); vmAllocInfo.getRequest().setUserData(new String(Base64.encode(userData.getBytes()))); return vmAllocInfo; }
From source file:edu.ucsb.eucalyptus.transport.query.WalrusQueryDispatcher.java
License:Open Source License
public String getOperation(HttpRequest httpRequest, MessageContext messageContext) throws EucalyptusCloudException { //Figure out if it is an operation on the service, a bucket or an object Map operationParams = new HashMap(); String[] target = null;//w ww . j av a2 s . co m String path = httpRequest.getOperationPath(); boolean walrusInternalOperation = false; if (path.length() > 0) { target = getTarget(path); } String verb = httpRequest.getHttpMethod(); Map<String, String> headers = httpRequest.getHeaders(); CaseInsensitiveMap caseInsensitiveHeaders = new CaseInsensitiveMap(headers); String operationKey = ""; Map<String, String> params = httpRequest.getParameters(); String operationName = null; long contentLength = 0; String contentLengthString = (String) messageContext.getProperty(HTTP.CONTENT_LEN); if (contentLengthString != null) { contentLength = Long.parseLong(contentLengthString); } if (caseInsensitiveHeaders.containsKey(StorageProperties.EUCALYPTUS_OPERATION)) { String value = caseInsensitiveHeaders.get(StorageProperties.EUCALYPTUS_OPERATION); for (WalrusProperties.WalrusInternalOperations operation : WalrusProperties.WalrusInternalOperations .values()) { if (value.toLowerCase().equals(operation.toString().toLowerCase())) { operationName = operation.toString(); walrusInternalOperation = true; break; } } if (!walrusInternalOperation) { for (WalrusProperties.StorageOperations operation : WalrusProperties.StorageOperations.values()) { if (value.toLowerCase().equals(operation.toString().toLowerCase())) { operationName = operation.toString(); walrusInternalOperation = true; break; } } } } if (target == null) { //target = service operationKey = SERVICE + verb; } else if (target.length < 2) { //target = bucket if (!target[0].equals("")) { operationKey = BUCKET + verb; operationParams.put("Bucket", target[0]); if (verb.equals(HTTPVerb.POST.toString())) { InputStream in = (InputStream) messageContext.getProperty("TRANSPORT_IN"); messageContext.setProperty(WalrusProperties.STREAMING_HTTP_PUT, Boolean.TRUE); String contentType = caseInsensitiveHeaders.get(HTTP.CONTENT_TYPE); int postContentLength = Integer.parseInt(caseInsensitiveHeaders.get(HTTP.CONTENT_LEN)); POSTRequestContext postRequestContext = new POSTRequestContext(in, contentType, postContentLength); FileUpload fileUpload = new FileUpload(new WalrusFileItemFactory()); InputStream formDataIn = null; String objectKey = null; String file = ""; String key; Map<String, String> formFields = new HashMap<String, String>(); try { List<FileItem> parts = fileUpload.parseRequest(postRequestContext); for (FileItem part : parts) { if (part.isFormField()) { String fieldName = part.getFieldName().toString().toLowerCase(); InputStream formFieldIn = part.getInputStream(); int bytesRead; String fieldValue = ""; byte[] bytes = new byte[512]; while ((bytesRead = formFieldIn.read(bytes)) > 0) { fieldValue += new String(bytes, 0, bytesRead); } formFields.put(fieldName, fieldValue); } else { formDataIn = part.getInputStream(); if (part.getName() != null) file = part.getName(); } } } catch (Exception ex) { LOG.warn(ex, ex); throw new EucalyptusCloudException("could not process form request"); } String authenticationHeader = ""; formFields.put(WalrusProperties.FormField.bucket.toString(), target[0]); if (formFields.containsKey(WalrusProperties.FormField.key.toString())) { objectKey = formFields.get(WalrusProperties.FormField.key.toString()); objectKey = objectKey.replaceAll("\\$\\{filename\\}", file); } if (formFields.containsKey(WalrusProperties.FormField.acl.toString())) { String acl = formFields.get(WalrusProperties.FormField.acl.toString()); headers.put(WalrusProperties.AMZ_ACL, acl); } if (formFields.containsKey(WalrusProperties.FormField.success_action_redirect.toString())) { String successActionRedirect = formFields .get(WalrusProperties.FormField.success_action_redirect.toString()); operationParams.put("SuccessActionRedirect", successActionRedirect); } if (formFields.containsKey(WalrusProperties.FormField.success_action_status.toString())) { Integer successActionStatus = Integer.parseInt( formFields.get(WalrusProperties.FormField.success_action_status.toString())); if (successActionStatus == 200 || successActionStatus == 201) operationParams.put("SuccessActionStatus", successActionStatus); else operationParams.put("SuccessActionStatus", 204); } else { operationParams.put("SuccessActionStatus", 204); } if (formFields.containsKey(WalrusProperties.FormField.policy.toString())) { String policy = new String( Base64.decode(formFields.remove(WalrusProperties.FormField.policy.toString()))); String policyData; try { policyData = new String(Base64.encode(policy.getBytes())); } catch (Exception ex) { LOG.warn(ex, ex); throw new EucalyptusCloudException("error reading policy data."); } //parse policy try { JSONObject policyObject = new JSONObject(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."); //TODO: currently this will be reported as an invalid operation //Fix this to report a security exception throw new EucalyptusCloudException("Policy has expired."); } } List<String> policyItemNames = new ArrayList<String>(); JSONArray conditions = (JSONArray) policyObject .get(WalrusProperties.PolicyHeaders.conditions.toString()); for (int i = 0; i < conditions.length(); ++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 EucalyptusCloudException("Policy verification failed."); } } else if (policyItem instanceof JSONArray) { JSONArray jsonArray = (JSONArray) policyItem; if (!partialMatch(jsonArray, formFields, policyItemNames)) { LOG.warn("Policy verification failed. "); throw new EucalyptusCloudException("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().toLowerCase())) { fieldOkay = true; break; } } if (fieldOkay) continue; if (policyItemNames.contains(formKey)) continue; LOG.warn("All fields except those marked with x-ignore- should be in policy."); throw new EucalyptusCloudException( "All fields except those marked with x-ignore- should be in policy."); } } catch (Exception ex) { //rethrow if (ex instanceof EucalyptusCloudException) throw (EucalyptusCloudException) ex; LOG.warn(ex); } //all form uploads without a policy are anonymous if (formFields .containsKey(WalrusProperties.FormField.AWSAccessKeyId.toString().toLowerCase())) { String accessKeyId = formFields .remove(WalrusProperties.FormField.AWSAccessKeyId.toString().toLowerCase()); authenticationHeader += "AWS" + " " + accessKeyId + ":"; } if (formFields.containsKey(WalrusProperties.FormField.signature.toString())) { String signature = formFields.remove(WalrusProperties.FormField.signature.toString()); authenticationHeader += signature; headers.put(HMACQuerySecurityHandler.SecurityParameter.Authorization.toString(), authenticationHeader); } headers.put(WalrusProperties.FormField.FormUploadPolicyData.toString(), policyData); } operationParams.put("Key", objectKey); key = target[0] + "." + objectKey; String randomKey = key + "." + Hashes.getRandom(10); LinkedBlockingQueue<WalrusDataMessage> putQueue = getWriteMessenger() .interruptAllAndGetQueue(key, randomKey); Writer writer = new Writer(formDataIn, postContentLength, putQueue); writer.start(); operationParams.put("ContentLength", (new Long(postContentLength).toString())); operationParams.put(WalrusProperties.Headers.RandomKey.toString(), randomKey); } } else { operationKey = SERVICE + verb; } } else { //target = object operationKey = OBJECT + verb; String objectKey = ""; String splitOn = ""; for (int i = 1; i < target.length; ++i) { objectKey += splitOn + target[i]; splitOn = "/"; } operationParams.put("Bucket", target[0]); operationParams.put("Key", objectKey); if (!params.containsKey(OperationParameter.acl.toString())) { if (verb.equals(HTTPVerb.PUT.toString())) { if (caseInsensitiveHeaders.containsKey(WalrusProperties.COPY_SOURCE.toString())) { String copySource = caseInsensitiveHeaders.get(WalrusProperties.COPY_SOURCE.toString()); String[] sourceTarget = getTarget(copySource); String sourceObjectKey = ""; String sourceSplitOn = ""; if (sourceTarget.length > 1) { for (int i = 1; i < sourceTarget.length; ++i) { sourceObjectKey += sourceSplitOn + sourceTarget[i]; sourceSplitOn = "/"; } operationParams.put("SourceBucket", sourceTarget[0]); operationParams.put("SourceObject", sourceObjectKey); operationParams.put("DestinationBucket", operationParams.remove("Bucket")); operationParams.put("DestinationObject", operationParams.remove("Key")); String metaDataDirective = caseInsensitiveHeaders .get(WalrusProperties.METADATA_DIRECTIVE.toString()); if (metaDataDirective != null) { operationParams.put("MetadataDirective", metaDataDirective); } AccessControlListType accessControlList; if (contentLength > 0) { InputStream in = (InputStream) messageContext.getProperty("TRANSPORT_IN"); accessControlList = getAccessControlList(in); } else { accessControlList = new AccessControlListType(); } operationParams.put("AccessControlList", accessControlList); operationKey += WalrusProperties.COPY_SOURCE.toString(); Iterator<String> iterator = caseInsensitiveHeaders.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); for (WalrusProperties.CopyHeaders header : WalrusProperties.CopyHeaders.values()) { if (key.replaceAll("-", "").equals(header.toString().toLowerCase())) { String value = caseInsensitiveHeaders.get(key); parseExtendedHeaders(operationParams, header.toString(), value); } } } } else { throw new EucalyptusCloudException("Malformed COPY request"); } } else { messageContext.setProperty(WalrusProperties.STREAMING_HTTP_PUT, Boolean.TRUE); InputStream in = (InputStream) messageContext.getProperty("TRANSPORT_IN"); InputStream inStream = in; if ((!walrusInternalOperation) || (!WalrusProperties.StorageOperations.StoreSnapshot .toString().equals(operationName))) { inStream = new BufferedInputStream(in); } else { try { inStream = new GZIPInputStream(in); } catch (Exception ex) { LOG.warn(ex, ex); throw new EucalyptusCloudException("cannot process input"); } } String key = target[0] + "." + objectKey; String randomKey = key + "." + Hashes.getRandom(10); LinkedBlockingQueue<WalrusDataMessage> putQueue = getWriteMessenger() .interruptAllAndGetQueue(key, randomKey); Writer writer = new Writer(inStream, contentLength, putQueue); writer.start(); operationParams.put("ContentLength", (new Long(contentLength).toString())); operationParams.put(WalrusProperties.Headers.RandomKey.toString(), randomKey); } } else if (verb.equals(HTTPVerb.GET.toString())) { messageContext.setProperty(WalrusProperties.STREAMING_HTTP_GET, Boolean.TRUE); if (!walrusInternalOperation) { operationParams.put("GetData", Boolean.TRUE); operationParams.put("InlineData", Boolean.FALSE); operationParams.put("GetMetaData", Boolean.TRUE); Iterator<String> iterator = caseInsensitiveHeaders.keySet().iterator(); boolean isExtendedGet = false; while (iterator.hasNext()) { String key = iterator.next(); for (WalrusProperties.ExtendedGetHeaders header : WalrusProperties.ExtendedGetHeaders .values()) { if (key.replaceAll("-", "").equals(header.toString().toLowerCase())) { String value = caseInsensitiveHeaders.get(key); isExtendedGet = true; parseExtendedHeaders(operationParams, header.toString(), value); } } } if (isExtendedGet) { operationKey += "extended"; //only supported through SOAP operationParams.put("ReturnCompleteObjectOnConditionFailure", Boolean.FALSE); } } else { for (WalrusProperties.InfoOperations operation : WalrusProperties.InfoOperations.values()) { if (operation.toString().equals(operationName)) { messageContext.removeProperty(WalrusProperties.STREAMING_HTTP_GET); break; } } } if (params.containsKey(WalrusProperties.GetOptionalParameters.IsCompressed.toString())) { Boolean isCompressed = Boolean.parseBoolean( params.remove(WalrusProperties.GetOptionalParameters.IsCompressed.toString())); operationParams.put("IsCompressed", isCompressed); } } else if (verb.equals(HTTPVerb.HEAD.toString())) { messageContext.setProperty(WalrusProperties.STREAMING_HTTP_GET, Boolean.FALSE); if (!walrusInternalOperation) { operationParams.put("GetData", Boolean.FALSE); operationParams.put("InlineData", Boolean.FALSE); operationParams.put("GetMetaData", Boolean.TRUE); } } } } if (verb.equals(HTTPVerb.PUT.toString()) && params.containsKey(OperationParameter.acl.toString())) { //read ACL InputStream in = (InputStream) messageContext.getProperty("TRANSPORT_IN"); operationParams.put("AccessControlPolicy", getAccessControlPolicy(in)); } ArrayList paramsToRemove = new ArrayList(); boolean addMore = true; Iterator iterator = params.keySet().iterator(); while (iterator.hasNext()) { Object key = iterator.next(); String keyString = key.toString().toLowerCase(); boolean dontIncludeParam = false; for (HMACQuerySecurityHandler.SecurityParameter securityParam : HMACQuerySecurityHandler.SecurityParameter .values()) { if (keyString.equals(securityParam.toString().toLowerCase())) { dontIncludeParam = true; break; } } if (dontIncludeParam) continue; String value = params.get(key); if (value != null) { String[] keyStringParts = keyString.split("-"); if (keyStringParts.length > 1) { keyString = ""; for (int i = 0; i < keyStringParts.length; ++i) { keyString += toUpperFirst(keyStringParts[i]); } } else { keyString = toUpperFirst(keyString); } operationParams.put(keyString, value); } if (addMore) { //just add the first one to the key operationKey += keyString.toLowerCase(); addMore = false; } paramsToRemove.add(key); } for (Object key : paramsToRemove) { params.remove(key); } if (!walrusInternalOperation) { operationName = operationMap.get(operationKey); } httpRequest.setBindingArguments(operationParams); messageContext.setProperty(WalrusProperties.WALRUS_OPERATION, operationName); return operationName; }
From source file:es.unican.meteo.esgf.myproxyclient.MyProxyLogon.java
License:Open Source License
private static void printB64(byte[] paramArrayOfByte, PrintStream paramPrintStream) { byte[] arrayOfByte = Base64.encode(paramArrayOfByte); for (int i = 0; i < arrayOfByte.length; i += 64) { if (arrayOfByte.length - i > 64) { paramPrintStream.write(arrayOfByte, i, 64); } else {/*from ww w . j av a 2s . c o m*/ paramPrintStream.write(arrayOfByte, i, arrayOfByte.length - i); } paramPrintStream.println(); } }
From source file:eu.eidas.auth.commons.EIDASUtil.java
License:Open Source License
/** * {@link Base64} encodes the input samlToken parameter. * * @param samlToken the SAML Token to be encoded. * @return The Base64 String representing the samlToken. * @see Base64#encode//from w ww . j a v a 2s . com */ public static String encodeSAMLToken(final byte[] samlToken) { try { if (samlToken.length == 0) { return ""; } return new String(Base64.encode(samlToken), "UTF8"); } catch (UnsupportedEncodingException e) { LOG.info(EIDASErrors.INTERNAL_ERROR.errorMessage(), e); return null; } }
From source file:eu.eidas.node.auth.connector.AUCONNECTOR.java
License:Open Source License
/** * Encodes, {@link org.bouncycastle.util.encoders.Base64}, a SAML Token. * * @param samlToken The Saml Token to encode. * @return The encoded SAML Token.//ww w. j av a 2s . c o m */ public byte[] sendRedirect(byte[] samlToken) { LOG.trace("Setting attribute SAML_TOKEN_PARAM"); return Base64.encode(samlToken); }
From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java
License:Open Source License
private DOMXMLSignature createEnveloping(SignatureParameters params, DOMSignContext signContext, org.w3c.dom.Document doc, String signatureId, String signatureValueId, Document inside) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, JAXBException, MarshalException, XMLSignatureException, ParserConfigurationException, IOException { XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI()); DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null); List<XMLObject> objects = new ArrayList<XMLObject>(); List<Reference> references = new ArrayList<Reference>(); byte[] b64data = Base64.encode(IOUtils.toByteArray(inside.openStream())); List<Transform> transforms = new ArrayList<Transform>(); Map<String, String> xpathNamespaceMap = new HashMap<String, String>(); xpathNamespaceMap.put("ds", "http://www.w3.org/2000/09/xmldsig#"); Transform exclusiveTransform = fac.newTransform(CanonicalizationMethod.BASE64, (TransformParameterSpec) null); transforms.add(exclusiveTransform);//from w ww . j av a 2s . c o m /* The first reference concern the whole document */ Reference reference = fac.newReference("#signed-data-" + computeDeterministicId(params), digestMethod, transforms, null, "signed-data-ref"); references.add(reference); String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params); QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params, xadesSignedPropertiesId, reference, MimeType.PLAIN); qualifyingProperties.setTarget("#" + signatureId); Node marshallNode = doc.createElement("marshall-node"); JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.marshal(xades13ObjectFactory.createQualifyingProperties(qualifyingProperties), marshallNode); Element qualifier = (Element) marshallNode.getFirstChild(); // add XAdES ds:Object List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>(); xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild())); XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null); objects.add(xadesObject); List<Transform> xadesTranforms = new ArrayList<Transform>(); Transform exclusiveTransform2 = fac.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null); xadesTranforms.add(exclusiveTransform2); Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod, xadesTranforms, XADES_TYPE, null); references.add(xadesreference); /* Signed Info */ SignatureMethod sm = fac.newSignatureMethod( params.getSignatureAlgorithm().getXMLSignatureAlgorithm(params.getDigestAlgorithm()), null); CanonicalizationMethod canonicalizationMethod = fac .newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null); SignedInfo signedInfo = fac.newSignedInfo(canonicalizationMethod, sm, references); /* Creation of signature */ KeyInfoFactory keyFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI()); List<Object> infos = new ArrayList<Object>(); List<X509Certificate> certs = new ArrayList<X509Certificate>(); certs.add(params.getSigningCertificate()); if (params.getCertificateChain() != null) { for (X509Certificate c : params.getCertificateChain()) { if (!c.getSubjectX500Principal().equals(params.getSigningCertificate().getSubjectX500Principal())) { certs.add(c); } } } infos.add(keyFactory.newX509Data(certs)); KeyInfo keyInfo = keyFactory.newKeyInfo(infos); DOMXMLSignature signature = (DOMXMLSignature) fac.newXMLSignature(signedInfo, keyInfo, objects, signatureId, signatureValueId); /* Marshall the signature to permit the digest. Need to be done before digesting the references. */ doc.removeChild(doc.getDocumentElement()); signature.marshal(doc, "ds", signContext); Element dsObject = doc.createElementNS(XMLSignature.XMLNS, "Object"); dsObject.setAttribute("Id", "signed-data-" + computeDeterministicId(params)); dsObject.setTextContent(new String(b64data)); doc.getDocumentElement().appendChild(dsObject); signContext.setIdAttributeNS((Element) qualifier.getFirstChild(), null, "Id"); signContext.setIdAttributeNS(dsObject, null, "Id"); digestReferences(signContext, references); return signature; }