我尝试在javascript中进行RSA加密,在java中进行解密。我把它称为例子(#2 post)
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方法修改了keypair生成部分,并将要传递给会话的jsp存储起来。并将解密部分更改为servlet的POST方法。我通过从会话中检索来获取用于解密的密钥。这只是为了我的学习,我确实意识到如果实时实施它将是脆弱的。这是为了向我学习基础知识。
问题是,在javascript代码中,它无法识别RSAkey(),我得到“未捕获的引用错误:RSAKey()未定义”。有谁知道用于该示例的.js文件是什么。我试过jsencrypt.js,显示为“未捕获的引用错误:RSAKey()未定义”,如果我使用rsa.js文件 - 我得到无效的RSA公钥错误。没有说明他使用了哪个.js文件。
也可以在这里找到(第二个答案)
Encrypt a small string with RSA in javascript then decrypt in java on server