· 7 years ago · May 27, 2018, 05:06 AM
1import java.io.IOException;
2import java.security.GeneralSecurityException;
3
4import javax.crypto.Cipher;
5import javax.crypto.SecretKey;
6import javax.crypto.SecretKeyFactory;
7import javax.crypto.spec.PBEKeySpec;
8import javax.crypto.spec.PBEParameterSpec;
9
10import sun.misc.BASE64Decoder;
11import sun.misc.BASE64Encoder;
12
13public class ProtectedConfigFile {
14
15 private static final char[] PASSWORD = "enfldsgbnlsngdlksdsgm".toCharArray();
16 private static final byte[] SALT = {
17 (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,
18 (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,
19 };
20
21 public static void main(String[] args) throws Exception {
22 String originalPassword = "secret";
23 System.out.println("Original password: " + originalPassword);
24 String encryptedPassword = encrypt(originalPassword);
25 System.out.println("Encrypted password: " + encryptedPassword);
26 String decryptedPassword = decrypt(encryptedPassword);
27 System.out.println("Decrypted password: " + decryptedPassword);
28 }
29
30 private static String encrypt(String property) throws GeneralSecurityException {
31 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
32 SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
33 Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
34 pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
35 return base64Encode(pbeCipher.doFinal(property.getBytes()));
36 }
37
38 private static String base64Encode(byte[] bytes) {
39 // NB: This class is internal, and you probably should use another impl
40 return new BASE64Encoder().encode(bytes);
41 }
42
43 private static String decrypt(String property) throws GeneralSecurityException, IOException {
44 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
45 SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
46 Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
47 pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
48 return new String(pbeCipher.doFinal(base64Decode(property)));
49 }
50
51 private static byte[] base64Decode(String property) throws IOException {
52 // NB: This class is internal, and you probably should use another impl
53 return new BASE64Decoder().decodeBuffer(property);
54 }
55
56}