如何在服务器和GWT客户端之间使用RSA?

3
我想在Java服务器后端和GWT客户端之间加密数据。在GWT客户端上,我使用sbn.js库。它的运行速度非常快,比gwt-crypto快得多。
这是我在客户端加密时使用RSA的(e,n)的方法。 我创建了一个JSFiddle
var n = "BC86E3DC782C446EE756B874ACECF2A115E613021EAF1ED5EF295BEC2BED899D26FE2EC896BF9DE84FE381AF67A7B7CBB48D85235E72AB595ABF8FE840D5F8DB";

var e = "3";
var d = "7daf4292fac82d9f44e47af87348a1c0b9440cac1474bf394a1b929d729e5bbcf402f29a9300e11b478c091f7e5dacd3f8edae2effe3164d7e0eeada87ee817b";

function do_encrypt() {
    var before = new Date();
    var rsa = new RSAKey();
    rsa.setPublic(n, e);
    var res = rsa.encrypt($("#plaintext").val());

    $("#ciphertext").val(res);
    $("#cipherb64").val(hex2b64(res));
    console.log("res");



}

$("#encrypt").click(function () {
    do_encrypt();
});

我在服务器上使用加密后的明文的十六进制表示进行解密。

以下是我在服务器上解密的方法:

我使用以下库:

compile 'org.bouncycastle:bcprov-jdk15on:1.51'
compile 'org.bouncycastle:bcprov-ext-jdk15on:1.51'

以下是我如何在服务器上使用RSA的(d,n)进行解密的方法:
    try {
        BigInteger modulus = new BigInteger("BC86E3DC782C446EE756B874ACECF2A115E613021EAF1ED5EF295BEC2BED899D26FE2EC896BF9DE84FE381AF67A7B7CBB48D85235E72AB595ABF8FE840D5F8DB",16);
        BigInteger exponent = new BigInteger("3");
        RSAKeyParameters publicKey = new RSAKeyParameters(false, modulus, exponent)

        BigInteger exponent2 = new BigInteger("7daf4292fac82d9f44e47af87348a1c0b9440cac1474bf394a1b929d729e5bbcf402f29a9300e11b478c091f7e5dacd3f8edae2effe3164d7e0eeada87ee817b", 16);
        RSAKeyParameters privateKey = new RSAKeyParameters(true, modulus, exponent2)

        String encryptedData = "a7f7d5c77c246729141cdfcc77f1f7b38d5f8066b0bc53b2e85119f3f1784f43be2140b5c382ad483bb57cc1b586962cbb1e831e6070a27e4880bbc549e20a372571d09c6b1269ddd7288916f10c96a9138f4165569c4767bfb489de2d44b450ed1495c99da985dc264dabadd9709ccd950ae55095373ccbc3344a26b3efd2dc";

        ////// decrypt
        AsymmetricBlockCipher d = new RSAEngine();
        d = new PKCS1Encoding(d);
        d.init(false, privateKey);

        byte[] messageBytes2 = new BigInteger(encryptedData,16).toByteArray();
        byte[] hexEncodedCipher2 = d.processBlock(messageBytes2, 0, messageBytes2.length); 


        println("encrypted:"+new String(hexEncodedCipher2));

    }
    catch(Exception e) {
        e.printStackTrace()
        println "#################### error"
    }

我遇到了以下异常:

Error |
org.bouncycastle.crypto.DataLengthException: input too large for RSA cipher.

我认为问题在于这一行:println("encrypted:"+new String(hexEncodedCipher2));

  1. 客户端如何解密?

  2. 为什么我使用相同的(e,n)和明文,在客户端加密多次后每次得到的密文都不同?


3
1)你的密码似乎太大了,它不应该比你的模数还要大。 2)这就是它应该工作的方式,RSA加密使用一些随机填充,因此每个加密(即使是相同的明文)都会不同。另外,你只应该使用bcprov-jdk15on库,-ext版本几乎相同,只是它包括一些你不需要的旧密码(比如IDEA)。 - President James K. Polk
@GregS,你能否帮我纠正一下我的代码示例。 - Michael
RSA(以及任何公钥方案)广泛用于加密将用于加密大量数据的对称密钥。对称密码比公钥密码快得多。混合方案是一个好选择。https://dev59.com/7HVD5IYBdhLWcg3wAWoO - philippe lhardy
1个回答

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接