Example usage for org.bouncycastle.util.encoders Base64Encoder decode

List of usage examples for org.bouncycastle.util.encoders Base64Encoder decode

Introduction

In this page you can find the example usage for org.bouncycastle.util.encoders Base64Encoder decode.

Prototype

public int decode(String data, OutputStream out) throws IOException 

Source Link

Document

decode the base 64 encoded String data writing it to the given output stream, whitespace characters will be ignored.

Usage

From source file:org.sonatype.security.ldap.upgrade.cipher.DefaultPlexusCipher.java

License:Open Source License

public String decrypt(String str, String passPhrase) throws PlexusCipherException {
    if (StringUtils.isEmpty(str))
        return str;

    try {// w w  w. ja  va 2s . com
        // Decode base64 to get bytes
        Base64Encoder decoder = new Base64Encoder();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        decoder.decode(str, baos);
        byte[] res = baos.toByteArray();

        int saltLen = res[0] & 0x00ff;
        if (saltLen != SALT_SIZE)
            throw new Exception("default.plexus.cipher.encryptedStringCorruptedStructure");

        if (res.length < (saltLen + 2))
            throw new Exception("default.plexus.cipher.encryptedStringCorruptedLength");

        byte[] salt = new byte[saltLen];
        System.arraycopy(res, 1, salt, 0, saltLen);

        int decLen = res.length - saltLen - 1;
        if (decLen < 1)
            throw new Exception("default.plexus.cipher.encryptedStringCorruptedSize");

        byte[] dec = new byte[decLen];
        System.arraycopy(res, saltLen + 1, dec, 0, decLen);

        // Decrypt
        Cipher cipher = init(passPhrase, salt, false);
        byte[] utf8 = cipher.doFinal(dec);

        // Decode using utf-8
        return new String(utf8, "UTF8");

    } catch (Exception e) {
        throw new PlexusCipherException(e);
    }
}