net.navasoft.madcoin.backend.services.security.Encrypter.java Source code

Java tutorial

Introduction

Here is the source code for net.navasoft.madcoin.backend.services.security.Encrypter.java

Source

/*******************************************************************************
 * Copyright 2014 Juan Diego Navarre Gonzalez
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package net.navasoft.madcoin.backend.services.security;

import java.security.MessageDigest;
import java.security.spec.KeySpec;
import java.util.Arrays;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.apache.commons.codec.binary.Base64;

/**
 * net.navasoft.madcoin.backend.services.security Class class Encrypter.
 * Description:
 * 
 * @author Juan Diego Navarre Gonzalez - (${authorMail})
 * @version 1.0
 * @since 5/08/2014 08:03:33 PM
 */
public class Encrypter {

    /**
     * key spec.
     * 
     * @since 5/08/2014, 08:03:33 PM
     */
    private KeySpec keySpec;

    /**
     * key.
     * 
     * @since 5/08/2014, 08:03:33 PM
     */
    private SecretKey key;

    /**
     * iv.
     * 
     * @since 5/08/2014, 08:03:33 PM
     */
    private IvParameterSpec iv;

    /**
     * Instantiates a new encrypter.
     * 
     * @param keyString
     *            the key string
     * @param ivString
     *            the iv string
     * @since 5/08/2014, 08:03:33 PM
     */
    public Encrypter(String keyString, String ivString) {
        try {
            final MessageDigest md = MessageDigest.getInstance("md5");
            final byte[] digestOfPassword = md.digest(Base64.decodeBase64(keyString.getBytes("utf-8")));
            final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
            for (int j = 0, k = 16; j < 8;) {
                keyBytes[k++] = keyBytes[j++];
            }

            keySpec = new DESedeKeySpec(keyBytes);

            key = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec);

            iv = new IvParameterSpec(ivString.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Encrypt.
     * 
     * @param value
     *            the value
     * @return the string
     * @since 5/08/2014, 08:03:33 PM
     */
    public String encrypt(String value) {
        try {
            Cipher ecipher = Cipher.getInstance("DESede/CBC/PKCS5Padding", "SunJCE");
            ecipher.init(Cipher.ENCRYPT_MODE, key, iv);

            if (value == null)
                return null;

            // Encode the string into bytes using utf-8
            byte[] utf8 = value.getBytes("UTF8");

            // Encrypt
            byte[] enc = ecipher.doFinal(utf8);

            // Encode bytes to base64 to get a string
            return new String(Base64.encodeBase64(enc), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Decrypt.
     * 
     * @param value
     *            the value
     * @return the string
     * @throws BadPaddingException
     *             the bad padding exception
     * @since 2/09/2014, 03:41:07 AM
     */
    public String decrypt(String value) throws BadPaddingException {
        try {
            Cipher dcipher = Cipher.getInstance("DESede/CBC/PKCS5Padding", "SunJCE");
            dcipher.init(Cipher.DECRYPT_MODE, key, iv);

            if (value == null)
                return null;

            // Decode base64 to get bytes
            byte[] dec = Base64.decodeBase64(value.getBytes());

            // Decrypt
            byte[] utf8 = dcipher.doFinal(dec);

            // Decode using utf-8
            return new String(utf8, "UTF8");
        } catch (Exception e) {
            if (e instanceof BadPaddingException) {
                throw (BadPaddingException) e;
            } else {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * The main method.
     * 
     * @param args
     *            the arguments
     * @since 5/08/2014, 08:57:04 PM
     */
    public static void main(String[] args) {

        try {
            String raw = "drandx/$2a$14$nv0yHyxSwnROrYnevt66TOx5pVCBr58wFiMOjkZKQScciwsiC18xG";
            Encrypter x = new Encrypter("Click-n-Done2014", "madcoins");
            String crypted = x.encrypt(raw);
            System.out.println("este es el token" + crypted);
            String dec;
            dec = x.decrypt(crypted);
            System.out.println(raw.split("/")[1]);
            System.out.println(dec.split("/")[1]);
            System.out.println(
                    raw + (BCrypt.checkpw(raw.split("/")[1], dec.split("/")[1]) ? " muchooooo!" : " es mentira"));
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }

    }
}