Skip to content

Instantly share code, notes, and snippets.

@instcode
Created May 9, 2014 23:26

Revisions

  1. instcode created this gist May 9, 2014.
    70 changes: 70 additions & 0 deletions Crypto.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,70 @@
    package com.puppycloud.game.cheat;
    import java.security.MessageDigest;

    import javax.crypto.Cipher;
    import javax.crypto.Mac;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;

    public class Crypto {

    public static byte[] HMACMD5(String s, String keyString) {
    try {
    SecretKeySpec key = new SecretKeySpec(
    (keyString).getBytes("UTF-8"), "HmacMD5");
    Mac mac = Mac.getInstance("HmacMD5");
    mac.init(key);

    byte[] bytes = mac.doFinal(s.getBytes("ASCII"));
    return bytes;
    } catch (Exception e) {
    e.printStackTrace();
    }
    return null;
    }

    public static String bytesToHexString(byte[] bytes) {
    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < bytes.length; i++) {
    String hex = String.format("%02x", 0xFF & bytes[i]);
    buffer.append(hex);
    }
    return buffer.toString();
    }

    public static byte[] stringToHexBytes(String s) {
    if ((s.length() % 2) == 1) {
    return new byte[0];
    }

    byte[] buffer = new byte[s.length() >> 1];
    for (int i = 0; i < s.length(); i += 2) {
    buffer[i >> 1] = (byte) Integer.parseInt(s.substring(i, i + 2), 16);
    }
    return buffer;
    }

    public static byte[] AES(boolean encrypt, byte[] key, byte[] iv, byte[] plain) {
    int mode = encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE;
    Cipher cipher;
    try {
    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(mode, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
    return cipher.doFinal(plain);
    } catch (Exception e) {
    e.printStackTrace();
    }
    return null;
    }

    public static byte[] MD5(String message) {
    try {
    byte[] bytes = message.getBytes("UTF-8");
    MessageDigest md = MessageDigest.getInstance("MD5");
    return md.digest(bytes);
    } catch (Exception e) {
    e.printStackTrace();
    }
    return null;
    }
    }