Encryption with AES algorithm in Java

梦想与她 提交于 2019-12-21 06:41:40

问题


I made a packet p, with some integers and boolean values. The packet is as follows:

TCPPacket p=new TCPPacket(481,516,23,42,true,false,false,false,false,false,false,false,10,10);

How can I encrypt the packet with AES, in Java?


回答1:


I suggest you read through the tutorial Using AES with Java Technology from Oracle.

(First hit on Google btw.)




回答2:


This is some sample code that should get you started. It uses AES (128) to crypt and decrypt an object (using SealedObject).

public class App {

    public static void main(String[] args) throws Exception {
        TCPPacket packet = new TCPPacket(481, 516, 23, 42, true, false, false, false, false, false, false, false, 10, 10);

        final char[] password = "secretpass".toCharArray();
        final byte[] salt = "a9v5n38s".getBytes();

        // Create key
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(password, salt, 1024, 128);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        // Init ciphers
        Cipher cipher = Cipher.getInstance("AES");
        Cipher dcipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secret);
        dcipher.init(Cipher.DECRYPT_MODE, secret);

        // Encrypt packet
        SealedObject so = new SealedObject(packet, cipher);

        // Decrypt packet
        TCPPacket decryptedPacket = (TCPPacket) so.getObject(dcipher);

        System.out.println(decryptedPacket.first);
    }

    private static class TCPPacket implements Serializable {
        private int first;
        public TCPPacket(final int _first, final int i1, final int i2, final int i3, final boolean b, final boolean b1,
                         final boolean b2, final boolean b3, final boolean b4, final boolean b5, final boolean b6,
                         final boolean b7, final int i4, final int i5) {

            first = _first;
        }
        public int getFirst() {
            return first;
        }

    }
}


来源:https://stackoverflow.com/questions/6262374/encryption-with-aes-algorithm-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!