简体   繁体   English

Java Windows-1252错误字符

[英]Java Windows-1252 wrong chars

I'm coding a RSA algorithm to encrypt a string to send to a VisualBasic webservice. 我正在编码RSA算法以加密要发送到VisualBasic Web服务的字符串。 Unfortunatelly the VB RSAcryptoserviceprovider always gives me an exception "Bad data" and i this the problem is the encoding. 不幸的是,VB RSAcryptoserviceprovider总是给我一个异常“ Bad data”,这是编码的问题。 The VisualBasic code receives the string and converts it to a byte array using windows-1252 encoding and them decrypts it. VisualBasic代码接收字符串,并使用Windows-1252编码将其转换为字节数组,然后解密。

In my Java code i'm encrypting using this: 在我的Java代码中,我使用以下代码进行加密:

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 . 当我'system.out.print'加密的字符串时,它给我像 的奇怪字符。 Does it means that me windows-1252 encoding is wrong right? 这是否意味着Windows-1252编码错误对吗? What am i doing wrong here? 我在这里做错了什么? Note that i can only make changes to the Java code and not the VB. 请注意,我只能更改Java代码,不能更改VB。

Thank you! 谢谢!

You need to convert the ciphertext to base 64 encoding, and back to bytes before decrypting. 您需要将密文转换为base 64编码,然后再解密为字节,然后再解密。 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. 当数据丢失时,您将收到一个异常,指示密文的大小不正确,或者RSA加密中使用的填充无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM