Created
March 30, 2021 03:39
-
-
Save kinginblue/78808496858dfcadcb91f26876620618 to your computer and use it in GitHub Desktop.
Java AES 256 CBC PKCS7 Demo
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; | |
import java.nio.charset.StandardCharsets; | |
import java.security.spec.AlgorithmParameterSpec; | |
import java.util.Base64; | |
public class JavaAes256CbcPkcs7Demo { | |
private static final byte[] keys = new byte[]{0x2e, 0x59, 0x46, (byte) 0x93, 0x2e, (byte) 0xf2, (byte) 0x8b, (byte) 0xed, (byte) 0xcf, (byte) 0xb3, (byte) 0xc4, (byte) 0xda, (byte) 0xc2, 0x53, (byte) 0xe8, (byte) 0xbd, 0x1a, 0x33, 0x17, (byte) 0xf3, 0x35, (byte) 0xca, 0x24, 0x40, (byte) 0xa5, 0x6c, 0x5f, 0x11, 0x11, (byte) 0xfa, 0x2e, 0x1b}; | |
private static final byte[] ivs = new byte[]{(byte) 0xfa, 0x7a, (byte) 0xeb, (byte) 0xcf, 0x29, 0x71, (byte) 0x8d, 0x7b, 0x5a, 0x67, (byte) 0xe4, 0x1d, 0x5c, (byte) 0x8f, 0x79, (byte) 0xa3}; | |
public static void main(String[] args) { | |
System.out.println(encrypt("abcd123!")); | |
System.out.println(decrypt("HAXyVME3JVLYSzivsHDMHA==")); | |
} | |
// 加密 | |
public static String encrypt(String strToEncrypt) { | |
try { | |
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); | |
SecretKeySpec secretKeySpec = new SecretKeySpec(keys, "AES"); | |
AlgorithmParameterSpec paramSpec = new IvParameterSpec(ivs); | |
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, paramSpec); | |
return Base64.getEncoder() | |
.encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8))); | |
} catch (Exception e) { | |
System.out.println("Error while encrypting: " + e.toString()); | |
} | |
return null; | |
} | |
// 解密 | |
public static String decrypt(String strToDecrypt) { | |
try { | |
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); | |
SecretKeySpec secretKeySpec = new SecretKeySpec(keys, "AES"); | |
AlgorithmParameterSpec paramSpec = new IvParameterSpec(ivs); | |
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, paramSpec); | |
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt))); | |
} catch (Exception e) { | |
System.out.println("Error while decrypting: " + e.toString()); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment