加密和解密字符串

时间:2015-02-16 23:08:58

标签: java encryption

我正在尝试使用两种方法:一种方法,我输入一个给定的字符串,然后我收到加密的字符串。第二个我输入加密的字符串,然后我收到原始字符串。因此,我希望两个方法都将String作为输入并返回一个String作为输出。

我目前正在使用:

   import javax.crypto.Cipher;
   import javax.crypto.BadPaddingException;
   import javax.crypto.IllegalBlockSizeException;
   import javax.crypto.KeyGenerator;
   import java.security.Key;
   import java.security.InvalidKeyException;

   public class CryptTest {

        private static String algorithm = "DESede";
        private static Key key = null;
        private static Cipher cipher = null;

        private static void setUp() throws Exception {
            key = KeyGenerator.getInstance(algorithm).generateKey();
            cipher = Cipher.getInstance(algorithm);
        }

        public static void main(String[] args) 
           throws Exception {
            setUp();

            byte[] encryptionBytes = null;
            String input = "something";
            System.out.println("Entered: " + input);
            encryptionBytes = encrypt(input);
            String encryptedInput =  encryptionBytes.toString();
            System.out.println("encrypted: " + encryptedInput);


            System.out.println(
              "Recovered: " + decrypt(encryptionBytes));
        }

        private static byte[] encrypt(String input)
            throws InvalidKeyException, 
                   BadPaddingException,
                   IllegalBlockSizeException {
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] inputBytes = input.getBytes();
            return cipher.doFinal(inputBytes);
        }

        private static String decrypt(byte[] encryptionBytes)
            throws InvalidKeyException, 
                   BadPaddingException,
                   IllegalBlockSizeException {
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] recoveredBytes = 
              cipher.doFinal(encryptionBytes);
            String recovered = 
              new String(recoveredBytes);
            return recovered;
          }
   }

目前,encrypt方法返回一个字节数组。我转换为字符串,所以我得到加密的表格。现在,当我想再次解密时,我想将其转换回字节数组。我尝试使用byte[] b = string.getBytes();,但我收到了与原始字符串不同的解密字符串。 为什么会这样?

0 个答案:

没有答案