0

Hello I build this 2 Methods the Encryption works fine but the Decryption get an error because cipher wants a byte and i want to encrypt from a String

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class Test {

    private byte[] encrypted;

    private String encryptedtext;
    private String decrypted;



    public String Encrypt (String pInput) {


      try {

         String Input = pInput;
         String key = "Bar12345Bar12345Bar12345Bar12345"; 

         // Erstelle key and cipher
         SecretKeySpec aesKey = new SecretKeySpec(key.getBytes(), "AES");
         Cipher cipher = Cipher.getInstance("AES");

         // Verschlüsselung
         cipher.init(Cipher.ENCRYPT_MODE, aesKey);
         byte[] encrypted = cipher.doFinal(Input.getBytes());
         encryptedtext = new String(encrypted);
         System.err.println("encrypted:" + encryptedtext);


      }catch(Exception e) {
         e.printStackTrace();
      }

        return encrypted;
    }



    public String Decrypt (String pInput) {


       try {

           String Input = pInput; 

           String key = "Bar12345Bar12345Bar12345Bar12345"; 

           // Erstelle key and cipher
           SecretKeySpec aesKey = new SecretKeySpec(key.getBytes(), "AES");
           Cipher cipher = Cipher.getInstance("AES");

           // Entschlüsselung
           cipher.init(Cipher.DECRYPT_MODE, aesKey);
           decrypted = new String(cipher.doFinal(encryptedtext)); // HERE IS THE PROBLEM IT WANT BYTE BUT I WANT TO ENCRYPT FROM A STRING
           System.err.println("decrypted: " + decrypted);

        }catch(Exception e) {
           e.printStackTrace();
        }
        return pInput;
      }

}
user253751
  • 57,427
  • 7
  • 48
  • 90
hanso
  • 11
  • 1
  • 1
  • 1
  • 2
    Encryption also uses bytes. So how did you solve it for encryption? – user253751 Jul 26 '14 at 07:01
  • yes i know but the bytes are converted into a String so i can use it and print it out but the problem is when i use the decryption it want the byte session from the encryption. But i want to give this mehtod a string and it store the decryptet text into a string to display the decrpyted value. I want to use this methods indipended in this version i must encrypt and decrypt and it will be work but i want to use decrypt without encrypting something before – hanso Jul 26 '14 at 07:07
  • Cipher encrypts bytes and returns bytes. But you are encrypting strings. So how did you convert a string into bytes before encrypting it? – user253751 Jul 26 '14 at 07:11
  • 3
    By the way, converting the encrypt*ed* bytes to a string is *WRONG* and can corrupt the data. If you keep doing this, you will eventually encrypt something and not be able to decrypt it again. – user253751 Jul 26 '14 at 07:12
  • please edit my code and make it i would like to see a code example :) – hanso Jul 26 '14 at 07:19
  • Take a look at [this answer of mine](http://stackoverflow.com/a/8828196/589259) if you want to go with strings all the way. You are currently using ECB mode of operation, which is unsafe for strings. – Maarten Bodewes Jul 26 '14 at 13:35

2 Answers2

4

Byte array cannot directly convert to string, and neither do the reverse direction.

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

public class stackoverflow_test {
    private byte[] encrypted;

    private String encryptedtext;
    private String decrypted;

    public String Encrypt(String pInput) {

        try {

            String Input = pInput;
            String key = "Bar12345Bar12345Bar12345Bar12345";

            SecretKeySpec aesKey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");

            cipher.init(Cipher.ENCRYPT_MODE, aesKey);
            byte[] encrypted = cipher.doFinal(Input.getBytes());
            //encryptedtext = new String(encrypted);
            encryptedtext = DatatypeConverter.printBase64Binary(encrypted);
            System.err.println("encrypted:" + encryptedtext);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return encryptedtext;
    }

    public String Decrypt(String pInput) {

        try {

            String Input = pInput;

            String key = "Bar12345Bar12345Bar12345Bar12345";

            SecretKeySpec aesKey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");

            cipher.init(Cipher.DECRYPT_MODE, aesKey);
            encrypted = DatatypeConverter.parseBase64Binary(encryptedtext);
            decrypted = new String(cipher.doFinal(encrypted)); 
            System.err.println("decrypted: " + decrypted);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return pInput;
    }

    public static void main(String[] ag){
        stackoverflow_test test = new stackoverflow_test();
        String a = test.Encrypt("Byte cannot directly convert to string");
        String b = test.Decrypt(a);
    }
}

Result

encrypted:UmH+3eUagjrRDblxSStArnaktoxTLX+7qvPdwiTO7VggYmYtuXu/Ygww8ZG5SrDz
decrypted: Byte cannot directly convert to string
tom87416
  • 542
  • 4
  • 9
  • Thank you :) but is it possible to dont use Base64 in this Code because Android get some Problems with Base64 :/ – hanso Jul 26 '14 at 07:30
  • this can help you, turn it into String of hexadecimal http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java – tom87416 Jul 26 '14 at 07:39
  • then you must have design it in wrong way. What is the string you going to create to be the parameter of the decrypt function? You can read byte[] from file, from network socket, no need to be a String unless some alien can input xff in command prompt. XD – tom87416 Jul 26 '14 at 07:45
  • No :/ look if you make the Encryption and then the Decryption Everything works but if you just wanna use the Decryption "Only" it doesent go on it gives me erros... – hanso Jul 26 '14 at 07:50
  • @tom87416: This is a pretty good answer but you should change one thing to make it portable. Change `Input.getBytes()` to `Input.getBytes("UTF-8");` in Encrypt and change `new String(cipher.doFinal(encrypted));` to `new String(cipher.doFinal(encrypted), "UTF-8");`. You need to do this because the default charsets may be different on different platforms and thus if, for example, you encrypt on a PC and decrypt on Android you might get the wrong answer. – President James K. Polk Jul 26 '14 at 11:11
  • @hanso: Are you saying you can't change the broken encryption code? – President James K. Polk Jul 26 '14 at 11:14
  • @hanso You didn't indicate Android anywhere. Besides, Android does have base 64 functionality in the main API. Is there any particular problem you are referring to in your first comment? – Maarten Bodewes Jul 26 '14 at 13:33
  • I cant use the Decryption only! i must use the encryption before to get this code working and thats not the solution i want – hanso Jul 26 '14 at 20:20
1

You can use Cipher to encrypt and decrypt a String.

public class CryptUtil {
    private static final String ALGORITHM = "Blowfish";
    private static final String MODE = "Blowfish/CBC/PKCS5Padding";
    private static final String IV = "abcdefgh";

    public static  String encrypt(String secretKey, String value ) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(MODE);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(IV.getBytes()));
        byte[] values = cipher.doFinal(value.getBytes());
        return Base64.encodeToString(values, Base64.DEFAULT);
    }

    public static  String decrypt(String secretKey, String value) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        byte[] values = Base64.decode(value, Base64.DEFAULT);
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(MODE);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(IV.getBytes()));
        return new String(cipher.doFinal(values));
    }
}
taylorthurlow
  • 2,953
  • 3
  • 28
  • 42
Farid Haq
  • 3,728
  • 1
  • 21
  • 15