Last active
September 26, 2023 06:25
-
-
Save keyganker/aed5d04a8f3fe305e049c74d5737fd1d to your computer and use it in GitHub Desktop.
mysql aes_encrypt/aes_decrypt加解密函数java实现 #java
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 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