RSA加密-在字节数组和字符串之间转换 [英] RSA encyrption - converting between bytes array and String

查看:89
本文介绍了RSA加密-在字节数组和字符串之间转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现能够执行以下操作的RSA加密:

I am trying to implement RSA encryption which is able to do the following:

  • 接受字符串值作为输入以使用公钥进行加密
  • 将加密密码返回为字符串
  • 接受加密密码作为输入以使用私钥解密
  • 返回解密后的原始值

如果我直接解密加密返回的 byte 数组,我就能使加密/解密工作,但是如果我解析 byte ,似乎也无法使加密/解密工作将code>数组转换为 String ,然后再次返回到 byte .

I am able to get the encryption/decryption working if I directly decrypt the byte array returned by the encryption, but annot seem to get it to work if I parse the byte array to a String and then back to bytes again.

以下代码有效:

The following code does work:

cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherBytes = cipher.doFinal(input);
System.out.println("cipher: " + new String(cipherBytes));
returnValue += new String(cipherBytes);

cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] plainText = cipher.doFinal(cipherBytes);
System.out.println("plain : " + new String(plainText));

以下代码不起作用:

byte[] cipherBytes = cipher.doFinal(input);
System.out.println("cipher: " + new String(cipherBytes));
returnValue += new String(cipherBytes);

String cipherText = new String(cipherBytes);
byte[] reCipherBytes = cipherText.getBytes();

cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] plainText = cipher.doFinal(reCipherBytes);
System.out.println("plain : " + new String(plainText));

任何人都可以建议我需要做些什么才能使第二个版本成功工作吗?

Can anyone advise what I'd need to do to get the second version to work successfully?

推荐答案

我认为您的问题是由于将字节数组转换为字符串时使用默认的Java编码/解码字符集,反之亦然.

I think your problem is because of the default java ecoding/deconding charset when converting a byte array to string and vice-versa.

我已经调试了您的代码,并且reCipherBytes的长度与cipherBytes的长度不同,这就是第二个代码块引发异常的原因.

I have debugged your code and reCipherBytes has not the same length as cipherBytes, that is why the second code blocks throws an exception.

我建议您使用base64编码将cipherBytes转换为字符串.

I recomend you to use base64 encoding for transforming cipherBytes into a string.

    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] cipherBytes = cipher.doFinal(input);
    System.out.println("cipher: " + new String(cipherBytes));
    String returnValue = new String(cipherBytes);

    String cipherText = Base64.getEncoder().encodeToString(cipherBytes);
    byte[] reCipherBytes = Base64.getDecoder().decode(cipherText);

    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    byte[] plainText = cipher.doFinal(reCipherBytes);
    System.out.println("plain : " + new String(plainText));

此代码片段应该起作用

这篇关于RSA加密-在字节数组和字符串之间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆