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

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

Introduction

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

Prototype

public static byte[] decodeBase64(final byte[] base64Data) 

Source Link

Document

Decodes Base64 data into octets

Usage

From source file:net.fender.crypto.CryptoUtil.java

/**
 * Returns a key based on System.getProperties(). Use setSystemPropertyKey
 * and setSystemPropertyAlgorithm to configure, or manually set System
 * properties using SYSTEM_PROPERTY_KEY_PREFIX.
 * //from   w w w  . j  a v a2 s. c o  m
 * @param keyName
 * @return
 * @throws GeneralSecurityException
 */
public static Key getSystemPropertyKey(String keyName) throws GeneralSecurityException {
    String base64Key = System.getProperty(SYSTEM_PROPERTY_KEY_PREFIX + keyName);
    String algorithm = System.getProperty(SYSTEM_PROPERTY_KEY_PREFIX + keyName + ".algorithm");
    byte[] keyBytes = Base64.decodeBase64(base64Key.getBytes());
    Key key = new SecretKeySpec(keyBytes, algorithm);
    return key;
}

From source file:com.cloudera.flume.core.TestDigestDecorator.java

/**
 * A helper function used by most of the tests here to reduce
 * boilerplate.// w  w w  . ja v  a2 s  . c  o  m
 */
private void helpTestDigest(String algorithm, boolean encodeBase64) throws IOException, InterruptedException {
    MemorySinkSource mem = new MemorySinkSource();
    EventSink dig = new DigestDecorator<EventSink>(mem, algorithm, "digest", encodeBase64);

    Event e = new EventImpl("content".getBytes());

    dig.open();
    dig.append(e);
    dig.close();

    mem.open();
    Event e2 = mem.next();
    byte digest[] = e2.get("digest");
    if (encodeBase64) {
        digest = Base64.decodeBase64(digest);
    }
    try {
        MessageDigest stomach = MessageDigest.getInstance(algorithm);
        stomach.update("content".getBytes());
        assertArrayEquals(stomach.digest(), digest);
    } catch (NoSuchAlgorithmException ex) {
        fail("Invalid algorithm supplied: " + algorithm);
    }
}

From source file:com.authlete.common.web.BasicCredentials.java

/**
 * Parse {@code Authorization} header for Basic authentication.
 *
 * @param input/*w  w  w  .  j  a  va2s .c  o  m*/
 *         The value of {@code Authorization} header. Expected inputs
 *         are either <code>"Basic <i>{Base64-Encoded-UserID-and-Password}</i>"</code>,
 *         or <code>"<i>{Base64-Encoded-UserID-and-Password}</i>"</code>.
 *
 * @return
 *         Parsed credentials. If {@code input} is {@code null} is returned.
 */
public static BasicCredentials parse(String input) {
    if (input == null) {
        return null;
    }

    Matcher matcher = CHALLENGE_PATTERN.matcher(input);

    if (matcher.matches() == false) {
        return new BasicCredentials(null, null);
    }

    // "userid:password" encoded in Base64.
    String encoded = matcher.group(1);

    // Decode the base64 string.
    byte[] decoded = Base64.decodeBase64(encoded);

    // Convert the byte array to String.
    String value = createString(decoded);

    // Split "userid:password" into "userid" and "password".
    String[] credentials = value.split(":", 2);

    // User ID and Password.
    String userId = null;
    String password = null;

    switch (credentials.length) {
    case 2:
        // Password
        password = credentials[1];
        // FALLTHROUGH

    case 1:
        // User ID
        userId = credentials[0];
    }

    return new BasicCredentials(userId, password);
}

From source file:com.github.ambry.commons.BlobId.java

/**
 * Re-constructs existing blobId by deserializing from BlobId "string"
 *
 * @param id of Blob as output by BlobId.getID()
 * @param clusterMap of the cluster that the blob id belongs to
 * @throws IOException/*from www.j a  va2s .co m*/
 */
public BlobId(String id, ClusterMap clusterMap) throws IOException {
    this(new DataInputStream(new ByteBufferInputStream(ByteBuffer.wrap(Base64.decodeBase64(id)))), clusterMap);
}

From source file:edu.ncu.csie.oolab.CommandTest.java

@Test
public void testExecute() {
    HashMap<String, Object> args = new HashMap<String, Object>();
    args.put("command", "execute");
    args.put("script", "print \'Hello, world!\'\n");
    String b64Data = this.json_.toJson(args);
    b64Data = new String(Base64.encodeBase64(b64Data.getBytes(Charset.forName("UTF-8"))),
            Charset.forName("UTF-8"));
    b64Data = this.parser_.execute(b64Data);
    b64Data = new String(Base64.decodeBase64(b64Data.getBytes(Charset.forName("UTF-8"))),
            Charset.forName("UTF-8"));
    args = this.json_.fromJson(b64Data, (new TypeToken<HashMap<String, Object>>() {
    }).getType());/*w w  w.  jav a 2 s.  c  o m*/
    assertTrue((Boolean) args.get("success"));
}

From source file:com.cloudera.impala.catalog.PartitionStatsUtil.java

/**
 * Reconstructs a TPartitionStats object from its serialised form in the given parameter
 * map. Returns null if no stats are serialised, and throws an exception if there was an
 * error during deserialisation./*from   w w w .j  a v a  2s .  c o  m*/
 */
public static TPartitionStats partStatsFromParameters(Map<String, String> hmsParameters)
        throws ImpalaException {
    if (hmsParameters == null)
        return null;
    String numChunksStr = hmsParameters.get(INTERMEDIATE_STATS_NUM_CHUNKS);
    if (numChunksStr == null)
        return null;
    int numChunks = Integer.parseInt(numChunksStr);
    if (numChunks == 0)
        return null;

    Preconditions.checkState(numChunks >= 0);
    StringBuilder encodedStats = new StringBuilder();
    for (int i = 0; i < numChunks; ++i) {
        String chunk = hmsParameters.get(INTERMEDIATE_STATS_CHUNK_PREFIX + i);
        if (chunk == null) {
            throw new ImpalaRuntimeException("Missing stats chunk: " + i);
        }
        encodedStats.append(chunk);
    }

    byte[] decodedStats = Base64.decodeBase64(encodedStats.toString());
    TCompactProtocol.Factory protocolFactory = new TCompactProtocol.Factory();
    TPartitionStats ret = new TPartitionStats();
    JniUtil.deserializeThrift(protocolFactory, ret, decodedStats);
    return ret;
}

From source file:lucee.runtime.img.ImageUtil.java

public static byte[] readBase64(String b64str, StringBuilder mimetype) throws IOException {
    if (StringUtil.isEmpty(b64str))
        throw new IOException("base64 string is empty");

    // data:image/png;base64,
    int index = b64str.indexOf("base64,");
    if (index != -1) {
        int semiIndex = b64str.indexOf(";");
        if (mimetype != null && semiIndex < index && StringUtil.startsWithIgnoreCase(b64str, "data:")) {
            mimetype.append(b64str.substring(5, semiIndex).trim());
        }/*from  w  w w.  j  a va 2 s  .c  o m*/

        b64str = b64str.substring(index + 7);
    }

    return Base64.decodeBase64(b64str.getBytes());
}

From source file:net.orpiske.sas.service.processors.bean.EvalServiceBean.java

/**
 * Calculates the sentiment of the phrase based on the existence of
 * certain words in the text/*from   w w w  .  j a  v  a  2 s .  co  m*/
 * @param requestType the request object
 * @return A response object
 */
public ResponseType eval(RequestType requestType) throws IOException {
    ResponseType responseType = new ResponseType();
    String phrase;

    if (requestType.getEvalRequest().isCompressed()) {
        String encodedText = requestType.getEvalRequest().getPhrase();
        byte[] encodedBytes = Base64.decodeBase64(encodedText);

        phrase = Decompressor.decompress(encodedBytes);
    } else {
        phrase = requestType.getEvalRequest().getPhrase();
    }

    int score = getScore(phrase);

    EvalResponseType evalResponseType = new EvalResponseType();
    evalResponseType.setScore(score);
    responseType.setEvalResponse(evalResponseType);

    return responseType;
}

From source file:com.tasktop.c2c.server.internal.profile.crypto.OpenSSHPublicKeyReader.java

public SshPublicKey readPublicKey(String keySpec) {
    keySpec = keySpec.trim();/*from ww  w.  j  a  v  a2s  .c  o  m*/
    String[] parts = keySpec.split(" ");
    if (parts.length >= 2) {
        String algorithm = parts[0];
        String base64Data = parts[1];
        if (algorithm.equals("ssh-rsa")) {
            SshPublicKey sshPublicKey = new SshPublicKey();
            sshPublicKey.setAlgorithm("RSA");
            byte[] decodedData = Base64.decodeBase64(StringUtils.getBytesUtf8(base64Data));

            Rfc4253Reader reader = new Rfc4253Reader(decodedData, 0);

            try {
                byte[] format = reader.readBytes();
                byte[] exponent = reader.readBytes();
                byte[] modulus = reader.readBytes();

                if (Arrays.equals(FORMAT, format)) {
                    BigInteger exp = new BigInteger(exponent);
                    BigInteger mod = new BigInteger(modulus);
                    RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(mod, exp);
                    try {
                        PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(rsaPublicKeySpec);
                        sshPublicKey.setKeyData(publicKey.getEncoded());
                        return sshPublicKey;
                    } catch (InvalidKeySpecException t) {
                        getLogger().warn("Invalid key spec: " + t.getMessage(), t);
                    } catch (NoSuchAlgorithmException t) {
                        getLogger().warn("Invalid algorithm: " + t.getMessage(), t);
                    }
                }

            } catch (IOException e) {
                // ignore
            }
        }
    }
    return null;
}

From source file:com.alliander.osgp.shared.security.CertificateHelper.java

public static PrivateKey createPrivateKeyFromBase64(final String keyBase64, final String keyType,
        final String provider)
        throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, NoSuchProviderException {
    final byte[] key = Base64.decodeBase64(keyBase64);

    final PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(key);
    KeyFactory privateKeyFactory;
    privateKeyFactory = KeyFactory.getInstance(keyType, provider);
    return privateKeyFactory.generatePrivate(privateKeySpec);
}