Skip to content

Instantly share code, notes, and snippets.

@zhong-j-yu
Created May 19, 2015 04:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhong-j-yu/9d23c850e580d60ddd46 to your computer and use it in GitHub Desktop.
Save zhong-j-yu/9d23c850e580d60ddd46 to your computer and use it in GitHub Desktop.
simple encrypt/decrypt utility
package bayou.util;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
class CryptoService
{
final byte[] cryptoKeyBytes;
final SecretKeySpec AES128KEY;
CryptoService(String encryptionKey)
{
this.cryptoKeyBytes = encryptionKey.getBytes();
this.AES128KEY = new SecretKeySpec(cryptoKeyBytes, 0, 128/8, "AES");
}
public String encrypt(String plainString)
{
byte[] plainBytes = plainString.getBytes(StandardCharsets.UTF_8);
byte[] hashPlainBytes = enhash( plainBytes, 4 );
byte[] encryptedBytes = doAes128(Cipher.ENCRYPT_MODE , hashPlainBytes );
String encryptedBase64 = Base64.getEncoder().withoutPadding().encodeToString(encryptedBytes);
return encryptedBase64;
}
public String decrypt(String encryptedBase64)
{
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedBase64);
byte[] hashPlainBytes = doAes128(Cipher.DECRYPT_MODE , encryptedBytes );
byte[] plainBytes = dehash( hashPlainBytes, 4 );
String plainString = new String(plainBytes, StandardCharsets.UTF_8);
return plainString;
}
public byte[] doAes128(int mode, byte[] bytes)
{
try
{
Cipher cipher = Cipher.getInstance("AES");
cipher.init(mode, AES128KEY);
return cipher.doFinal( bytes );
}
catch (GeneralSecurityException e)
{
throw new RuntimeException(e);
}
}
static byte[] sha256(byte[] bytes1, byte[] bytes2)
{
try
{
MessageDigest md = MessageDigest.getInstance("SHA-256");
if(bytes1 !=null) md.update(bytes1);
if(bytes2 !=null) md.update(bytes2);
return md.digest();
}
catch (NoSuchAlgorithmException e)
{
throw new RuntimeException(e);
}
}
static byte[] enhash(byte[] bytes, int HASH_BYTES)
{
byte[] hash = sha256(bytes, null);
byte[] joined = new byte[HASH_BYTES + bytes.length];
System.arraycopy(hash, 0, joined, 0, HASH_BYTES);
System.arraycopy(bytes,0, joined, HASH_BYTES, bytes.length);
return joined;
}
static byte[] dehash(byte[] joined, int HASH_BYTES)
{
byte[] bytes = new byte[joined.length-HASH_BYTES];
System.arraycopy(joined, HASH_BYTES, bytes, 0, bytes.length);
byte[] hash = sha256(bytes, null);
for(int i=0; i<HASH_BYTES; i++)
if(hash[i]!=joined[i])
throw new RuntimeException("hash mismatch");
return bytes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment