java - make string unreadable [closed]

与世无争的帅哥 提交于 2019-12-04 22:05:44

See encryption and decryption of data algorithgms with example code http://www.code2learn.com/2011/06/encryption-and-decryption-of-data-using.html. Encryption / decription is embedded in JRE and is not difficult to use.

Here is a very short example of using true encryption. It's 128 bit AES, which is farily secure - certainly not readable by any stretch of the imagination.

It generates a random key, so it would be different on each run. You would need to share they key between the two programs exchanging data somehow.

private static final String ENCRYPTION_ALGORITHM = "AES/ECB/PKCS5Padding";
private static final SecureRandom RANDOM = new SecureRandom();

public static void main(String[] args) throws UnsupportedEncodingException, GeneralSecurityException {
    final KeyGenerator keyGen = KeyGenerator.getInstance(ENCRYPTION_ALGORITHM.substring(0, ENCRYPTION_ALGORITHM.indexOf('/')));
    keyGen.init(128, RANDOM);
    final SecretKey key = keyGen.generateKey();
    final String s = "My topsecret string";
    System.out.println(s);
    final Cipher encryption = getCipher(key, Cipher.ENCRYPT_MODE);
    final String enc = DatatypeConverter.printBase64Binary(encryption.doFinal(s.getBytes("UTF-8")));
    System.out.println(enc);
    final Cipher decryption = getCipher(key, Cipher.DECRYPT_MODE);
    final String dec = new String(decryption.doFinal(DatatypeConverter.parseBase64Binary(enc)), "UTF-8");
    System.out.println(dec);
}

private static Cipher getCipher(final Key key, final int mode) throws GeneralSecurityException {
    final Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
    cipher.init(mode, key, RANDOM);
    return cipher;
}

Output:

My topsecret string
ip4La5KUBJGTTYenoE920V5w0VBHwALv4fp3qyLTY9o=
My topsecret string

What direction should I go, are there any classes that can do this for me? I don't mean something like Base68Encryption or whatever it might be called, I mean a true unreadable text that I can safely send over the internet.

There are two ways to address this:

  • You could pick one of the existing high quality encryption systems that is implemented as standard in a typical JVM. Then:

    1. Encode the string as bytes; e.g. using UTF-8.

    2. Encrypt the bytes using an agreed encryption system, and a previously agreed key.

    3. Encode the bytes using base_64 or equivalent.

    and at the other end:

    1. Decode the base_64

    2. Decrypt the bytes with the same system and key.

    3. Decode the UTF-8 to get a String.

  • Use SSL/TLS to secure the TCP/IP connection, and send the String over the connection as-is.

Neither of these options is particularly fast. But don't be tempted to try and invent your own faster encryption system. The chances are that a "home brewed" encryption system it will be a lot easier to break than you realize.

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