有没有办法在java / kotlin中加密并用AES / CBC解密nodejs?

时间:2018-03-31 16:51:58

标签: java android node.js cryptography kotlin

我尝试在java中加密文本并在nodejs中解密(反之亦然)

我可以使用相同的语言加密和解密,但我不能同时使用它们......

这是我在Kotlin的代码:

@Throws(Exception::class)
fun encrypt(text: String, password: String?): String?
{
    if (password == null)
        return null

    val hash = toHash(password).copyOf(16)
    val keySpec = SecretKeySpec(hash, "AES")
    val ivSpec = IvParameterSpec(hash)
    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)

}

@Throws(Exception::class)
fun decrypt(text: String, password: String?): String?
{
    if (password == null)
        return null

    val hash = toHash(password).copyOf(16)
    val keySpec = SecretKeySpec(hash, "AES")
    val ivSpec = IvParameterSpec(hash)
    val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec)

    return String(cipher.doFinal(Base64.decode(text, Base64.DEFAULT)))
}

这是我在JS中的代码:

function decrypt(data, password)
{
    var hash = sha256(password).substring(0, 16)
    var decipher = crypto.createDecipheriv('aes-128-cbc', hash, hash);
    var dec = decipher.update(data, 'hex', 'utf8');
    dec += decipher.final('utf8');
    return dec;
}

function encrypt(data, password)
{
    var hash = sha256(password).substring(0, 16)
    var cipher = crypto.createCipheriv('aes-128-cbc', hash, hash);
    var crypted = cipher.update(data, 'utf8', 'hex');
    crypted += cipher.final('hex');
    return crypted;
}

我尝试在Java和nodeJS(192,128和256)中使用不同的块大小,但它不起作用。 我不想在ECB中加密,我想在CBC或CTR中实现这一点。

有人知道怎么做吗?谢谢你提前!

2 个答案:

答案 0 :(得分:2)

我尝试过使用cbc,noPadding并在js和java中应用相同的填充算法,并且工作正常,它在js和java中生成相同的加密字符串,请检查链接:

JS链接:

https://plnkr.co/edit/aihF54rkxxw3Jjcly9Uo?p=preview

Java代码:

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.*;

public class CipherConversion {

    private static final String algorithm = "AES/CBC/NoPadding";

    private static final byte[] keyValue = new byte[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    private static final byte[] ivValue = new byte[] { 'f', 'e', 'd', 'c', 'b', 'a', '9', '8', '7', '6', '5', '4', '3', '2', '1', '0' };

    private static final IvParameterSpec ivspec = new IvParameterSpec(ivValue);
    private static final SecretKeySpec keyspec = new SecretKeySpec(keyValue, "AES");

   // final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();

    public static String encrypt(String Data) throws Exception {
        Cipher c = Cipher.getInstance(algorithm);
        c.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
        byte[] encVal = c.doFinal(Data.getBytes());
        String encryptedValue = new BASE64Encoder().encode(encVal);
        return encryptedValue;
    }

    public static String decrypt(String encryptedData) throws Exception {
        Cipher c = Cipher.getInstance(algorithm);
        c.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
        byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
        byte[] decValue = c.doFinal(decordedValue);
        String decryptedValue = new String(decValue);
        return decryptedValue;
    }

    private static String padString(String source) {
        char paddingChar = ' ';
        int size = 16;
        int x = source.length() % size;
        int padLength = size - x;

        for (int i = 0; i < padLength; i++)
        {
            source += paddingChar;
        }
        return source;
      }

    public static void main(String[] args) throws Exception {
        System.out.println("keyValue"+keyValue);
        System.out.println("keyValue"+ivValue);
        String password = "ChangeMe1";
        String passwordEnc = CipherConversion.encrypt(padString(password));
        String passwordDec = CipherConversion.decrypt(passwordEnc);

        System.out.println("Plain Text : " + password);
        System.out.println("Encrypted Text : " + passwordEnc);
        System.out.println("Decrypted Text : " + passwordDec);
    }

}

答案 1 :(得分:1)

之前我遇到过类似的情况,AES加密对应用程序和服务器端都不起作用。最后,我可以让它适用于Android和服务器端。我提供的是用于AES加密的类。但是,我有一个java实现,我认为这将是一个帮助。

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESProvider {
    private static final String ALGORITHM = "AES";
    private static final String ENCRYPTION_KEY = "YourEncryptionKey";

    public static String encrypt(String stringToEncrypt) {
        try {
            SecretKeySpec secretKey = new SecretKeySpec(ENCRYPTION_KEY, ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] data = cipher.doFinal(stringToEncrypt.getBytes("UTF-8"));
            return Base64.encodeToString(data, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    public static String decrypt(String stringToDecrypt) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(ENCRYPTION_KEY, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        return new String(cipher.doFinal(Base64.decode(stringToDecrypt, Base64.DEFAULT)));
    }
}

在我的情况下编码和解码AES加密时,我错过了Base64编码和解码。希望有所帮助!