想把榜样留给后代:)
首先,我们需要在java代码中生成密钥对
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
现在对于javascript方面:
function sendPassword() {
var password = $('#passwordField').val();
var rsa = new RSAKey();
rsa.setPublic($('#keyModulus').text(), '10001');
var res = rsa.encrypt(password);
$('#ajaxSentPassword').val(res);
}
并用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);
给你,对不起,我不擅长处理这些 catch 子句。
==================================================== ===================
更新:在这里我发现了一些关于这段代码的问题。首先,你可以改变算法
javax.crypto.Cipher.getInstance("RSA/ECB/PKCS1Padding");
至:
javax.crypto.Cipher.getInstance("RSA");
但这不是必需的,它适用于两者。现在真正的问题是关于这条线
byte[] passwordBytes = passwordInt.toByteArray();
在这里,当您从 BigInteger 生成字节数组时,它有时会在前面添加 [0] 作为符号(有时不是!所以算法可以破译该数组),因此字节数组大小可以是 65/129/257,无法通过算法破译,它抛出 IllegalBlockSizeException。在模 RSA 密钥中获取 1 个字节的额外内容中讨论了这个问题,有时对指数也有疑问。最简单的解决方案就是从数组中丢弃那个零:
byte[] byteArray = new byte[256];
BigInteger passwordInt = new BigInteger(password, 16);
if (passwordInt.toByteArray().length > 256) {
for (int i=1; i<257; i++) {
byteArray[i-1] = passwordInt.toByteArray()[i];
}
} else {
byteArray = passwordInt.toByteArray();
}