How to encrypt String in Java

后端 未结 16 1410
梦毁少年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:20

    Warning

    Do not use this as some kind of security measurement.

    The encryption mechanism in this post is a One-time pad, which means that the secret key can be easily recovered by an attacker using 2 encrypted messages. XOR 2 encrypted messages and you get the key. That simple!

    Pointed out by Moussa


    I am using Sun's Base64Encoder/Decoder which is to be found in Sun's JRE, to avoid yet another JAR in lib. That's dangerous from point of using OpenJDK or some other's JRE. Besides that, is there another reason I should consider using Apache commons lib with Encoder/Decoder?

    public class EncryptUtils {
        public static final String DEFAULT_ENCODING = "UTF-8"; 
        static BASE64Encoder enc = new BASE64Encoder();
        static BASE64Decoder dec = new BASE64Decoder();
    
        public static String base64encode(String text) {
            try {
                return enc.encode(text.getBytes(DEFAULT_ENCODING));
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        }//base64encode
    
        public static String base64decode(String text) {
            try {
                return new String(dec.decodeBuffer(text), DEFAULT_ENCODING);
            } catch (IOException e) {
                return null;
            }
        }//base64decode
    
        public static void main(String[] args) {
            String txt = "some text to be encrypted";
            String key = "key phrase used for XOR-ing";
            System.out.println(txt + " XOR-ed to: " + (txt = xorMessage(txt, key)));
    
            String encoded = base64encode(txt);       
            System.out.println(" is encoded to: " + encoded + " and that is decoding to: " + (txt = base64decode(encoded)));
            System.out.print("XOR-ing back to original: " + xorMessage(txt, key));
        }
    
        public static String xorMessage(String message, String key) {
            try {
                if (message == null || key == null) return null;
    
                char[] keys = key.toCharArray();
                char[] mesg = message.toCharArray();
    
                int ml = mesg.length;
                int kl = keys.length;
                char[] newmsg = new char[ml];
    
                for (int i = 0; i < ml; i++) {
                    newmsg[i] = (char)(mesg[i] ^ keys[i % kl]);
                }//for i
    
                return new String(newmsg);
            } catch (Exception e) {
                return null;
            }
        }//xorMessage
    }//class
    

提交回复
热议问题