与java的rsa_Android和Java中的RSA加密

我想用RSA加密对String进行加密。我的公钥/私钥已生成并存储在DB中。在android中,我使用以下代码:

public static String encryptRSAToString(String text, String strPublicKey) {

byte[] cipherText = null;

String strEncryInfoData="";

try {

KeyFactory keyFac = KeyFactory.getInstance("RSA");

KeySpec keySpec = new X509EncodedKeySpec(Base64.decode(strPublicKey.trim().getBytes(), Base64.DEFAULT));

Key publicKey = keyFac.generatePublic(keySpec);

// get an RSA cipher object and print the provider

final Cipher cipher = Cipher.getInstance("RSA");

// encrypt the plain text using the public key

cipher.init(Cipher.ENCRYPT_MODE, publicKey);

cipherText = cipher.doFinal(text.getBytes());

strEncryInfoData = new String(Base64.encode(cipherText,Base64.DEFAULT));

} catch (Exception e) {

e.printStackTrace();

}

return strEncryInfoData.replaceAll("(\\r|\\n)", "");

}

出于调试目的,我尝试使用相同的参数调用此方法两次,并且String结果相似(符合预期)。

我想在Java中生成相同的加密字符串。但是,“ android.util.Base64”类在Java中不可用,因此我尝试使用默认的Base64类:

public static String encryptRSAToString(String text, String strPublicKey) {

byte[] cipherText = null;

String strEncryInfoData="";

try {

KeyFactory keyFac = KeyFactory.getInstance("RSA");

KeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(strPublicKey.trim().getBytes()));

Key publicKey = keyFac.generatePublic(keySpec);

// get an RSA cipher object and print the provider

final Cipher cipher = Cipher.getInstance("RSA");

// encrypt the plain text using the public key

cipher.init(Cipher.ENCRYPT_MODE, publicKey);

cipherText = cipher.doFinal(text.getBytes());

strEncryInfoData = new String(Base64.encodeBase64(cipherText));

} catch (Exception e) {

e.printStackTrace();

}

return strEncryInfoData.replaceAll("(\\r|\\n)", "");

}

但是Android中生成的String和Java中生成的String是不同的。

在Android端产生:

Ky2T4j1JdI081ZESVJgxZXEf/xmtpehfv/EwpVvKQxUu1JI8lwXP2Rc66jHZRc0P846ZYuF3C9YEmWoKbXGXk2MBuT5KVxa2yoTbwZlMmhVOX3X3Efq0VyaO5zZ4qavIq036cA3MzvQbUAb678UdbALW/CjRCsOdeH+hSCzNQ+0=

在JAVA端生成:

XhSLxfiJUUdZW5kWh0MEPSrqoROBBhNC/krfTx+sdnXML3WegYbMzSvNnPgB8+8Z9joEUBMmoeBI1OhTF6qPFL1EEixkFYAkGaryEFxvN/aFI75kEUj71OHNzAHAuvS+h+9Nssx9psSZ5gc2OoLQH0QtbGDyXB4p+qUGFCde4tY=

有人知道如何解决我的问题吗?

谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值