美文网首页
Java自带 AES/OFB/NoPadding 加解密

Java自带 AES/OFB/NoPadding 加解密

作者: Uning | 来源:发表于2020-12-07 17:40 被阅读0次

    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 加解密

          本文链接:https://www.haomeiwen.com/subject/vlutgktx.html