Last active
October 21, 2020 08:15
-
-
Save Eldelshell/833c468a0deb4ebc3698cf3d90fe83e6 to your computer and use it in GitHub Desktop.
Encrypt & decrypt Java String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.security.Key; | |
import java.util.Optional; | |
import javax.crypto.Cipher; | |
import javax.crypto.spec.SecretKeySpec; | |
public class AESCrypto { | |
public Optional<String> encrypt (final String plain, final String secret) { | |
Key aesKey = new SecretKeySpec(secret.getBytes(), "AES"); | |
byte[] encBytes = null; | |
try { | |
Cipher cipher = Cipher.getInstance("AES"); | |
cipher.init(Cipher.ENCRYPT_MODE, aesKey); | |
encBytes = cipher.doFinal(plain.getBytes()); | |
} catch (Exception e) { | |
return Optional.empty(); | |
} | |
StringBuilder sb = new StringBuilder(); | |
for (byte b : encBytes) { | |
sb.append((char) b); | |
} | |
return Optional.of(sb.toString()); | |
} | |
public Optional<String> decrypt (final String encrypted, final String secret) { | |
Key aesKey = new SecretKeySpec(secret.getBytes(), "AES"); | |
byte[] bb = new byte[encrypted.length()]; | |
for (int i = 0; i < encrypted.length(); i++) { | |
bb[i] = (byte) encrypted.charAt(i); | |
} | |
try { | |
Cipher cipher = Cipher.getInstance("AES"); | |
cipher.init(Cipher.DECRYPT_MODE, aesKey); | |
return Optional.of(new String(cipher.doFinal(bb))); | |
} catch (Exception e) { | |
return Optional.empty(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment