Javascript 无法识别 RSAkey(),即使包含 js

Javascript not recognising RSAkey() even though js is included

本文关键字:包含 js 识别 RSAkey Javascript      更新时间:2023-09-26

我尝试在javascript中进行RSA加密,在java中进行解密。我以这个为例(#2帖子)

http://www.wenda.io/questions/5025740/encrypt-a-small-string-with-rsa-in-javascript-then-decrypt-in-java-on-server.html

KeyPairGenerator kpg;
try {
    kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(2048);
    KeyPair kp = kpg.genKeyPair();
    yourVariablePublic = kp.getPublic();
    yourVariablePublic = kp.getPrivate();
} catch(NoSuchAlgorithmException e) {
}

现在让我们转到当前页面的 java 代码:

// receiving public key from where you store it
Key publicKey = YourCarrierClass.getYourVariablePublic();
KeyFactory fact;
// initializing public key variable
RSAPublicKeySpec pub = new RSAPublicKeySpec(BigInteger.ZERO, BigInteger.ZERO);
try {
    fact = KeyFactory.getInstance("RSA");
    pub = fact.getKeySpec(publicKey,    RSAPublicKeySpec.class);
} catch(NoSuchAlgorithmException e1) {
} catch(InvalidKeySpecException e) {
}
// now you should pass Modulus string onto your html(jsp) in such way
String htmlUsedModulus = pub.getModulus().toString(16);
// send somehow this String to page, so javascript can use it

并在java代码中解密它:

 Key privateKey = YourCarrierClass.getYourVariablePrivate();
 Cipher cipher;
 BigInteger passwordInt = new BigInteger(ajaxSentPassword, 16);
 byte[] dectyptedText = new byte[1];
 try {
   cipher = javax.crypto.Cipher.getInstance("RSA/ECB/PKCS1Padding");
   byte[] passwordBytes = passwordInt.toByteArray();
   cipher.init(Cipher.DECRYPT_MODE, privateKey);
   dectyptedText = cipher.doFinal(passwordBytes);
   } catch(NoSuchAlgorithmException e) {
   } catch(NoSuchPaddingException e) { 
   } catch(InvalidKeyException e) {
   } catch(IllegalBlockSizeException e) {
   } catch(BadPaddingException e) {
   }
   String passwordNew = new String(dectyptedText);
   System.out.println("Password new " + passwordNew);

就像在示例中一样,我在javascript中使用了以下代码

function sendPassword() {
    var password = $('#passwordField').val();
    var rsa = new RSAKey();
    rsa.setPublic($('#keyModulus').text(), '10001');
    var res = rsa.encrypt(password);
    $('#ajaxSentPassword').val(res);
}

我已经用 Servlet 的 Get 方法更改了密钥对生成部分,并将要传递给 jsp 的值存储在会话中。并将解密部分改为 servlet 的 POST 方法。我确实通过从会话中检索来获取这些密钥以进行解密。这只是为了我的学习,我确实意识到如果实时实施它将很脆弱。这是为了向我学习基础知识。

问题是,在javascript代码中,它无法识别RSAkey(),我得到的是"未捕获的引用错误:RSAKey()未定义"。有谁知道用于该示例的.js文件是什么。我尝试了jsencrypt.js,它显示为"未捕获的引用错误:RSAKey()未定义",如果我使用rsa.js文件 - 我得到无效的RSA公钥错误。没有说明他使用了哪个.js文件。

也可以在这里找到(第二个答案)

在javascript中使用RSA加密一个小字符串,然后在服务器上用java解密

如果你使用 jsencrypt,那么你需要使用它的 API:

 var encrypt = new JSEncrypt();
 encrypt.setPublicKey($('#pubkey').val());
 var encrypted = encrypt.encrypt($('#input').val());

虽然它使用了jsbn库,但我认为它没有暴露。所以,RSAKey不会在那里。如果你想直接使用jsbn,那么你将有一个对RSAKey的引用。

相关文章: