nodejs对接java端加密解密问题
发布于 9 年前 作者 wwj559 5547 次浏览 最后一次编辑是 8 年前 来自 问答

当前项目要求对上游java端发来的数据进行解密,尝试了很久未能操作成功.之后还有对数据进行加密发送过去的要求. 不知问题出在哪儿, 还请各位赐教.

java端代码如下: public class Copy_Converter{ public static String enConverter(String xmlStr, String key)throws Exception { String str = Copy_StrZipUtil.compress(xmlStr); str = Copy_AES.encrypt(str, key); return str; } public static String deConverter(String xmlStr, String key) throws Exception { String str = null; str = Copy_AES.decrypt(xmlStr, key); str = Copy_StrZipUtil.uncompress(str); return str; } }

public class Copy_AES{ public static String encrypt(String str, String key) throws Exception{ if ((str == null) || (key == null)) return null; Cipher cipher = Cipher.getInstance(“AES/ECB/PKCS5Padding”); cipher.init(1, new SecretKeySpec(key.getBytes(“utf-8”), “AES”)); byte[] bytes = cipher.doFinal(str.getBytes(“utf-8”)); return new BASE64Encoder().encode(bytes); } public static String decrypt(String str, String key) throws Exception { if ((str == null) || (key == null)) return null; Cipher cipher = Cipher.getInstance(“AES/ECB/PKCS5Padding”); cipher.init(2, new SecretKeySpec(key.getBytes(“utf-8”), “AES”)); byte[] bytes = new BASE64Decoder().decodeBuffer(str); bytes = cipher.doFinal(bytes); return new String(bytes, “utf-8”); } }

public class Copy_StrZipUtil { public static String compress(String str) throws IOException{ if ((str == null) || (str.length() == 0)) { return str; } ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(out); gzip.write(str.getBytes()); gzip.close(); return out.toString(“ISO-8859-1”); } public static String uncompress(String str) throws IOException { if ((str == null) || (str.length() == 0)) { return str; } ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes(“ISO-8859-1”)); GZIPInputStream gunzip = new GZIPInputStream(in); byte[] buffer = new byte[256]; int n; while ((n = gunzip.read(buffer)) >= 0){ out.write(buffer, 0, n); } return out.toString(); } }

自己拟写的nodejs端代码 var crypto = require(‘crypto’), zlib = require(‘zlib’), deAES = function(key, str){ str = new Buffer(str, ‘base64’); var deCipher = crypto.createDecipheriv(‘aes-128-ecb’, key, ‘’); str = deCipher.update(str, ‘base64’, ‘utf8’) + deCipher.final(‘utf8’); return str; }, gunzip = function(str){ var buffer = new Buffer(str, ‘utf8’); zlib.gunzip(buffer, function(err, buffer) { if (err) { console.log(err); //此处被执行 }else{ console.log(buffer.toString();) } }); };

回到顶部