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:com.teasoft.teavote.util.Signature.java

private PublicKey getPublicKey()
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
    Resource resource = res.getResource("classpath:gotaSafui");
    byte[] pubKeyBytes;
    try (InputStream pubKeyInputStream = resource.getInputStream()) {
        pubKeyBytes = IOUtils.toByteArray(pubKeyInputStream);
        pubKeyBytes = Base64.decodeBase64(pubKeyBytes);
    }/*  ww  w.  j  a v  a2s.  c o m*/
    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKeyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
    PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
    return pubKey;
}

From source file:com.vangent.hieos.xutil.soap.Mtom.java

public void decode(OMElement document) throws XdsIOException, IOException {
    this.document = document;
    OMText binaryNode = (OMText) document.getFirstOMChild();
    //System.out.println("isOptimized: " + binaryNode.isOptimized());

    xop = binaryNode.isOptimized();// w ww  . ja  v  a 2  s.c o  m

    if (xop) {
        javax.activation.DataHandler datahandler = (javax.activation.DataHandler) binaryNode.getDataHandler();
        InputStream is = null;
        try {
            is = datahandler.getInputStream();
            contents = Io.getBytesFromInputStream(is);
        } catch (IOException e) {
            throw new XdsIOException("Error accessing XOP encoded document content from message");
        }
        this.content_type = datahandler.getContentType();
    } else {
        String base64 = binaryNode.getText();
        contents = Base64.decodeBase64(base64.getBytes());
        /* BHT: REMOVED (and replaced with above line).
        BASE64Decoder d  = new BASE6decoded.toString();4Decoder();
        contents = d.decodeBuffer(base64);
         */
        this.content_type = null;
    }
}

From source file:jp.co.golorp.emarf.util.CryptUtil.java

/**
 * Base64??AES????/*from   www. j a  v  a2 s.co  m*/
 *
 * @param encryped
 *            ?
 * @return ?
 */
public static String decrypt(final String encryped) {

    if (encryped == null) {
        return null;
    }

    byte[] input = Base64.decodeBase64(encryped);

    byte[] decrypted = cipher(Cipher.DECRYPT_MODE, input);

    String ret = new String(decrypted);

    LOG.debug("Decrypt [" + encryped + "] to [" + ret + "].");

    return ret;
}

From source file:com.at.lic.LicenseControl.java

private boolean validateLicense() {
    boolean isValid = false;
    File f = new File(licenseKeyFilepath);
    if (f.exists() && f.isFile() && f.canRead()) {
        Serializer serializer = new Persister();
        License lic = null;// w w w. j a v a  2s .c o  m
        try {
            lic = serializer.read(License.class, f);
        } catch (Exception e) {
            log.error("License file reading failed.", e);
            isValid = false;
            return isValid;
        }

        String lic_checkCode = lic.getCheckCode();
        String lic_code = lic.getLicenseCode();
        String sign_code = lic.getSignCode();
        String sign_date = lic.getSignDate();

        String lcc = getLicenseCheckCode(); // get license check code
        if (!lcc.equals(lic_checkCode)) {
            log.error("License file is not for this machine.");
            isValid = false;
            return isValid;
        }

        StringBuilder sb = new StringBuilder();
        sb.append(lcc);
        sb.append(lic_code);
        sb.append(sign_date);
        String text = sb.toString();

        byte[] signature = Base64.decodeBase64(sign_code);

        try {
            isValid = RSAKeyManager.validSign(text, signature);
        } catch (Exception e) {
            log.error("Validate sign failed.", e);
            isValid = false;
            return isValid;
        }

    }
    return isValid;
}

From source file:com.dianxin.imessage.common.util.SignUtil.java

public static boolean verifySign(String src, String sign, PublicKey publicKey) {
    try {//from w  w w  . j a va 2  s. co m
        Signature rsa = Signature.getInstance("SHA1WithRSA");

        rsa.initVerify(publicKey);
        rsa.update(src.getBytes());
        return rsa.verify(Base64.decodeBase64(sign.getBytes()));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:com.rackspacecloud.blueflood.io.serializers.astyanax.TimerSerializationTest.java

@Test
public void testV1RoundTrip() throws IOException {
    // build up a Timer
    BluefloodTimerRollup r0 = new BluefloodTimerRollup().withSum(Double.valueOf(42)).withCountPS(23.32d)
            .withAverage(56).withVariance(853.3245d).withMinValue(2).withMaxValue(987).withCount(345);
    r0.setPercentile("foo", 741.32d);
    r0.setPercentile("bar", 0.0323d);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    //The V1 serialization is artificially constructed for the purposes of this test and should no longer be used.
    baos.write(//w  w  w . j a  v  a2s  . co  m
            Base64.encodeBase64(Serializers.timerRollupInstance.toByteBufferWithV1Serialization(r0).array()));
    baos.write("\n".getBytes());
    baos.close();

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(new ByteArrayInputStream(baos.toByteArray())));
    ByteBuffer bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
    BluefloodTimerRollup r1 = Serializers.timerRollupInstance.fromByteBuffer(bb);
    Assert.assertEquals(r0, r1);
}

From source file:net.arccotangent.pacchat.net.Client.java

public static void sendMessage(String msg, String ip_address) {
    client_log.i("Sending message to " + ip_address);
    client_log.i("Connecting to server...");

    PublicKey pub;/*from www .j av  a 2 s.  c o  m*/
    PrivateKey priv;
    Socket socket;
    BufferedReader input;
    BufferedWriter output;

    client_log.i("Checking for recipient's public key...");
    if (KeyManager.checkIfIPKeyExists(ip_address)) {
        client_log.i("Public key found.");
    } else {
        client_log.i("Public key not found, requesting key from their server.");
        try {
            Socket socketGetkey = new Socket();
            socketGetkey.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000);
            BufferedReader inputGetkey = new BufferedReader(
                    new InputStreamReader(socketGetkey.getInputStream()));
            BufferedWriter outputGetkey = new BufferedWriter(
                    new OutputStreamWriter(socketGetkey.getOutputStream()));

            outputGetkey.write("301 getkey");
            outputGetkey.newLine();
            outputGetkey.flush();

            String pubkeyB64 = inputGetkey.readLine();
            byte[] pubEncoded = Base64.decodeBase64(pubkeyB64);
            X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            outputGetkey.close();
            inputGetkey.close();

            KeyManager.saveKeyByIP(ip_address, keyFactory.generatePublic(pubSpec));
        } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
            client_log.e("Error saving recipient's key!");
            e.printStackTrace();
        }
    }

    try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000);
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    } catch (SocketTimeoutException e) {
        client_log.e("Connection to server timed out!");
        e.printStackTrace();
        return;
    } catch (ConnectException e) {
        client_log.e("Connection to server was refused!");
        e.printStackTrace();
        return;
    } catch (UnknownHostException e) {
        client_log.e("You entered an invalid IP address!");
        e.printStackTrace();
        return;
    } catch (IOException e) {
        client_log.e("Error connecting to server!");
        e.printStackTrace();
        return;
    }

    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    pub = KeyManager.loadKeyByIP(ip_address);
    priv = Main.getKeypair().getPrivate();

    String cryptedMsg = MsgCrypto.encryptAndSignMessage(msg, pub, priv);
    try {
        client_log.i("Sending message to recipient.");
        output.write("200 encrypted message");
        output.newLine();
        output.write(cryptedMsg);
        output.newLine();
        output.flush();

        String ack = input.readLine();
        switch (ack) {
        case "201 message acknowledgement":
            client_log.i("Transmission successful, received server acknowledgement.");
            break;
        case "202 unable to decrypt":
            client_log.e(
                    "Transmission failure! Server reports that the message could not be decrypted. Did your keys change? Asking recipient for key update.");
            kuc_id++;
            KeyUpdateClient kuc = new KeyUpdateClient(kuc_id, ip_address);
            kuc.start();
            break;
        case "203 unable to verify":
            client_log.w("**********************************************");
            client_log.w(
                    "Transmission successful, but the receiving server reports that the authenticity of the message could not be verified!");
            client_log.w(
                    "Someone may be tampering with your connection! This is an unlikely, but not impossible scenario!");
            client_log.w(
                    "If you are sure the connection was not tampered with, consider requesting a key update.");
            client_log.w("**********************************************");
            break;
        case "400 invalid transmission header":
            client_log.e(
                    "Transmission failure! Server reports that the message is invalid. Try updating your software and have the recipient do the same. If this does not fix the problem, report the error to developers.");
            break;
        default:
            client_log.w("Server responded with unexpected code: " + ack);
            client_log.w("Transmission might not have been successful.");
            break;
        }

        output.close();
        input.close();
    } catch (IOException e) {
        client_log.e("Error sending message to recipient!");
        e.printStackTrace();
    }
}

From source file:com.cisco.oss.foundation.directory.utils.ObfuscatUtil.java

/**
 * base64 decode./* w w  w.j a va 2  s. c  o m*/
 *
 * @param base64Buffer
 *         the base64 encoded byte array.
 * @return
 *         the decoded byte array.
 */
public static byte[] base64Decode(byte[] base64Buffer) {
    return Base64.decodeBase64(base64Buffer);
}

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

/**
 * @param base64Key//from  www  . j av a2s .  c o m
 * @return
 * @throws GeneralSecurityException
 */
public Key getKey(String base64Key) throws GeneralSecurityException {
    byte[] keyBytes = Base64.decodeBase64(base64Key.getBytes());
    Key key = new SecretKeySpec(keyBytes, algorithm);
    return key;
}

From source file:com.aperigeek.dropvault.web.service.AuthenticationService.java

public User checkAuthentication(String header)
        throws InvalidPasswordException, NotAuthorizedException, ProtocolException {

    if (header == null) {
        throw new InvalidPasswordException();
    }/* w  w  w.ja  v  a2 s .c  o  m*/

    Pattern headerPattern = Pattern.compile("Basic (.+)");
    Matcher headerMatcher = headerPattern.matcher(header);

    if (!headerMatcher.matches()) {
        throw new ProtocolException("Invalid Authorization header");
    }

    String b64 = headerMatcher.group(1);
    String headerContent = new String(Base64.decodeBase64(b64));

    Pattern passwordPattern = Pattern.compile("(.+):([^:]+)");
    Matcher passwordMatcher = passwordPattern.matcher(headerContent);

    if (!passwordMatcher.matches()) {
        throw new ProtocolException("Invalid authentication header");
    }

    String user = passwordMatcher.group(1);
    String password = passwordMatcher.group(2);
    String hashPassword = hashService.hash(password);

    if (usersDAO.login(user, hashPassword)) {
        return new User(user, password);
    }

    throw new InvalidPasswordException();
}