Skip to content

Instantly share code, notes, and snippets.

@deniszink
Created March 28, 2018 12:01
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 deniszink/e4ae4c7544b69118890f39f64306a640 to your computer and use it in GitHub Desktop.
Save deniszink/e4ae4c7544b69118890f39f64306a640 to your computer and use it in GitHub Desktop.
import com.sun.org.apache.xml.internal.security.encryption.EncryptionMethod;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.URLEncoder;
import java.security.*;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import java.util.Optional;
public class Main {
private static final String ENCRYPTION_KEY = "CCxcZiyhVyBnnP52Y79wVRLtRCStun2X";
static String testJson = "{\"expires\":1522270800,\"guid\":39655946,\"display_name\":\"semion\"," +
"\"email\":\"semion@seekingalpha.com\",\"locale\":\"en\"," +
"\"avatar_url\":\"https://dev2.cdn-seekingalpha.com/images/users_profile/039/655/946/big_pic.png\"," +
"\"force_update_avatar\":true,\"verified_email\":true,\"custom_fields\":{\"beta_tester\":false}}";
private static final String ENCRYPTION_IV = "4e5Wa71fYoT7MFEX";
public static void main(String[] args) throws Exception {
/* String encrypt = encrypt(testJson);
String s = URLEncoder.encode(encrypt, "UTF-8");
System.out.println(s);
System.out.println(encrypt);*/
oldmain();
}
private static void oldmain() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IOException, IllegalBlockSizeException, BadPaddingException {
final SecureRandom rng = new SecureRandom();
// final SecretKey aesKey = createKey("AES", 256, Optional.empty(), Optional.of(rng));
Key key = makeKey();
final byte[] plaintext = testJson.getBytes("UTF-8");
final byte[] ciphertext;
{
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final Cipher aesCBC = Cipher.getInstance("AES/CBC/PKCS5Padding");
final IvParameterSpec ivForCBC = createIV(aesCBC.getBlockSize(), Optional.of(rng));
aesCBC.init(Cipher.ENCRYPT_MODE, key, ivForCBC);
baos.write(ivForCBC.getIV());
try (final CipherOutputStream cos = new CipherOutputStream(baos, aesCBC)) {
cos.write(plaintext);
}
ciphertext = baos.toByteArray();
byte[] update = aesCBC.update(plaintext);
byte[] finall = aesCBC.doFinal();
byte[] result = new byte[update.length + finall.length];
System.arraycopy(update, 0, result, 0, update.length);
System.arraycopy(finall, 0, result, update.length, finall.length);
byte[] iv = ivForCBC.getIV();
byte[] token = new byte[iv.length + result.length];
System.arraycopy(iv, 0, token, 0, iv.length);
System.arraycopy(result, 0, token, iv.length, result.length);
String s = java.util.Base64.getEncoder().encodeToString(token);
System.out.println(s);
String encode = URLEncoder.encode(s, "UTF-8");
System.out.println(encode);
System.out.println("Encrypted - " + Arrays.toString(ciphertext));
}
final byte[] decrypted;
{
final ByteArrayInputStream bais = new ByteArrayInputStream(ciphertext);
final Cipher aesCBC = Cipher.getInstance("AES/CBC/PKCS5Padding");
final IvParameterSpec ivForCBC = readIV(aesCBC.getBlockSize(), bais);
aesCBC.init(Cipher.DECRYPT_MODE, key, ivForCBC);
final byte[] buf = new byte[1_024];
try (final CipherInputStream cis = new CipherInputStream(bais, aesCBC);
final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
int read;
while ((read = cis.read(buf)) != -1) {
baos.write(buf, 0, read);
}
decrypted = baos.toByteArray();
}
}
System.out.println(new String(decrypted, "UTF-8"));
}
public static IvParameterSpec createIV(final int ivSizeBytes, final Optional<SecureRandom> rng) {
final byte[] iv = new byte[ivSizeBytes];
final SecureRandom theRNG = rng.orElse(new SecureRandom());
theRNG.nextBytes(iv);
return new IvParameterSpec(iv);
}
public static IvParameterSpec readIV(final int ivSizeBytes, final InputStream is) throws IOException {
final byte[] iv = new byte[ivSizeBytes];
int offset = 0;
while (offset < ivSizeBytes) {
final int read = is.read(iv, offset, ivSizeBytes - offset);
if (read == -1) {
throw new IOException("Too few bytes for IV in input stream");
}
offset += read;
}
return new IvParameterSpec(iv);
}
static Key makeKey() {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] key = md.digest(ENCRYPTION_KEY.getBytes("UTF-8"));
return new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
public static SecretKey createKey(final String algorithm, final int keysize,
final Optional<Provider> provider,
final Optional<SecureRandom> rng) throws NoSuchAlgorithmException {
final KeyGenerator keyGenerator;
if (provider.isPresent()) {
keyGenerator = KeyGenerator.getInstance(algorithm, provider.get());
} else {
keyGenerator = KeyGenerator.getInstance(algorithm);
}
if (rng.isPresent()) {
keyGenerator.init(keysize, rng.get());
} else {
// not really needed for the Sun provider which handles null OK
keyGenerator.init(keysize);
}
return keyGenerator.generateKey();
}
public static String encrypt(String src) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, makeKey(), makeIv());
return Base64.encodeBytes(cipher.doFinal(src.getBytes()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static AlgorithmParameterSpec makeIv() {
try {
return new IvParameterSpec(ENCRYPTION_IV.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment