Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class EncryptionUtils {
- private MessageDigest dg = null;
- private String username, password;
- private byte[] key = null;
- public EncryptionUtils(String username, String password) {
- this.username = username;
- this.password = password;
- }
- public String encode(String message) {
- return byteArrayToString(getEncode(getKey(), message));
- }
- public String dencode(String message) {
- try {
- return new String(aes256Dec(getKey(), getEncode(getKey(), message)));
- } catch (Exception e) {
- e.printStackTrace();
- }
- return "";
- }
- private byte[] getKey() {
- if (key != null) {
- return key;
- }
- try {
- return hash(arrayMerge(username.getBytes(), hash(password.getBytes())));
- } catch (Exception e) {
- e.printStackTrace();
- }
- return new byte[]{0};
- }
- private byte[] getEncode(byte[] key, String message) {
- try {
- return aes256Enc(key, message.getBytes());
- } catch (Exception e) {
- e.printStackTrace();
- }
- return new byte[]{0};
- }
- private String byteArrayToString(byte[] bArr) {
- return DatatypeConverter.printHexBinary(bArr);
- }
- public byte[] stringToByteArray(String str) {
- return DatatypeConverter.parseHexBinary(str);
- }
- private byte[] arrayMerge(byte[] arr1, byte[] arr2) {
- byte[] res = new byte[arr1.length + arr2.length];
- System.arraycopy(arr1, 0, res, 0, arr1.length);
- System.arraycopy(arr2, 0, res, arr1.length, arr2.length);
- return res;
- }
- private byte[] hash(byte[] in) throws Exception {
- if (dg == null)
- dg = MessageDigest.getInstance("SHA-256");
- return dg.digest(in);
- }
- private byte[] aes256Enc(byte[] key, byte[] in) throws Exception {
- Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
- SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
- cipher.init(Cipher.ENCRYPT_MODE, secretKey);
- return cipher.doFinal(in);
- }
- private byte[] aes256Dec(byte[] key, byte[] in) throws Exception {
- Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
- SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
- cipher.init(Cipher.DECRYPT_MODE, secretKey);
- return cipher.doFinal(in);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement