Java自带 AES/OFB/NoPadding 加解密

Java自带 AES/OFB/NoPadding 加解密



import lombok.SneakyThrows;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public final class SecurityCodec {

    private static final byte[] key = new byte[]{
            0x2F, 0x0A, 0x17, 0x69, 0x0B, 0x27, 0x03, 0x48,
            0x1E, 0x39, 0x29, 0x57, 0x0C, 0x44, 0x2B, 0x39};

    private static final SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
    private static final IvParameterSpec ivParameterSpec = new IvParameterSpec(key);

    @SneakyThrows
    public static byte[] encryptMessage(byte[] plainText) {
        Cipher cipher = Cipher.getInstance("AES/OFB/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        return cipher.doFinal(plainText);
    }

    @SneakyThrows
    public static byte[] decryptMessage(byte[] encryptText) {
        Cipher cipher = Cipher.getInstance("AES/OFB/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        return cipher.doFinal(encryptText);
    }

    private SecurityCodec() {
    }

    public static void main(String[] args) {
        try {
            String testByte = "{\"gameId\": 11,\"userId\": 8526,\"roomId\": 7}";
            byte[] testEncrypt = encryptMessage(testByte.getBytes());
            String testDecrypt = new String(decryptMessage(testEncrypt), StandardCharsets.UTF_8);
            System.out.println(testDecrypt);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


你可能感兴趣的:(Java自带 AES/OFB/NoPadding 加解密)