· 6 years ago · Mar 17, 2019, 03:40 AM
1String[] data; // the data you want to save
2int byteLength = 0;
3byte[][] bytes = new byte[data.length][];
4
5// Calculate the length of the content.
6for(int i=0; i<data.length; i++) {
7 bytes[i] = data[i].getBytes();
8 byteLength += bytes[i].length;
9 byteLength += 4; // this is for an integer, which is for the length of the String
10}
11
12// Transfer the content to a ByteBuffer object
13ByteBuffer buffer = ByteBuffer.allocate(byteLength);
14for(int i=0; i<bytes.length; i++) {
15 // Put the length of the current byte array
16 buffer.putInt(bytes[i].length);
17 for(int j=0; j<bytes[i].length; j++) {
18 // Reverse the byte so that it can't be understood
19 buffer.put((byte)(~bytes[i][j]));
20 }
21}
22
23FileOutputStream fos = new FileOutputStream("YourFileName.anyExtension");
24fos.write(buffer.array());
25fos.close();
26
27FileInputStream fis = new FileInputStream("YourFileName.anyExtension");
28DataInputStream dis = new DataInputStream(fis);
29ArrayList<String> list = new ArrayList<String>();
30byte[] bytes;
31while(dis.available()) {
32 int length = dis.readInt();
33 bytes = new byte[length];
34 for(int i=0; i<length; i++) {
35 // Those bytes were reversed, right?
36 bytes[i] = (byte)(~dis.readByte());
37 }
38 // Convert byte array to String
39 String str = new String(bytes);
40 list.add(str);
41}
42
43byte password[] = (WHAT YOUR WANT. STRING, NUMBER, etc.).getBytes();
44 DESKeySpec desKeySpec;
45 try {
46
47 desKeySpec = new DESKeySpec(password);
48 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
49 SecretKey key = keyFactory.generateSecret(desKeySpec);
50
51 Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
52 desCipher.init(Cipher.ENCRYPT_MODE, key);
53
54 // Create stream
55 FileOutputStream fos = new FileOutputStream("Your file here");
56 BufferedOutputStream bos = new BufferedOutputStream(fos);
57 CipherOutputStream cos = new CipherOutputStream(bos, desCipher);
58 }
59
60SecretKey key = loadKey(); // Deserialize your SecretKey object
61try {
62 Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
63 cipher.init(Cipher.DECRYPT_MODE, key);
64 FileInputStream fis = new FileInputStream("Your file here");
65 BufferedInputStream bis = new BufferedInputStream(fis);
66 CipherInputStream cis = new CipherInputStream(bis, cipher);