有人知道如何在java中加密并在nodejs中解密吗? 无论算法如何,aes / cbc会更好但无关紧要。
经过几天和几天的搜索解决方案,似乎两种语言的算法不一样。
这是我在kotlin / java中的代码:
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val text = "Hello everybody !"
val password = "1234567812345678"
val encrypted = encrypt(text, password)
Log.i("MainActivity", "encrypted = $encrypted")
val decrypted = decrypt(encrypted, password)
Log.i("MainActivity", "decrypted = $decrypted")
}
private fun encrypt(text: String, password: String): String
{
val keySpec = SecretKeySpec(password.toByteArray(), "AES")
val ivSpec = IvParameterSpec(password.toByteArray())
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec)
val results = cipher.doFinal(text.toByteArray())
return Base64.encodeToString(results, Base64.NO_WRAP or Base64.DEFAULT)
}
private fun decrypt(text: String, password: String): String
{
val keySpec = SecretKeySpec(password.toByteArray(), "AES")
val ivSpec = IvParameterSpec(password.toByteArray())
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec)
return String(cipher.doFinal(Base64.decode(text, Base64.DEFAULT)))
}
这是我在nodejs中的代码:
var crypto = require('crypto');
var text = "Hello everybody !"
var password = new Buffer("1234567812345678")
console.log("Password = " + password)
var encrypted = encrypt(text, password)
console.log("Encrypted = " + encrypted)
var decrypted = decrypt(encrypted, password)
console.log("Decrypted = " + decrypted)
function encrypt(data, password)
{
var cipher = crypto.createCipheriv('aes-128-cbc', password, password);
var crypted = cipher.update(data, 'utf8', 'hex');
crypted += cipher.final('hex');
return crypted;
}
function decrypt(data, password)
{
var decipher = crypto.createDecipheriv('aes-128-cbc', password, password);
var dec = decipher.update(data, 'hex', 'utf8');
dec += decipher.final('utf8');
return dec;
}
我已经阅读了所有相关的教程,但没有任何工作。
答案 0 :(得分:0)
如果您打算将代码用于此类字符串,那么您的代码几乎完全正确。您只需在node.js
部分中使用不正确的编码。
将node.js
的加密和解密更改为base64
,如下所示:
function encrypt(data, password)
{
var cipher = crypto.createCipheriv('aes-128-cbc', password, password);
var crypted = cipher.update(data, 'utf8', 'base64');
crypted += cipher.final('base64');
return crypted;
}
function decrypt(data, password)
{
var decipher = crypto.createDecipheriv('aes-128-cbc', password, password);
var dec = decipher.update(data, 'base64', 'utf8');
dec += decipher.final('utf8');
return dec;
}
并将java部分中的base64
编码更改为以下内容:
private fun encrypt(text: String, password: String): String
{
...
return Base64.getEncoder().encodeToString(results)
}
private fun decrypt(text: String, password: String): String
{
...
return String(cipher.doFinal(Base64.getDecoder().decode(text)))
}
现在Java
和node.js
的加密/解密结果匹配。 :)