· 7 years ago · Oct 12, 2018, 06:50 PM
1public void encrypt ()
2{
3 byte[] input = w.getSprites().toString().getBytes(); // Data to be encrypted
4 byte[] encrypted = null; // Encrypted output
5 Cipher cipher; // Cipher algorithm to be used
6
7 try {
8
9 // Setup the cipher algorithm to use and select the wanted mode
10 // AES is the cipher algorithm GCM is the mode
11 cipher = Cipher.getInstance("AES/GCM/NoPadding");
12
13 // Generate a random key for the encryption
14 KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
15 keyGenerator.init(256);
16 SecretKey key = keyGenerator.generateKey();
17
18 // Generate a random iv for the encryption
19 SecureRandom randomSecureRandom = new SecureRandom();
20 byte[] iv = new byte[cipher.getBlockSize()];
21 randomSecureRandom.nextBytes(iv);
22
23 // Encrypt the data
24 cipher.init(Cipher.ENCRYPT_MODE, key, randomSecureRandom);
25 encrypted = new byte[cipher.getOutputSize(input.length)];
26 int enc_len = cipher.update(input, 0, input.length, encrypted, 0);
27 enc_len += cipher.doFinal(encrypted, enc_len);
28 }
29 catch (NoSuchAlgorithmException |
30 NoSuchPaddingException |
31 InvalidKeyException |
32 ShortBufferException |
33 IllegalBlockSizeException |
34 BadPaddingException e) { e.printStackTrace(); }
35
36 FileHandle f = Gdx.files.local("bin/default/saves/default/test.txt");
37 f.writeString(encrypted.toString(), false);
38}