Ejemplo 1:
En estos días me ha preocupado un problema. El cifrado AES de NodeJS es inconsistente con el cifrado Java y C#. Por supuesto, esto no será descifrado. Estaba luchando por mucho tiempo: todavía no podía hacerlo más tarde. Se dice en línea que la implementación habitual de NodeJS AES es diferente de otros idiomas. Ok ~~ tal vez.
NodeJs Crypto Module.
La copia del código es la siguiente:
var crypto = require ('crypto');
var data = "156156165152165156156";
console.log ('Original ClearText:' + data);
VAR algorithm = 'AES-128-ECB';
var key = '78541561566';
var clearEncoding = 'utf8';
// var cipherencoding = 'hex';
// Si la siguiente línea no está comentada, el Clearext final es incorrecto.
var cipherencoding = 'base64';
/*cifrado*/
var cifre = crypto.createCipher (algoritmo, clave);
var cipherchunks = [];
cipherchunks.push (cifrado.
cipherchunks.push (cifrado. Final (cifrado));
console.log (cipherencoding + 'cifrado de texto:' + cipherchunks.Join (''));
/*Descifrado*/
var decipher = crypto.createDecipher (algoritmo, clave);
var PlainChunks = [];
para (var i = 0; i <cipherchunks.length; i ++) {
PlainChunks.push (Decipher.update (cipherchunks [i], cifrado de cifrado, clearencoding));
}
PlainChunks.push (Decipher.Final (ClearEncoding));
console.log ("UTF8 EntreMinText Decidt:" + PlainChunks.Join (''));
De hecho, es cierto ~~ cifrado y descifrado son exitosos. Pero es diferente de los encriptados en Java y C#. Dios. Creo que todos están luchando aquí ~~ ¿verdad? De hecho, solo agregue un vector y será consistente. Hay muy pocos recursos buscados en línea. Es solo que he estado luchando durante tanto tiempo. Ok, el código correcto es:
La copia del código es la siguiente:
var crypto = require ('crypto');
var data = "156156165152165156156";
console.log ('Original ClearText:' + data);
VAR algorithm = 'AES-128-ECB';
var key = '78541561566';
var clearEncoding = 'utf8';
var IV = "";
// var cipherencoding = 'hex';
// Si la siguiente línea no está comentada, el Clearext final es incorrecto.
var cipherencoding = 'base64';
var cifre = crypto.createCipheriv (algoritmo, clave, iv);
var cipherchunks = [];
cipherchunks.push (cifrado.
cipherchunks.push (cifrado. Final (cifrado));
console.log (cipherencoding + 'cifrado de texto:' + cipherchunks.Join (''));
var deciPher = crypto.createDecipheriv (algoritmo, clave, iv);
var PlainChunks = [];
para (var i = 0; i <cipherchunks.length; i ++) {
PlainChunks.push (Decipher.update (cipherchunks [i], cifrado de cifrado, clearencoding));
}
PlainChunks.push (Decipher.Final (ClearEncoding));
console.log ("UTF8 EntreMinText Decidt:" + PlainChunks.Join (''));
Comparativamente, se descubrió que el cifrado era consistente. Ok, publica ~~~ Te odio, me perdí el día.
Ejemplo 2:
Durante el trabajo, encontré el lado de Nodejs encriptado a través de AES, y el cliente de Android Java descifró. El lado necesita cifrar la clave ZA y MD5.
NodeJS:
La copia del código es la siguiente:
/**
* Cifrado AES
* @param datos
* @param secretkey
*/
cifryptutils.aesenCrypt = function (data, SecretKey) {
var cipher = crypto.createCipher ('AES-128-ECB', SecretKey);
return cipher.update (datos, 'utf8', 'hex') + cipher.final ('hex');
}
/**
* descifrado de AES
* @param datos
* @param secretkey
* @returns {*}
*/
cifryptutils.aesdecrypt = function (data, SecretKey) {
var cipher = crypto.createDecipher ('AES-128-ECB', SecretKey);
return cipher.update (datos, 'hex', 'utf8') + cipher.final ('utf8');
}
Java:
La copia del código es la siguiente:
paquete com.iofamily.util;
import java.security.MessageGest;
import javax.crypto.cipher;
import javax.crypto.spec.secretkeyspec;
/**
* Cifrado AES, consistente con NodeJS
* @author lmiky
* @Date 2014-2-25
*/
clase pública aesfornodejs {
public static final String default_coding = "UTF-8";
/**
* Descifrado
* @author lmiky
* @Date 2014-2-25
* @param encriptado
* @param semilla
* @devolver
* @@throws Exception
*/
Cadena estática privada Decrypt (Cadena cifrada, semilla de cadena) arroja excepción {
byte [] keyB = Seed.getBytes (default_coding);
MessageDigest MD = MessageGest.getInstance ("MD5");
byte [] thedigest = md.digest (keyb);
Secretkeyspec skey = new SecretKeSpec (thedigest, "aes");
Cifrado dcipher = cipher.getInstance ("aes");
dcipher.init (cipher.decrypt_mode, skey);
byte [] clearByte = dcipher.dofinal (tobyte (encriptado));
devolver una nueva cadena (ClearByte);
}
/**
* Cifrado
* @author lmiky
* @Date 2014-2-25
* @param contenido
* @Param Key
* @devolver
* @@throws Exception
*/
public static string encrypt (contenido de cadena, tecla de cadena) lanza la excepción {
byte [] input = content.getBytes (default_coding);
MessageDigest MD = MessageGest.getInstance ("MD5");
byte [] thedigest = md.digest (key.getBytes (default_coding));
Secretkeyspec skc = new SecretKeSpec (thedigest, "aes");
Cifrado cifrado = cifrado.
cipher.init (cipher.encrypt_mode, skc);
byte [] cifradoxt = nuevo byte [cipher.getOutputSize (input.length)];
int ctLength = cipher.update (entrada, 0, input.length, cifrado de texto, 0);
ctLength += cipher.dofinal (cifrado de texto, ctlength);
return parseByte2hexstr (cifrado de texto);
}
/**
* Cadena a la matriz de bytes
* @author lmiky
* @Date 2014-2-25
* @param hexstring
* @devolver
*/
byte estático privado [] tobyte (string hexstring) {
int len = hexString.length () / 2;
byte [] resultado = nuevo byte [len];
para (int i = 0; i <len; i ++) {
Result [i] = Integer.ValueOf (hexString.substring (2 * i, 2 * i + 2), 16) .byTeValue ();
}
resultado de retorno;
}
/**
* Byte a la matriz hexadecimal
* @author lmiky
* @Date 2014-2-25
* @param buf
* @devolver
*/
cadena estática privada parsebyte2hexstr (byte buf []) {
StringBuffer sb = new StringBuffer ();
para (int i = 0; i <buf.length; i ++) {
Cadena hex = integer.toHexString (buf [i] & 0xff);
if (hex.length () == 1) {
hex = '0' + hex;
}
sb.append (hex);
}
return sb.ToString ();
}
public static void main (string [] args) lanza la excepción {
System.out.println(AESForNodejs.encrypt("fsadfsdafsdafsdafsdafsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadfsadf
System.out.println (aesfornodejs.decrypt ("5b8e85b7a86ad15a275a7cb61fe4c0606005e8741f68797718a3e90d74b5092a", "1234fghjnmlkiuha"); ::::::::: :::::::::::::::::: para::: ::::::::::::::::::::::::::::::: :::::::::::::::::::::::::::::::::::::::::::::::::::
}
}