有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓有没有一种方法可以用java/kotlin加密,用AES/CBC在nodejs中解密?

我尝试用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) 个答案

  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编码和解码。希望有帮助

  2. # 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);
        }
    
    }