How to encrypt String in Java

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

    Here are some links you can read what Java supports

    Encrypting/decrypting a data stream.

    This example demonstrates how to encrypt (using a symmetric encryption algorithm such as AES, Blowfish, RC2, 3DES, etc) a large amount of data. The data is passed in chunks to one of the encrypt methods: EncryptBytes, EncryptString, EncryptBytesENC, or EncryptStringENC. (The method name indicates the type of input (string or byte array) and the return type (encoded string or byte array). The FirstChunk and LastChunk properties are used to indicate whether a chunk is the first, middle, or last in a stream to be encrypted. By default, both FirstChunk and LastChunk equal true -- meaning that the data passed is the entire amount.

    JCERefGuide

    Java Encryption Examples

    0 讨论(0)
  • 2020-11-22 10:13
    String s1="arshad"; 
    char[] s2=s1.toCharArray(); 
    int s3= s2.length; 
    
      System.out.println(s3);
     int i=0; 
    
    // for(int j=0;j<s3;j++) 
    // System.out.println(s2[j]); 
    
    for(i=0;i<((s3)/2);i++) { 
    
    char z,f=10; 
    z=(char) (s2[i] * f); 
    s2[i]=s2[(s3-1)-i]; 
    s2[(s3-1)-i]=z; 
    
    String b=new String(s2);
    
     print(b);  }
    
    0 讨论(0)
  • 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!"));
    
        }
    }
    
    0 讨论(0)
  • 2020-11-22 10:16

    thanks ive made this class using your code maybe someone finds it userfull

    object crypter

    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.security.InvalidAlgorithmParameterException;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.ShortBufferException;
    import javax.crypto.spec.DESKeySpec;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    
    
    public class ObjectCrypter {
    
    private Cipher deCipher;
    private Cipher enCipher;
    private SecretKeySpec key;
    private IvParameterSpec ivSpec;
    
    
    public ObjectCrypter(byte[] keyBytes,   byte[] ivBytes) {
        // wrap key data in Key/IV specs to pass to cipher
    
    
         ivSpec = new IvParameterSpec(ivBytes);
        // create the cipher with the algorithm you choose
        // see javadoc for Cipher class for more info, e.g.
        try {
             DESKeySpec dkey = new  DESKeySpec(keyBytes);
              key = new SecretKeySpec(dkey.getKey(), "DES");
             deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
             enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public byte[] encrypt(Object obj) throws InvalidKeyException, InvalidAlgorithmParameterException, IOException, IllegalBlockSizeException, ShortBufferException, BadPaddingException {
        byte[] input = convertToByteArray(obj);
        enCipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
    
        return enCipher.doFinal(input);
    
    
    
    
    //  cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
    //  byte[] encypted = new byte[cipher.getOutputSize(input.length)];
    //  int enc_len = cipher.update(input, 0, input.length, encypted, 0);
    //  enc_len += cipher.doFinal(encypted, enc_len);
    //  return encypted;
    
    
    }
    public Object decrypt( byte[]  encrypted) throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException, ClassNotFoundException {
        deCipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
    
        return convertFromByteArray(deCipher.doFinal(encrypted));
    
    }
    
    
    
    private Object convertFromByteArray(byte[] byteObject) throws IOException,
            ClassNotFoundException {
        ByteArrayInputStream bais;
    
        ObjectInputStream in;
        bais = new ByteArrayInputStream(byteObject);
        in = new ObjectInputStream(bais);
        Object o = in.readObject();
        in.close();
        return o;
    
    }
    
    
    
    private byte[] convertToByteArray(Object complexObject) throws IOException {
        ByteArrayOutputStream baos;
    
        ObjectOutputStream out;
    
        baos = new ByteArrayOutputStream();
    
        out = new ObjectOutputStream(baos);
    
        out.writeObject(complexObject);
    
        out.close();
    
        return baos.toByteArray();
    
    }
    
    
    }
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 10:22

    How about this:

    private static byte[] xor(final byte[] input, final byte[] secret) {
        final byte[] output = new byte[input.length];
        if (secret.length == 0) {
            throw new IllegalArgumentException("empty security key");
        }
        int spos = 0;
        for (int pos = 0; pos < input.length; ++pos) {
            output[pos] = (byte) (input[pos] ^ secret[spos]);
            ++spos;
            if (spos >= secret.length) {
                spos = 0;
            }
        }
        return output;
    }
    

    Works fine for me and is rather compact.

    0 讨论(0)
提交回复
热议问题