[英]Android RSA and node.js RSA Encryption/Decryption
我目前在服务器上解密RSA加密的数据时遇到问题,该服务器正在使用node.js并使用node-rsa库进行加密/解密。
我的Android客户端上收到的公钥没有任何问题,但是当尝试解密数据时,出现以下异常:
TypeError: Cannot call method 'toString' of null
at NodeRSA.module.exports.NodeRSA.$getDecryptedData (C:\src\qteddev\node\nod
e_modules\node-rsa\src\NodeRSA.js:283:27)
at NodeRSA.module.exports.NodeRSA.decrypt (C:\src\qteddev\node\node_modules\
node-rsa\src\NodeRSA.js:170:21)
at IncomingMessage.<anonymous> (C:\src\qteddev\node\main.js:187:36)
at IncomingMessage.emit (events.js:92:17)
at _stream_readable.js:929:16
at process._tickCallback (node.js:419:13)
这就是我在客户端上生成PublicKey的方式
public static void getPublicKeyFromPemFormat(String PEMString,
boolean isFilePath) throws IOException, NoSuchAlgorithmException,
InvalidKeySpecException {
BufferedReader pemReader = null;
if (isFilePath) {
pemReader = new BufferedReader(new InputStreamReader(
new FileInputStream(PEMString)));
} else {
pemReader = new BufferedReader(new InputStreamReader(
new ByteArrayInputStream(PEMString.getBytes("UTF-8"))));
}
StringBuffer content = new StringBuffer();
String line = null;
while ((line = pemReader.readLine()) != null) {
if (line.indexOf("-----BEGIN PUBLIC KEY-----") != -1) {
while ((line = pemReader.readLine()) != null) {
if (line.indexOf("-----END PUBLIC KEY") != -1) {
break;
}
content.append(line.trim());
}
break;
}
}
if (line == null) {
throw new IOException("PUBLIC KEY" + " not found");
}
Log.i("PUBLIC KEY: ", "PEM content = : " + content.toString());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(Base64.decode(content.toString(), Base64.DEFAULT)));
//Log.i("GENERATED EXPONENT AND MODULUS = ", publicKey.toString());
}
这是客户端的加密:
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, QtedEncryption.publicKey);
cipherData = cipher.doFinal(password.getBytes());
password = Base64.encodeToString(cipherData, Base64.DEFAULT);
然后通过POST请求将密码发送到服务器。
var password = key.decrypt(requestData.password,'utf8');
使用此代码启动服务器时会生成公钥和私钥
var rsa = require('node-rsa');
//create RSA-key
var key = new rsa({b: 1024});
console.log(key.getPrivatePEM());
console.log(key.getPublicPEM());
尝试Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
代替。 'node-rsa'
似乎默认为OAEP填充,当前您根本没有使用RSA填充方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.