1
votes

I am encrypting a string using AES and want to decrypt it on other pc. The encryption and decryption works if i execute on the same pc. But for decryption on other pc my encryption algo is generating a "Cipher cipher" which is needed for decryption on other side along with the key. I am not sure how do I transfer the cipher to the other side.

here is my code

 public class AESCrypt {

    static String plainText;
    static byte[] plainBytesDecrypted = new byte[1024];
    static byte[] cipherBytes = new byte[1024];
    static SecretKey key;
    static Cipher cipher;

    public AESCrypt() throws NoSuchAlgorithmException {
        KeyGenerator generator = KeyGenerator.getInstance("AES");

        generator.init(128);
        key = generator.generateKey();

    }

    public static byte[] encryption(String plainBytes) {

        try {
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            cipherBytes = cipher.doFinal(plainBytes.getBytes());
            System.out.println("Encrypted data : " + new String(cipherBytes));

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return cipherBytes;
    }

    private static String bytesToHex(byte[] hash) {

        return DatatypeConverter.printHexBinary(hash);

    }

    public static String Decryption() throws InvalidKeyException, IllegalBlockSizeException, InvalidAlgorithmParameterException, BadPaddingException {

        cipher.init(Cipher.DECRYPT_MODE, key, cipher.getParameters());
        plainBytesDecrypted = cipher.doFinal(cipherBytes);

        System.out.println("Decrypted data : " + new String(plainBytesDecrypted));

        return (new String(plainBytesDecrypted));
    }
}
1
Have you heard of Public-key cryptography? - Artjom B.

1 Answers

0
votes

You have 3 choices in general:

  • Hardcode the cipher/mode/padding, so that both sides are aware you're always using the same format.
  • Send the cipher/mode/padding before the secret messages, so the other side knows what cipher to initialise.
  • Use an existing protocol, which already includes all those things for you and does it securely. You can send your data inside of TLS connection, for example.