How to encrypt String in Java

后端 未结 16 1511
梦毁少年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条回答
  •  猫巷女王i
    2020-11-22 10:03

    I'd recommend to use some standard symmetric cypher that is widely available like DES, 3DES or AES. While that is not the most secure algorithm, there are loads of implementations and you'd just need to give the key to anyone that is supposed to decrypt the information in the barcode. javax.crypto.Cipher is what you want to work with here.

    Let's assume the bytes to encrypt are in

    byte[] input;
    

    Next, you'll need the key and initialization vector bytes

    byte[] keyBytes;
    byte[] ivBytes;
    

    Now you can initialize the Cipher for the algorithm that you select:

    // wrap key data in Key/IV specs to pass to cipher
    SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
    IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
    // create the cipher with the algorithm you choose
    // see javadoc for Cipher class for more info, e.g.
    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    

    Encryption would go like this:

    cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
    byte[] encrypted= new byte[cipher.getOutputSize(input.length)];
    int enc_len = cipher.update(input, 0, input.length, encrypted, 0);
    enc_len += cipher.doFinal(encrypted, enc_len);
    

    And decryption like this:

    cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
    byte[] decrypted = new byte[cipher.getOutputSize(enc_len)];
    int dec_len = cipher.update(encrypted, 0, enc_len, decrypted, 0);
    dec_len += cipher.doFinal(decrypted, dec_len);
    

提交回复
热议问题