Search code examples
javavb.netencryptioncharacter-encodingwindows-1252

Java Windows-1252 wrong chars


I'm coding a RSA algorithm to encrypt a string to send to a VisualBasic webservice. Unfortunatelly the VB RSAcryptoserviceprovider always gives me an exception "Bad data" and i this the problem is the encoding. The VisualBasic code receives the string and converts it to a byte array using windows-1252 encoding and them decrypts it.

In my Java code i'm encrypting using this:

private static String encryptBlock(Cipher cipher, String textToEncrypt) {
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    String encrypted = new String(cipher.doFinal(textToEncrypt.getBytes(Charset.defaultCharset())), "windows-1252");
    return encrypted;
}

When i 'system.out.print' the encrypted string it gives me strange chars like �. Does it means that me windows-1252 encoding is wrong right? What am i doing wrong here? Note that i can only make changes to the Java code and not the VB.

Thank you!


Solution

  • You need to convert the ciphertext to base 64 encoding, and back to bytes before decrypting. Either that or you need to keep treating the ciphertext as binary.

    There are no character encodings that will use every possible random byte value as printable character. So using just the default character encoding as you do now is going to lead to data loss.

    When data is lost you will get an exception indicating that the size of the ciphertext is incorrect, or that the padding used within the RSA encryption is invalid.