【问题标题】:Is there a way to cipher in java/kotlin and decipher in nodejs with AES/CBC?有没有办法用 AES/CBC 在 java/kotlin 中加密并在 nodejs 中解密?
【发布时间】:2018-03-31 16:51:58
【问题描述】:

我尝试在 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 中实现。

请问有人知道怎么做吗?感谢您提前!

【问题讨论】:

  • 您的 Kotlin 代码使用 Base64byte[]<->String 进行编码/解码,但是在 Node.js 方面,您定义它应该被视为 hex。我认为这不会奏效。
  • 您需要为每个编码使用相同的编码,请查看每个编码的文档。许多“新”语言想要掩盖二进制以支持字符串,但许多东西本质上是二进制的,例如加密和互联网。因此,您必须为每种语言和加密实现弄清楚这一点。

标签: java android node.js cryptography kotlin


【解决方案1】:

我尝试在 js 和 java 中使用 cbc,noPadding 并应用相同的填充算法并且工作正常,它在 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);
    }

}

【讨论】:

  • 它是从 sun.misc 导入的一个类 sun.misc.BASE64Decoder 用于将 base64 编码数据转换为二进制数据。
【解决方案2】:

我之前也遇到过类似的情况,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 编码和解码。希望有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 2021-06-24
    • 2021-01-05
    • 2017-09-28
    相关资源
    最近更新 更多