List of usage examples for org.apache.commons.codec.binary Base64 encodeBase64
public static byte[] encodeBase64(final byte[] binaryData)
From source file:edu.wfu.inotado.helper.EncryptionHelper.java
public String calculateHMAC(String data, String key) throws java.security.SignatureException { String result = ""; try {/*from w w w . j a v a2 s . com*/ if (!StringUtils.isBlank(data) && !StringUtils.isBlank(key)) { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM); // get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes()); // base64-encode the hmac result = new String(Base64.encodeBase64(rawHmac)); } else { log.warn("data or key appears to be empty!"); } } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return result; }
From source file:com.marvelution.jira.plugins.hudson.encryption.StringEncrypter.java
/** * Encrypt a given {@link String}/* w w w . j a v a 2s . c o m*/ * * @param stringToEncrypt the {@link String} to encrypt * @return the encrypted {@link String} */ public String encrypt(String stringToEncrypt) { if (stringToEncrypt == null || stringToEncrypt.length() == 0) { return ""; } try { initiliseCipher(Cipher.ENCRYPT_MODE); return new String(Base64.encodeBase64(cipher.doFinal(stringToEncrypt.getBytes(UNICODE_FORMAT)))); } catch (Exception e) { LOGGER.error("Failed to encrypt provided String. Reason: " + e.getMessage(), e); throw new StringEncryptionException("Failed to encrypt provided String. Reason: " + e.getMessage(), e); } }
From source file:cloudeventbus.codec.Encoder.java
@Override public void encode(ChannelHandlerContext ctx, Frame frame, ByteBuf out) throws Exception { LOGGER.debug("Encoding frame {}", frame); switch (frame.getFrameType()) { case AUTHENTICATE: final AuthenticationRequestFrame authenticationRequestFrame = (AuthenticationRequestFrame) frame; out.writeByte(FrameType.AUTHENTICATE.getOpcode()); out.writeByte(' '); final String challenge = Base64.encodeBase64String(authenticationRequestFrame.getChallenge()); writeString(out, challenge);//w ww .jav a 2s.c om break; case AUTH_RESPONSE: final AuthenticationResponseFrame authenticationResponseFrame = (AuthenticationResponseFrame) frame; out.writeByte(FrameType.AUTH_RESPONSE.getOpcode()); out.writeByte(' '); // Write certificate chain final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final OutputStream base64Out = new Base64OutputStream(outputStream, true, Integer.MAX_VALUE, new byte[0]); CertificateStoreLoader.store(base64Out, authenticationResponseFrame.getCertificates()); out.writeBytes(outputStream.toByteArray()); out.writeByte(' '); // Write salt final byte[] encodedSalt = Base64.encodeBase64(authenticationResponseFrame.getSalt()); out.writeBytes(encodedSalt); out.writeByte(' '); // Write signature final byte[] encodedDigitalSignature = Base64 .encodeBase64(authenticationResponseFrame.getDigitalSignature()); out.writeBytes(encodedDigitalSignature); break; case ERROR: final ErrorFrame errorFrame = (ErrorFrame) frame; out.writeByte(FrameType.ERROR.getOpcode()); out.writeByte(' '); writeString(out, Integer.toString(errorFrame.getCode().getErrorNumber())); if (errorFrame.getMessage() != null) { out.writeByte(' '); writeString(out, errorFrame.getMessage()); } break; case GREETING: final GreetingFrame greetingFrame = (GreetingFrame) frame; out.writeByte(FrameType.GREETING.getOpcode()); out.writeByte(' '); writeString(out, Integer.toString(greetingFrame.getVersion())); out.writeByte(' '); writeString(out, greetingFrame.getAgent()); out.writeByte(' '); writeString(out, Long.toString(greetingFrame.getId())); break; case PING: out.writeByte(FrameType.PING.getOpcode()); break; case PONG: out.writeByte(FrameType.PONG.getOpcode()); break; case PUBLISH: final PublishFrame publishFrame = (PublishFrame) frame; out.writeByte(FrameType.PUBLISH.getOpcode()); out.writeByte(' '); writeString(out, publishFrame.getSubject().toString()); if (publishFrame.getReplySubject() != null) { out.writeByte(' '); writeString(out, publishFrame.getReplySubject().toString()); } out.writeByte(' '); final ByteBuf body = Unpooled.wrappedBuffer(publishFrame.getBody().getBytes(CharsetUtil.UTF_8)); writeString(out, Integer.toString(body.readableBytes())); out.writeBytes(Codec.DELIMITER); out.writeBytes(body); break; case SERVER_READY: out.writeByte(FrameType.SERVER_READY.getOpcode()); break; case SUBSCRIBE: final SubscribeFrame subscribeFrame = (SubscribeFrame) frame; out.writeByte(FrameType.SUBSCRIBE.getOpcode()); out.writeByte(' '); writeString(out, subscribeFrame.getSubject().toString()); break; case UNSUBSCRIBE: final UnsubscribeFrame unsubscribeFrame = (UnsubscribeFrame) frame; out.writeByte(FrameType.UNSUBSCRIBE.getOpcode()); out.writeByte(' '); writeString(out, unsubscribeFrame.getSubject().toString()); break; default: throw new EncodingException("Don't know how to encode message of type " + frame.getClass().getName()); } out.writeBytes(Codec.DELIMITER); }
From source file:com.demandware.vulnapp.challenge.impl.CookieChallenge.java
@SuppressWarnings("unchecked") private Cookie generateCookie() { JSONObject o = new JSONObject(); o.put(ACCESS_KEY, "false"); String value = new String(Base64.encodeBase64(o.toJSONString().getBytes())); Cookie c = new Cookie(COOKIE_NAME, value); c.setMaxAge(MAX_AGE);/*from w w w.ja v a 2s . c om*/ c.setPath("/"); return c; }
From source file:com.xerox.amazonws.ec2.UploadPolicy.java
public String getPolicyString() { StringBuilder json = new StringBuilder("{\n"); json.append("\"expiration\": \""); final String DateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"; SimpleDateFormat format = new SimpleDateFormat(DateFormat, Locale.US); format.setTimeZone(TimeZone.getTimeZone("GMT")); json.append(format.format(new Date(System.currentTimeMillis() + (minutesToExpiration * 60000L)))); json.append("\",\n"); json.append("\"conditions\": [\n"); json.append("{\"acl\": \""); json.append(acl);//from w ww .ja v a 2 s .c om json.append("\"},\n"); json.append("{\"bucket\": \""); json.append(bucket); json.append("\"},\n"); json.append("[\"starts-with\", \"$key\", \""); json.append(prefix); json.append("\"],\n"); json.append("]\n}"); logger.debug("JSON policy string = " + json.toString()); return new String(Base64.encodeBase64(json.toString().getBytes())); }
From source file:com.android.builder.files.FileCacheByPath.java
/** * Computes a unique key identifying the path of the file. * * @param f the path/*w ww . j av a 2 s. c om*/ * @return the unique key */ @NonNull private static String key(@NonNull File f) { String absolutePath = f.getAbsolutePath(); byte[] sha1Sum = Hashing.sha1().hashString(absolutePath, Charsets.UTF_8).asBytes(); return new String(Base64.encodeBase64(sha1Sum), Charsets.US_ASCII).replaceAll("/", "_"); }
From source file:net.jolm.util.UserPasswordHelper.java
/** * Calculates hash of clear text password to be stored in the userPassword * field./*from w w w .j a v a2 s . co m*/ * * @param clearpass * The password in plaintext that should be hashed. * @param alg * The algorithm to caculate the hash. * @param salt * The salt that is to be used together with the schemes {SMD5} * and {SSHA}. Should be between 8 and 16 Bytes. salt should be * null for any other scheme. * @return The base64-encoded hashed pwd with the following format: - * {MD5}base64(MD5-hash) for MD5 hashes - {SHA}base64(SHA-hash) for * SHA hashes - {SMD5}base64(MD5-hash+salt bytes) for SMD5 hashes - * {SSHA}base64(SHA-hash+salt bytes) for SSHA hashes Or null if t is * not one of 2, 3, 4, 5. */ public static byte[] clearPassToUserPassword(String clearpass, HashAlg alg, byte[] salt) { if (alg == null) { throw new IllegalArgumentException("Invalid hash argorithm."); } try { MessageDigest digester = null; StringBuilder resultInText = new StringBuilder(); switch (alg) { case MD5: resultInText.append("{MD5}"); digester = MessageDigest.getInstance("MD5"); break; case SMD5: resultInText.append("{SMD5}"); digester = MessageDigest.getInstance("MD5"); break; case SHA: resultInText.append("{SHA}"); digester = MessageDigest.getInstance("SHA"); break; case SSHA: resultInText.append("{SSHA}"); digester = MessageDigest.getInstance("SHA"); break; default: break; } digester.reset(); digester.update(clearpass.getBytes(DEFAULT_ENCODING)); byte[] hash = null; if (salt != null && (alg == HashAlg.SMD5 || alg == HashAlg.SSHA)) { digester.update(salt); hash = ArrayUtils.addAll(digester.digest(), salt); } else { hash = digester.digest(); } resultInText.append(new String(Base64.encodeBase64(hash), DEFAULT_ENCODING)); return resultInText.toString().getBytes(DEFAULT_ENCODING); } catch (UnsupportedEncodingException uee) { log.warn("Error occurred while hashing password ", uee); return new byte[0]; } catch (java.security.NoSuchAlgorithmException nse) { log.warn("Error occurred while hashing password ", nse); return new byte[0]; } }
From source file:com.twilio.sdk.TwilioUtils.java
public boolean validateRequest(String expectedSignature, String url, Map<String, String> params) { SecretKeySpec signingKey = new SecretKeySpec(this.authToken.getBytes(), "HmacSHA1"); try {/*from w w w . j a va2s. c o m*/ //initialize the hash algortihm Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); //sort the params alphabetically, and append the key and value of each to the url StringBuffer data = new StringBuffer(url); if (params != null) { List<String> sortedKeys = new ArrayList<String>(params.keySet()); Collections.sort(sortedKeys); for (String s : sortedKeys) { data.append(s); String v = ""; if (params.get(s) != null) { v = params.get(s); } data.append(v); } } //compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.toString().getBytes("UTF-8")); //base64-encode the hmac String signature = new String(Base64.encodeBase64(rawHmac)); return signature.equals(expectedSignature); } catch (NoSuchAlgorithmException e) { return false; } catch (InvalidKeyException e) { return false; } catch (UnsupportedEncodingException e) { return false; } }
From source file:com.docdoku.cli.helpers.FileHelper.java
public String downloadFile(File pLocalFile, String pURL) throws IOException, LoginException, NoSuchAlgorithmException { ConsoleProgressMonitorInputStream in = null; OutputStream out = null;//from w w w .j a v a2 s.c o m HttpURLConnection conn = null; try { //Hack for NTLM proxy //perform a head method to negociate the NTLM proxy authentication URL url = new URL(pURL); System.out.println("Downloading file: " + pLocalFile.getName() + " from " + url.getHost()); performHeadHTTPMethod(url); out = new BufferedOutputStream(new FileOutputStream(pLocalFile), BUFFER_CAPACITY); conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setAllowUserInteraction(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestMethod("GET"); byte[] encoded = Base64.encodeBase64((login + ":" + password).getBytes("ISO-8859-1")); conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII")); conn.connect(); manageHTTPCode(conn); MessageDigest md = MessageDigest.getInstance("MD5"); in = new ConsoleProgressMonitorInputStream(conn.getContentLength(), new DigestInputStream(new BufferedInputStream(conn.getInputStream(), BUFFER_CAPACITY), md)); byte[] data = new byte[CHUNK_SIZE]; int length; while ((length = in.read(data)) != -1) { out.write(data, 0, length); } out.flush(); byte[] digest = md.digest(); return Base64.encodeBase64String(digest); } finally { if (out != null) out.close(); if (in != null) in.close(); if (conn != null) conn.disconnect(); } }
From source file:com.epam.wilma.extras.shortcircuit.ShortCircuitInterceptorCore.java
/** * Method that generates the general hash code for a request in Short Circuit. * * @param wilmaHttpRequest is the request, that is the base of the hash code * @return with the generated hash code//from www . j av a 2s . c om */ String generateKeyForMap(final WilmaHttpRequest wilmaHttpRequest) { String hashString = wilmaHttpRequest.getRequestLine() + " - " + wilmaHttpRequest.getBody().hashCode(); //ensure that it is ok for a header //CHECKSTYLE OFF - we must use "new String" here hashString = new String(Base64.encodeBase64(hashString.getBytes())); //CHECKSTYLE ON return hashString; }