Last active
October 29, 2020 22:04
-
-
Save oyekanmiayo/4feaa4c807316e4fa950d3d159eed6e3 to your computer and use it in GitHub Desktop.
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 javax.crypto.Cipher; | |
import javax.crypto.spec.IvParameterSpec; | |
import javax.crypto.spec.SecretKeySpec; | |
public class AESCBCDecryption { | |
static final String cipher_type = "AES/CBC/PKCS5Padding"; | |
public static void main(String[] args) { | |
String key = "57067125438768260656188878670043"; | |
String iv = "5706712543876826"; | |
String data = "dd3364461dbca39ddb5eb32e9f11b81f000acac9ce8b91369f8bf7e4a88787785a8cc498c85ea20370e68f0e7014e92a2" + | |
"b5aedd4c670ec172d7adb45dfa5a770b582e8ed255bb857d94afdfd6e579525f24890070f984b8862133eda9cbb118ba7880db125c32dea7e7c54bc77abfc02"; | |
byte[] enc = decodeHexString(data); | |
byte[] dec = decode(key, iv, enc); | |
byte[] dec2= decode(key, iv, decodeHexString(new String(dec))); | |
System.out.println(new String(dec2)); | |
} | |
public static byte[] decode(String skey, String iv, byte[] data) { | |
return process(Cipher.DECRYPT_MODE, skey, iv, data); | |
} | |
private static byte[] process(int mode, String skey, String iv, byte[] data) { | |
SecretKeySpec key = new SecretKeySpec(skey.getBytes(), "AES"); | |
IvParameterSpec param = new IvParameterSpec(iv.getBytes()); | |
try { | |
Cipher cipher = Cipher.getInstance(cipher_type); | |
cipher.init(mode, key, param); | |
return cipher.doFinal(data); | |
} catch (Exception e) { | |
System.err.println(e.getMessage()); | |
throw new RuntimeException(e); | |
} | |
} | |
public static byte[] decodeHexString(String hexString) { | |
if(hexString.length() % 2 != 0){ | |
hexString = addLeadingZeros(hexString.length() + 1, hexString); | |
} | |
byte[] bytes = new byte[hexString.length() / 2]; | |
for (int i = 0; i < hexString.length(); i += 2) { | |
bytes[i / 2] = hexToByte(hexString.substring(i, i + 2)); | |
} | |
return bytes; | |
} | |
private static String addLeadingZeros(int count, String hexString) { | |
StringBuilder sb = new StringBuilder(); | |
while (count-- > 0){ | |
sb.append('0'); | |
} | |
sb.append(hexString); | |
return sb.toString(); | |
} | |
public static byte hexToByte(String hexString) { | |
int firstDigit = toDigit(hexString.charAt(0)); | |
int secondDigit = toDigit(hexString.charAt(1)); | |
return (byte) ((firstDigit << 4) + secondDigit); | |
} | |
private static int toDigit(char hexChar) { | |
int digit = Character.digit(hexChar, 16); | |
if(digit == -1) { | |
throw new IllegalArgumentException( | |
"Invalid Hexadecimal Character: "+ hexChar); | |
} | |
return digit; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment