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

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

Introduction

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

Prototype

public Base64() 

Source Link

Document

Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

Usage

From source file:amazon.SignedRequestsHelper.java

/**
 * Compute the HMAC.//from w w w . ja  v a2 s .  co  m
 *  
 * @param stringToSign  String to compute the HMAC over.
 * @return              base64-encoded hmac value.
 */
private String hmac(String stringToSign) {
    String signature = null;
    byte[] data;
    byte[] rawHmac;
    try {
        data = stringToSign.getBytes(UTF8_CHARSET);
        rawHmac = mac.doFinal(data);
        Base64 encoder = new Base64();
        signature = new String(encoder.encode(rawHmac));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(UTF8_CHARSET + " is unsupported!", e);
    }
    return signature;
}

From source file:ecommerceParser.searchModule.SignedRequestsHelper.java

/**
 * Compute the HMAC./* ww w  .j a va2s . co  m*/
 *
 * @param stringToSign  String to compute the HMAC over.
 * @return              base64-encoded hmac value.
 */
private String hmac(String stringToSign) {
    String signature = null;
    byte[] data;
    byte[] rawHmac;
    try {
        data = stringToSign.getBytes(UTF8_CHARSET);
        rawHmac = mac.doFinal(data);
        //Base64.main();
        Base64 encoder = new Base64();
        signature = new String(encoder.encode(rawHmac));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(UTF8_CHARSET + " is unsupported!", e);
    }
    return signature;
}

From source file:com.forsrc.utils.MyRsaUtils.java

/**
 * Encrypt 2 string./*from   w  w w  .  j a v  a2 s  .  c  o  m*/
 *
 * @param rsaKey    the rsa key
 * @param plaintext the plaintext
 * @return the string
 */
public static String encrypt2(RsaKey rsaKey, String plaintext) {

    BigInteger[] plaintextBigIntegers = string2BigIntegers(plaintext);
    StringBuilder sb = new StringBuilder(BLOCK_SIZE + 1);
    for (BigInteger bigInteger : plaintextBigIntegers) {
        BigInteger encrypt = encrypt(rsaKey, bigInteger);
        sb.append(encrypt.toString()).append("$");
    }
    sb.delete(sb.length() - 1, sb.length());

    return new String(new Base64().encode(sb.toString().getBytes()));
}

From source file:com.trsst.client.Client.java

/**
 * Returns a Feed for the specified feed id, and will attempt to decrypt any
 * encrypted content with the specified key.
 * //  w  w w.ja va2  s  .  c  om
 * @param urn
 *            a feed or entry urn id.
 * @param decryptionKey
 *            one or more private keys used to attempt to decrypt content.
 * @return a Feed containing the latest entries for this feed id.
 */
public Feed pull(String urn, PrivateKey[] decryptionKeys) {
    Feed feed = pull(urn);
    if (feed == null) {
        return null;
    }

    Content content;
    MimeType contentType;
    for (Entry entry : feed.getEntries()) {
        content = entry.getContentElement();
        if (content != null && (contentType = content.getMimeType()) != null
                && "application/xenc+xml".equals(contentType.toString())) {

            // if this message was intended for us, we will be able to
            // decrypt one of the elements into an AES key to decrypt the
            // encrypted entry itself

            QName publicEncryptName = new QName(Common.NS_URI, Common.ENCRYPT);
            QName publicSignName = new QName(Common.NS_URI, Common.SIGN);
            QName encryptedDataName = new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedData");
            QName cipherDataName = new QName("http://www.w3.org/2001/04/xmlenc#", "CipherData");
            QName cipherValueName = new QName("http://www.w3.org/2001/04/xmlenc#", "CipherValue");

            String encodedBytes;
            byte[] decodedBytes;
            Element publicKeyElement, cipherData, cipherValue, result;
            List<Element> encryptedElements = content.getElements();
            int lastIndex = encryptedElements.size() - 1;
            Element element;
            PublicKey publicKey = null;
            byte[] decryptedKey = null;

            publicKeyElement = feed.getFirstChild(publicEncryptName);
            if (publicKeyElement == null) {
                // fall back on signing key
                publicKeyElement = feed.getFirstChild(publicSignName);
            }
            if (publicKeyElement != null && publicKeyElement.getText() != null) {
                try {
                    publicKey = Common.toPublicKeyFromX509(publicKeyElement.getText());
                } catch (GeneralSecurityException gse) {
                    log.error("Could not parse public key: " + publicKeyElement);
                }
            }

            if (publicKey != null) {

                // TODO: if we're the author, we can start loop at
                // (lastIndex-1)
                for (int i = 0; i < encryptedElements.size(); i++) {
                    element = encryptedElements.get(i);
                    if (encryptedDataName.equals(element.getQName())) {
                        cipherData = element.getFirstChild(cipherDataName);
                        if (cipherData != null) {
                            cipherValue = cipherData.getFirstChild(cipherValueName);
                            if (cipherValue != null) {
                                encodedBytes = cipherValue.getText();
                                if (encodedBytes != null) {
                                    decodedBytes = new Base64().decode(encodedBytes);
                                    if (i != lastIndex) {
                                        // if we're not at the last index
                                        // (the payload) so we should
                                        // attempt
                                        // to decrypt this AES key
                                        for (PrivateKey decryptionKey : decryptionKeys) {
                                            try {
                                                decryptedKey = Crypto.decryptKeyWithIES(decodedBytes,
                                                        entry.getUpdated().getTime(), publicKey, decryptionKey);
                                                if (decryptedKey != null) {
                                                    // success:
                                                    // skip to lastIndex
                                                    i = lastIndex - 1;
                                                    break;
                                                }
                                            } catch (GeneralSecurityException e) {
                                                // key did not fit
                                                log.trace("Could not decrypt key: " + entry.getId(), e);
                                            } catch (Throwable t) {
                                                log.warn(
                                                        "Error while decrypting key on entry: " + entry.getId(),
                                                        t);
                                            }
                                        }
                                    } else if (decryptedKey != null) {
                                        // if we're at the last index
                                        // (the payload) and we have an
                                        // AES key: attempt to decrypt
                                        try {
                                            result = decryptElementAES(decodedBytes, decryptedKey);
                                            for (Element ee : encryptedElements) {
                                                ee.discard();
                                            }
                                            content.setValueElement(result);
                                            break;
                                        } catch (SecurityException e) {
                                            log.error("Key did not decrypt element: " + entry.getId(), e);
                                        } catch (Throwable t) {
                                            log.warn("Could not decrypt element on entry: " + entry.getId(), t);
                                        }
                                    }
                                } else {
                                    log.warn("No cipher text for entry: " + entry.getId());
                                }
                            } else {
                                log.warn("No cipher value for entry: " + entry.getId());
                            }
                        } else {
                            log.warn("No cipher data for entry: " + entry.getId());
                        }
                    }
                }

            } else {
                log.error("No public key for feed: " + feed.getId());
            }
        }
    }
    return feed;
}

From source file:com.titilink.camel.rest.util.OtherUtil.java

/**
 * ?BASE64?//  w  w  w.j  a  va  2  s.com
 *
 * @param base64EncodeStr --?BASE64?
 * @return String          --??
 */
public static String strBase64Decode(String base64EncodeStr) {
    Base64 b64 = new Base64();
    byte[] b = b64.decode(base64EncodeStr.getBytes());
    return new String(b);
}

From source file:fi.aalto.seqpig.filter.CoordinateFilter.java

protected void decodeRegions() {
    try {/* w  w  w  .j  a va 2  s  .com*/
        Base64 codec = new Base64();
        Properties p = UDFContext.getUDFContext().getUDFProperties(this.getClass());
        this.regions_str = p.getProperty("regionsstr");

        //System.err.println("decoded regions!");
    } catch (Exception e) {
        //System.err.println("error: "+e.toString());
    }

    populateRegions();
}

From source file:de.alpharogroup.crypto.key.reader.PrivateKeyReader.java

/**
 * Read pem private key./*ww w. ja  v  a2s .  c  om*/
 *
 * @param file
 *            the file
 * @param securityProvider
 *            the security provider
 * @return the private key
 * @throws Exception
 *             is thrown if if a security error occur
 */
public static PrivateKey readPemPrivateKey(final File file, final SecurityProvider securityProvider)
        throws Exception {
    final String privateKeyAsString = readPemFileAsBase64(file);
    final byte[] decoded = new Base64().decode(privateKeyAsString);
    return readPrivateKey(decoded, securityProvider);
}

From source file:com.ligadata.EncryptUtils.EncryptionUtil.java

/**
 * Decode(Base64 decoding) given byte array to a string
 * //from   ww w . j  a  v  a2s  .  c om
 * @param bytes
 *          : the encoded value as array of bytes 
 * @return decoded value as a String
 * @throws java.lang.Exception an exception is thrown
 */

public static String decode(byte[] bytes) throws Exception {
    try {
        Base64 base64 = new Base64();
        String decoded = new String(base64.decode(bytes));
        return decoded;
    } catch (Exception e) {
        logger.error("Failed to decode a byte array", e);
        throw e;
    }
}

From source file:com.forsrc.utils.MyRsaUtils.java

/**
 * Decrypt 2 string.//  w  ww. j av  a  2  s. c om
 *
 * @param rsaKey    the rsa key
 * @param encrypted the encrypted
 * @return the string
 * @throws IOException the io exception
 */
public static String decrypt2(RsaKey rsaKey, String encrypted) throws IOException {

    String text = new String(new Base64().decode(encrypted));
    String[] texts = text.split("\\$");
    BigInteger[] bigIntegers = new BigInteger[texts.length];
    BigInteger bigInteger = null;
    for (int i = 0; i < bigIntegers.length; i++) {
        bigInteger = new BigInteger(texts[i]);
        bigIntegers[i] = decrypt(rsaKey, bigInteger);
    }

    return bigIntegers2String(bigIntegers);
}

From source file:com.hypersocket.client.HypersocketClient.java

public void loginHttp(String realm, String username, String password, boolean hashedPassword)
        throws IOException {

    Map<String, String> params = new HashMap<String, String>();
    Base64 base64 = new Base64();
    String authorization = "Basic " + new String(base64
            .encode((username + (StringUtils.isBlank(realm) ? "" : "@" + realm) + ":" + password).getBytes()));

    transport.setHeader("Authorization", authorization);

    String json = transport.post("logon/hypersocketClient", params);
    processLogon(json, params, new ArrayList<Prompt>());

    if (!isLoggedOn()) {
        disconnect(false);/*from w  ww .ja  va 2  s.c  o m*/
        throw new IOException("Failed to perform http logon");
    }

    postLogin();

}