Package com.gwcworld.util

Source Code of com.gwcworld.util.SymmetricCipher

package com.gwcworld.util;

import java.security.Key;

import javax.crypto.spec.SecretKeySpec;
import javax.crypto.Cipher;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class SymmetricCipher {

  private static final String ALGORITHM = "AES";

  public static String encrypt(String salt, String content) throws Exception {
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, generateKey(salt));
    byte[] encryptedBytes = cipher.doFinal(content.getBytes());
    return new BASE64Encoder().encode(encryptedBytes);
  }

  public static String decrypt(String salt, String content) throws Exception {
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(Cipher.DECRYPT_MODE, generateKey(salt));
    byte[] decryptedBytes = cipher.doFinal(new BASE64Decoder().decodeBuffer(content));
    return new String(decryptedBytes);
  }
 
  private static Key generateKey(String keyValue) throws Exception {
        Key key = new SecretKeySpec(keyValue.getBytes(), ALGORITHM);
        return key;
}

}
TOP

Related Classes of com.gwcworld.util.SymmetricCipher

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.