List of usage examples for org.apache.commons.codec.binary Base64 encodeBase64URLSafeString
public static String encodeBase64URLSafeString(final byte[] binaryData)
From source file:alfio.manager.CheckInManager.java
public static String encrypt(String key, String payload) { try {//from w w w.jav a2 s. c o m Pair<Cipher, SecretKeySpec> cipherAndSecret = getCypher(key); Cipher cipher = cipherAndSecret.getKey(); cipher.init(Cipher.ENCRYPT_MODE, cipherAndSecret.getRight()); byte[] data = cipher.doFinal(payload.getBytes(StandardCharsets.UTF_8)); byte[] iv = cipher.getIV(); return Base64.encodeBase64URLSafeString(iv) + "|" + Base64.encodeBase64URLSafeString(data); } catch (GeneralSecurityException e) { throw new IllegalStateException(e); } }
From source file:com.smartitengineering.cms.spi.impl.events.EventConsumerTest.java
@Test public void testSequenceConsumptionWithInvalidMessage() { mockery.checking(new Expectations() { {/*from w ww. ja v a2s.com*/ } }); EventConsumer consumer = injector.getInstance(EventConsumer.class); consumer.consume(MSG_TYPE, "SEQUENCE\nCREATE\n" + Base64.encodeBase64URLSafeString(StringUtils.getBytesUtf8("random string\nfor test"))); mockery.assertIsSatisfied(); }
From source file:com.thruzero.common.core.security.SimpleCipher.java
/** * @return the given {@code plaintext} as an encrypted string. * @throws SimpleCipherException/*from ww w . j a va 2s. c om*/ */ public String encrypt(final String plaintext) throws SimpleCipherException { String result = null; try { byte[] plaintextBytes = plaintext.getBytes(); byte[] enc = encryptionCipher.doFinal(plaintextBytes); // Encrypt the plaintext result = Base64.encodeBase64URLSafeString(enc); } catch (Exception e) { throw new SimpleCipherException( "Couldn't encrypt the given plaintext because of " + ExceptionUtils.getMessage(e), e); } return result; }
From source file:be.fedict.eid.idp.protocol.openid.AbstractOpenIDProtocolService.java
private String findAttribute(String typeUri, Map<String, Attribute> attributes) { for (Attribute attribute : attributes.values()) { if (attribute.getUri().equals(typeUri)) { switch (attribute.getAttributeType()) { case STRING: if (attribute.getUri().equals(OpenIDAXConstants.AX_GENDER_TYPE)) { String attributeValue = (String) attribute.getValue(); if (attributeValue.equals("1")) { return "M"; } else if (attributeValue.equals("2")) { return "F"; } else { return attributeValue; }/*w ww . j a v a2 s . c o m*/ } else { return (String) attribute.getValue(); } case INTEGER: return attribute.getValue().toString(); case DATE: return new SimpleDateFormat("yyyy/MM/dd") .format(((GregorianCalendar) attribute.getValue()).getTime()); case BINARY: return Base64.encodeBase64URLSafeString((byte[]) attribute.getValue()); } } } return null; }
From source file:it.attocchi.jsf2.PageBase.java
protected String encodeParam(String value) { return Base64.encodeBase64URLSafeString(value.getBytes()); }
From source file:com.demandware.appsec.csrf.StatelessCSRFTokenManager.java
/** * Given a byte array, return an encoded version using a URL-safe Base64. * /*from w w w . jav a2 s . c o m*/ * @param tokenBytes the bytes of a csrf token * @return an encoded String of the tokenBytes */ protected String encodeToken(byte[] tokenBytes) { return Base64.encodeBase64URLSafeString(tokenBytes); }
From source file:com.ibm.jaggr.core.impl.transport.RequestedModuleNamesTest.java
@Test public void testDecodeModuleIds() throws Exception { final String[] idList = new String[0x10005]; idList[1] = "module1"; idList[2] = "module2"; idList[3] = "foo"; idList[4] = "bar"; idList[5] = "plugin"; idList[0x10003] = "bigId"; int ids[] = new int[] { // specifies the following {,,,"module1",,"module2","plugin!foo",,,"bar"} // first segment 3, // start at third slot in module list 1, // one module id to follow // start of module id 1, // "module1" // new segment 5, // fifth slot in module list 2, // two module ids to follow 2, // module2 // second module id in segment specifies "plugin!foo" 0, 5, // "plugin" 3, // "foo" // third segment 10, // slot 10 in modulelist 1, // one module id to follow 4 // "bar" };/*from w ww.java 2 s. co m*/ byte hash[] = new byte[] { 1, 2, 3 }; // test with 16-bit encoding byte[] bytes = new byte[ids.length * 2]; for (int i = 0; i < ids.length; i++) { bytes[i * 2] = (byte) (ids[i] >> 8); bytes[i * 2 + 1] = (byte) (ids[i] & 0xFF); } String encoded = Base64 .encodeBase64URLSafeString(ArrayUtils.addAll(ArrayUtils.addAll(hash, new byte[] { 0 }), bytes)); System.out.println(encoded); String resultArray[] = new String[11]; HttpServletRequest mockRequest = TestUtils.createMockRequest(null); EasyMock.replay(mockRequest); RequestedModuleNames requestedModules = new RequestedModuleNames(mockRequest, Arrays.asList(idList), hash); requestedModules.decodeModuleIds(encoded, resultArray); Assert.assertArrayEquals(new String[] { null, null, null, "module1", null, "module2", "plugin!foo", null, null, null, "bar" }, resultArray); // test again with 32-bit encoding ids = ArrayUtils.addAll(ids, new int[] { 12, 1, 0x10003 }); // slot 12, 1 module, "bigId" bytes = new byte[ids.length * 4]; for (int i = 0; i < ids.length; i++) { bytes[i * 4] = (byte) (ids[i] >> 24); bytes[i * 4 + 1] = (byte) ((ids[i] >> 16) & 0xFF); bytes[i * 4 + 2] = (byte) ((ids[i] >> 8) & 0xFF); bytes[i * 4 + 3] = (byte) (ids[i] & 0xFF); } encoded = Base64 .encodeBase64URLSafeString(ArrayUtils.addAll(ArrayUtils.addAll(hash, new byte[] { 1 }), bytes)); System.out.println(encoded); resultArray = new String[13]; requestedModules.decodeModuleIds(encoded, resultArray); Assert.assertArrayEquals(new String[] { null, null, null, "module1", null, "module2", "plugin!foo", null, null, null, "bar", null, "bigId" }, resultArray); // Make sure exception is thrown if hash is not correct try { encoded = Base64.encodeBase64URLSafeString(ArrayUtils.addAll(new byte[] { 3, 2, 1 }, bytes)); requestedModules.decodeModuleIds(encoded, new String[11]); fail("Expected exception"); } catch (BadRequestException ex) { } }
From source file:com.distrimind.madkit.kernel.MadkitProperties.java
boolean prepareCurrentRandomSeedsForBackup() { boolean change = false; if (approvedRandom != null) { savedRandomSeedForApprovedRandom = Base64.encodeBase64URLSafeString(approvedRandom.generateSeed(55)); change = true;/*from w w w.j av a 2s . c o m*/ } if (approvedRandomForKeys != null) { savedRandomSeedForApprovedRandomForKeys = Base64 .encodeBase64URLSafeString(approvedRandomForKeys.generateSeed(55)); change = true; } return change; }
From source file:com.cloud.servlet.ConsoleProxyServlet.java
private boolean verifyRequest(Map<String, Object[]> requestParameters) { try {/* w w w . j ava 2 s.c o m*/ String apiKey = null; String secretKey = null; String signature = null; String unsignedRequest = null; // - build a request string with sorted params, make sure it's all lowercase // - sign the request, verify the signature is the same List<String> parameterNames = new ArrayList<String>(); for (Object paramNameObj : requestParameters.keySet()) { parameterNames.add((String) paramNameObj); // put the name in a list that we'll sort later } Collections.sort(parameterNames); for (String paramName : parameterNames) { // parameters come as name/value pairs in the form String/String[] String paramValue = ((String[]) requestParameters.get(paramName))[0]; if ("signature".equalsIgnoreCase(paramName)) { signature = paramValue; } else { if ("apikey".equalsIgnoreCase(paramName)) { apiKey = paramValue; } if (unsignedRequest == null) { unsignedRequest = paramName + "=" + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20"); } else { unsignedRequest = unsignedRequest + "&" + paramName + "=" + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20"); } } } // if api/secret key are passed to the parameters if ((signature == null) || (apiKey == null)) { if (s_logger.isDebugEnabled()) { s_logger.debug( "expired session, missing signature, or missing apiKey -- ignoring request...sig: " + signature + ", apiKey: " + apiKey); } return false; // no signature, bad request } Transaction txn = Transaction.open(Transaction.CLOUD_DB); txn.close(); User user = null; // verify there is a user with this api key Pair<User, Account> userAcctPair = _accountMgr.findUserByApiKey(apiKey); if (userAcctPair == null) { s_logger.debug("apiKey does not map to a valid user -- ignoring request, apiKey: " + apiKey); return false; } user = userAcctPair.first(); Account account = userAcctPair.second(); if (!user.getState().equals(Account.State.enabled) || !account.getState().equals(Account.State.enabled)) { s_logger.debug("disabled or locked user accessing the api, userid = " + user.getId() + "; name = " + user.getUsername() + "; state: " + user.getState() + "; accountState: " + account.getState()); return false; } // verify secret key exists secretKey = user.getSecretKey(); if (secretKey == null) { s_logger.debug( "User does not have a secret key associated with the account -- ignoring request, username: " + user.getUsername()); return false; } unsignedRequest = unsignedRequest.toLowerCase(); Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1"); mac.init(keySpec); mac.update(unsignedRequest.getBytes()); byte[] encryptedBytes = mac.doFinal(); String computedSignature = Base64.encodeBase64URLSafeString(encryptedBytes); boolean equalSig = signature.equals(computedSignature); if (!equalSig) { s_logger.debug("User signature: " + signature + " is not equaled to computed signature: " + computedSignature); } if (equalSig) { requestParameters.put("userid", new Object[] { String.valueOf(user.getId()) }); requestParameters.put("account", new Object[] { account.getAccountName() }); requestParameters.put("accountobj", new Object[] { account }); } return equalSig; } catch (Exception ex) { s_logger.error("unable to verifty request signature", ex); } return false; }
From source file:com.github.ambry.commons.BlobIdTest.java
/** * Build a string that resembles a bad blobId. * @param version The version number to be embedded in the blobId. * @param type The {@link BlobIdType} of the blobId. * @param datacenterId The datacenter id to be embedded in the blobId. * @param accountId The account id to be embedded in the blobId. * @param containerId The container id to be embedded in the blobId. * @param partitionId The partition id to be embedded in the blobId. * @param uuidLength The length of the uuid. * @param uuid The UUID to be embedded in the blobId. * @param extraChars Extra characters to put at the end of the ID. * @return a base-64 encoded {@link String} representing the blobId. *//* w ww .j av a2 s .c o m*/ private String buildBadBlobId(short version, BlobIdType type, Byte datacenterId, Short accountId, Short containerId, PartitionId partitionId, int uuidLength, String uuid, String extraChars) { int idLength; ByteBuffer idBuf; switch (version) { case BLOB_ID_V1: idLength = 2 + partitionId.getBytes().length + 4 + uuid.length() + extraChars.length(); idBuf = ByteBuffer.allocate(idLength); idBuf.putShort(version); break; case BLOB_ID_V2: idLength = 2 + 1 + 1 + 2 + 2 + partitionId.getBytes().length + 4 + uuid.length() + extraChars.length(); idBuf = ByteBuffer.allocate(idLength); idBuf.putShort(version); idBuf.put((byte) 0); idBuf.put(datacenterId); idBuf.putShort(accountId); idBuf.putShort(containerId); break; case BLOB_ID_V3: case BLOB_ID_V4: case BLOB_ID_V5: case BLOB_ID_V6: idLength = 2 + 1 + 1 + 2 + 2 + partitionId.getBytes().length + 4 + uuid.length() + extraChars.length(); idBuf = ByteBuffer.allocate(idLength); idBuf.putShort(version); idBuf.put((byte) type.ordinal()); idBuf.put(datacenterId); idBuf.putShort(accountId); idBuf.putShort(containerId); break; default: idLength = 2 + partitionId.getBytes().length + 4 + uuid.length() + extraChars.length(); idBuf = ByteBuffer.allocate(idLength); idBuf.putShort(version); break; } idBuf.put(partitionId.getBytes()); switch (version) { case BLOB_ID_V6: UUID uuidObj = UUID.fromString(uuid); idBuf.putLong(uuidObj.getMostSignificantBits()); idBuf.putLong(uuidObj.getLeastSignificantBits()); break; default: idBuf.putInt(uuidLength); idBuf.put(uuid.getBytes()); } idBuf.put(extraChars.getBytes()); return Base64.encodeBase64URLSafeString(idBuf.array()); }