Skip to content

Instantly share code, notes, and snippets.

@AnanthaRajuC
Forked from keyganker/MysqlAESDecrypt.java
Created April 18, 2022 12:33
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 AnanthaRajuC/a436c46a34f143207d5d2a1a47ef9733 to your computer and use it in GitHub Desktop.
Save AnanthaRajuC/a436c46a34f143207d5d2a1a47ef9733 to your computer and use it in GitHub Desktop.
mysql aes_encrypt/aes_decrypt加解密函数java实现
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
//mysql源码中对加密key的生成实现 https://github.com/mysql/mysql-server/blob/8.0/mysys_ssl/my_aes.cc
//参考博文:https://info.michael-simons.eu/2011/07/18/mysql-compatible-aes-encryption-decryption-in-java/
//参考2:https://www.example-code.com/java/mysql_aes_encrypt.asp
public class MysqlAESDecrypt {
public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, DecoderException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {
final Cipher decryptCipher = Cipher.getInstance("AES");
decryptCipher.init(Cipher.DECRYPT_MODE, generateMySQLAESKey("十六进制encode key", "UTF-8"));
System.out.println(new String(decryptCipher.doFinal(Hex.decodeHex("密文".toCharArray()))));
// Encrypt
// final Cipher encryptCipher = Cipher.getInstance("AES");
// encryptCipher.init(Cipher.ENCRYPT_MODE, generateMySQLAESKey("your super secret passphrase", "UTF-8"));
// System.out.println(String.format("Select aes_decrypt(unhex('%s'), 'your super secret passphrase');", new String(Hex.encodeHex(encryptCipher.doFinal("Hallo nach Aachen".getBytes("UTF-8"))))));
}
public static SecretKeySpec generateMySQLAESKey(final String key, final String encoding) throws DecoderException {
final byte[] finalKey = new byte[16];
int i = 0;
for(byte b : Hex.decodeHex(key))
finalKey[i++%16] ^= b;
return new SecretKeySpec(finalKey, "AES");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment