How to encrypt String in Java

后端 未结 16 1234
梦毁少年i
梦毁少年i 2020-11-22 09:58

What I need is to encrypt string which will show up in 2D barcode(PDF-417) so when someone get an idea to scan it will get nothing readable.

Other requirements:

16条回答
  •  囚心锁ツ
    2020-11-22 10:15

    Like many of the guys have already told, you should use a standard cypher that is overly used like DES or AES.

    A simple example of how you can encrypt and decrypt a string in java using AES.

    import org.apache.commons.codec.binary.Base64;
    
    import javax.crypto.Cipher;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    
    public class EncryptorDemo {
    
        public static String encrypt(String key, String randomVector, String value) {
            try {
                IvParameterSpec iv = new IvParameterSpec(randomVector.getBytes("UTF-8"));
                SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
                byte[] encrypted = cipher.doFinal(value.getBytes());
                System.out.println("encrypted text: "  + Base64.encodeBase64String(encrypted));
                return Base64.encodeBase64String(encrypted);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    
        public static String decrypt(String key, String randomVector, String encrypted) {
            try {
                IvParameterSpec iv = new IvParameterSpec(randomVector.getBytes("UTF-8"));
                SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
                cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
                byte[] originalText = cipher.doFinal(Base64.decodeBase64(encrypted));
                System.out.println("decrypted text: "  + new String(originalText));
                return new String(originalText);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    
        public static void main(String[] args) {
            String key = "JavasEncryptDemo"; // 128 bit key
            String randomVector = "RandomJavaVector"; // 16 bytes IV
            decrypt(key, randomVector, encrypt(key, randomVector, "Anything you want to encrypt!"));
    
        }
    }
    

提交回复
热议问题