Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.javieraviles.utils.security;
- import javax.crypto.Cipher;
- import javax.crypto.spec.SecretKeySpec;
- import sun.misc.BASE64Decoder;
- import sun.misc.BASE64Encoder;
- /**
- * @author JAVIERAVILES
- *
- * This class will encrypt/decrypt strings (intended for passwords mainly) into any specified algorithm with a secret.
- *
- * The initial purpose of it is to encrypt/decrypt passwords (maybe stored in atable in the database and want to be read?)
- */
- public class StringCipher {
- private static final String secret = "your-secret-here";
- private static final String algorithm = "Blowfish";
- /**
- * Encrypts a string (intended for passwords) with the specified secret and algorithm. base 64.
- *
- * @param password the password to be encrypted, plain text
- * @return the encrypted password
- * @throws Exception in case some error happens in the process of encrypting
- */
- public static String encrypt(final String password) throws Exception {
- byte[] keyData = secret.getBytes();
- SecretKeySpec secretKeySpec = new SecretKeySpec(keyData, algorithm);
- Cipher cipher = Cipher.getInstance(algorithm);
- cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
- byte[] hasil = cipher.doFinal(password.getBytes());
- return new BASE64Encoder().encode(hasil);
- }
- /**
- * Decrypts a string (intended for passwords) with the specified secret and algorithm. base 64.
- *
- * @param password the password to be decrypted
- * @return the decrypted password, plain text
- * @throws Exception in case some error happens in the process of decrypting
- */
- public static String decrypt(final String string) throws Exception {
- byte[] keyData = secret.getBytes();
- SecretKeySpec secretKeySpec = new SecretKeySpec(keyData, algorithm);
- Cipher cipher = Cipher.getInstance(algorithm);
- cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
- byte[] hasil = cipher.doFinal(new BASE64Decoder().decodeBuffer(string));
- return new String(hasil);
- }
- }
Add Comment
Please, Sign In to add comment