Example usage for org.apache.commons.codec.binary Base64 encodeBase64URLSafeString

List of usage examples for org.apache.commons.codec.binary Base64 encodeBase64URLSafeString

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Base64 encodeBase64URLSafeString.

Prototype

public static String encodeBase64URLSafeString(final byte[] binaryData) 

Source Link

Document

Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output.

Usage

From source file:net.unicon.cas.chalkwire.servlet.CasChalkWireHttpServlet.java

private static String encodeBase64(final byte[] signBytes) {
    return Base64.encodeBase64URLSafeString(signBytes);
}

From source file:net.ymate.framework.core.util.WebUtils.java

/**
 * (IP?)//from  ww  w  .  j  a v a  2s.  co  m
 *
 * @param request HttpServletRequest
 * @param dataStr 
 * @return ?
 * @throws Exception ?
 */
public static String encryptStr(HttpServletRequest request, String dataStr) throws Exception {
    return Base64.encodeBase64URLSafeString(CodecUtils.DES.encrypt(dataStr.getBytes(),
            DigestUtils.md5(request.getRemoteAddr() + request.getHeader("User-Agent"))));
}

From source file:net.ymate.framework.core.util.WebUtils.java

public static String encryptStr(HttpServletRequest request, byte[] bytes) throws Exception {
    return Base64.encodeBase64URLSafeString(CodecUtils.DES.encrypt(bytes,
            DigestUtils.md5(request.getRemoteAddr() + request.getHeader("User-Agent"))));
}

From source file:net.ymate.framework.core.util.WebUtils.java

/**
 * /*  w  w  w. ja  v  a2  s.co m*/
 *
 * @param dataStr 
 * @param key     
 * @return ?
 * @throws Exception ?
 */
public static String encryptStr(String dataStr, String key) throws Exception {
    return Base64.encodeBase64URLSafeString(CodecUtils.DES.encrypt(dataStr.getBytes(), DigestUtils.md5(key)));
}

From source file:net.ymate.platform.module.wechat.support.MessageHelper.java

static String encrypt(String appId, byte[] aesKey, String randomStr, String messageStr) throws AesException {
    ByteGroup byteCollector = new ByteGroup();
    byte[] randomStrBytes = randomStr.getBytes(__CHARSET);
    byte[] textBytes = messageStr.getBytes(__CHARSET);
    byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length);
    byte[] appidBytes = appId.getBytes(__CHARSET);
    // randomStr + networkBytesOrder + text + appid
    byteCollector.addBytes(randomStrBytes);
    byteCollector.addBytes(networkBytesOrder);
    byteCollector.addBytes(textBytes);/*  w  w w.  j  a va2s .  c  o  m*/
    byteCollector.addBytes(appidBytes);
    // ... + pad: ??
    byte[] padBytes = PKCS7Encoder.encode(byteCollector.size());
    byteCollector.addBytes(padBytes);
    // ?, 
    byte[] unencrypted = byteCollector.toBytes();

    try {
        // ?AESCBC?
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
        IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
        // 
        byte[] encrypted = cipher.doFinal(unencrypted);
        // BASE64??
        String base64Encrypted = Base64.encodeBase64URLSafeString(encrypted);
        //
        return base64Encrypted;
    } catch (Exception e) {
        throw new AesException(AesException.EncryptAESError, RuntimeUtils.unwrapThrow(e));
    }
}

From source file:ninja.utils.CookieEncryption.java

/**
 * Encrypts data with secret key./*from  ww  w.  j  a va 2s  . c o  m*/
 *
 * @param data text to encrypt
 * @return encrypted text in base64 format
 */
public String encrypt(String data) {

    Objects.requireNonNull(data, "Data to be encrypted");

    if (!encryptionEnabled) {
        return data;
    }

    try {
        // encrypt data
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec.get());
        byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));

        // convert encrypted bytes to string in base64
        return Base64.encodeBase64URLSafeString(encrypted);

    } catch (InvalidKeyException ex) {
        logger.error(getHelperLogMessage(), ex);
        throw new RuntimeException(ex);
    } catch (GeneralSecurityException ex) {
        logger.error("Failed to encrypt data.", ex);
        throw new RuntimeException(ex);
    }
}

From source file:org.alfresco.rad.test.AlfrescoTestRunner.java

public static String serializableToString(Serializable serializable) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(serializable);/* w ww.j  a v  a  2 s . c o  m*/
    oos.close();

    String string = Base64.encodeBase64URLSafeString(baos.toByteArray());

    return string;
}

From source file:org.alfresco.repo.quickshare.QuickShareServiceImpl.java

@Override
public QuickShareDTO shareContent(final NodeRef nodeRef) {
    checkEnabled();/*from  www  .j  a v a  2  s.c om*/

    //Check the node is the correct type
    final QName typeQName = nodeService.getType(nodeRef);
    if (isSharable(typeQName) == false) {
        throw new InvalidNodeRefException(nodeRef);
    }

    final String sharedId;

    // Only add the quick share aspect if it isn't already present.
    // If it is retura dto built from the existing properties.
    if (!nodeService.getAspects(nodeRef).contains(QuickShareModel.ASPECT_QSHARE)) {
        UUID uuid = UUIDGenerator.getInstance().generateRandomBasedUUID();
        sharedId = Base64.encodeBase64URLSafeString(uuid.toByteArray()); // => 22 chars (eg. q3bEKPeDQvmJYgt4hJxOjw)

        final Map<QName, Serializable> props = new HashMap<QName, Serializable>(2);
        props.put(QuickShareModel.PROP_QSHARE_SHAREDID, sharedId);
        props.put(QuickShareModel.PROP_QSHARE_SHAREDBY, AuthenticationUtil.getRunAsUser());

        // Disable audit to preserve modifier and modified date
        // see MNT-11960
        behaviourFilter.disableBehaviour(nodeRef, ContentModel.ASPECT_AUDITABLE);
        try {
            // consumer/contributor should be able to add "shared" aspect (MNT-10366)
            AuthenticationUtil.runAsSystem(new RunAsWork<Void>() {
                public Void doWork() {
                    nodeService.addAspect(nodeRef, QuickShareModel.ASPECT_QSHARE, props);
                    return null;
                }
            });
        } finally {
            behaviourFilter.enableBehaviour(nodeRef, ContentModel.ASPECT_AUDITABLE);
        }

        final NodeRef tenantNodeRef = tenantService.getName(nodeRef);

        TenantUtil.runAsDefaultTenant(new TenantRunAsWork<Void>() {
            public Void doWork() throws Exception {
                attributeService.setAttribute(tenantNodeRef, ATTR_KEY_SHAREDIDS_ROOT, sharedId);
                return null;
            }
        });

        final StringBuffer sb = new StringBuffer();
        sb.append("{").append("\"sharedId\":\"").append(sharedId).append("\"").append("}");

        eventPublisher.publishEvent(new EventPreparator() {
            @Override
            public Event prepareEvent(String user, String networkId, String transactionId) {
                return new ActivityEvent("quickshare", transactionId, networkId, user, nodeRef.getId(), null,
                        typeQName.toString(), Client.asType(ClientType.webclient), sb.toString(), null, null,
                        0l, null);
            }
        });

        if (logger.isInfoEnabled()) {
            logger.info("QuickShare - shared content: " + sharedId + " [" + nodeRef + "]");
        }
    } else {
        sharedId = (String) nodeService.getProperty(nodeRef, QuickShareModel.PROP_QSHARE_SHAREDID);
        if (logger.isDebugEnabled()) {
            logger.debug("QuickShare - content already shared: " + sharedId + " [" + nodeRef + "]");
        }
    }

    return new QuickShareDTO(sharedId);
}

From source file:org.alfresco.repo.quickshare.QuickShareServiceIntegrationTest.java

@Test(expected = InvalidSharedIdException.class)
public void getMetadataFromShareIdWithInvalidId() {
    UUID uuid = UUIDGenerator.getInstance().generateRandomBasedUUID();
    String sharedId = Base64.encodeBase64URLSafeString(uuid.toByteArray()); // => 22 chars (eg. q3bEKPeDQvmJYgt4hJxOjw)

    Map<String, Object> metadata = quickShareService.getMetaData(sharedId);
}

From source file:org.apache.abdera2.activities.extra.Jwt.java

public static String generate(IO io, Alg alg, Key key, byte[] claim, ASBase header) {
    try {/*from   w w w  .  j av a 2s. c om*/
        checkNotNull(header);
        checkNotNull(header.getProperty("alg"));
        StringBuilder buf = new StringBuilder();
        String _header = Base64.encodeBase64URLSafeString(checkNotNull(io).write(header).getBytes("UTF-8"));
        String _claim = Base64.encodeBase64URLSafeString(claim);
        buf.append(_header).append('.').append(_claim);
        String mat = buf.toString();
        buf.append('.').append(alg.sig(key, mat.getBytes("UTF-8")));
        return buf.toString();
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
}