Created
May 9, 2014 23:26
-
-
Save instcode/77e8fa36864976e5b717 to your computer and use it in GitHub Desktop.
HMAC for hashing secret, AES for encrypting/decrypting data
This file contains hidden or 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
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment