简体   繁体   English

在 Android 中加密并在 CryptoJS 中解密

[英]encrypt in Android and decrypt in CryptoJS

Hi I have java code which decrypt the ciphertext encrypted using CryptoJS library(AES).嗨,我有解密使用 CryptoJS 库(AES)加密的密文的 Java 代码。 Now i wanted to write the javacode which will encrypt the plaintext again.现在我想编写将再次加密明文的javacode。

Please find the below code.请找到以下代码。

 try {
        String secret = "René Über";
        String cipherText="U2FsdGVkX1+tsmZvCEFa/iGeSA0K7gvgs9KXeZKwbCDNCs2zPo+BXjvKYLrJutMK+hxTwl/hyaQLOaD7LLIRo2I5fyeRMPnroo6k8N9uwKk=";

        byte[] cipherData = Base64.decode(cipherText, Base64.DEFAULT);
        byte[] saltData = Arrays.copyOfRange(cipherData, 8, 16);

        MessageDigest md5 = MessageDigest.getInstance("MD5");
        final byte[][] keyAndIV = GenerateKeyAndIV(32, 16, 1, saltData, secret.getBytes("utf-8"), md5);
        SecretKeySpec key = new SecretKeySpec(keyAndIV[0], "AES");
        IvParameterSpec iv = new IvParameterSpec(keyAndIV[1]);

        byte[] encrypted = Arrays.copyOfRange(cipherData, 16, cipherData.length);
        Cipher aesCBC = Cipher.getInstance("AES/CBC/PKCS5Padding");
        aesCBC.init(Cipher.DECRYPT_MODE, key, iv);
        byte[] decryptedData = aesCBC.doFinal(encrypted);
        String decryptedText = new String(decryptedData,"utf-8");
        System.out.println("Decrypted "+decryptedText);
//Here I get right plain text as 
//System.out: Decrypted The quick brown fox jumps over the lazy dog.


        Cipher abc=Cipher.getInstance("AES/CBC/PKCS5Padding");
        abc.init(Cipher.ENCRYPT_MODE,key,iv);
        byte[] encryptedData=abc.doFinal(decryptedData);
        String str=Base64.encodeToString(encryptedData,Base64.DEFAULT);


        System.out.println("encrypted "+str);

//Here i want the encrypted text as
// encrypted U2FsdGVkX1+tsmZvCEFa/iGeSA0K7gvgs9KXeZKwbCDNCs2zPo+BXjvKYLrJutMK+hxTwl/hy//aQLOaD7LLIRo2I5fyeRMPnroo6k8N9uwKk=
//but i receive 
//System.out: encrypted IZ5IDQruC+Cz0pd5krBsIM0KzbM+j4FeO8pgusm60wr6HFPCX+HJpAs5oPssshGjYjl/J5Ew+//eui



    }catch (Exception e)
    {}

When I decrypt the code I get correct Plain Text but when I again encrypt the plain text I didnt get the encrypted text as previous.当我解密代码时,我得到了正确的纯文本,但是当我再次加密纯文本时,我没有像以前那样得到加密文本。 Please Help.请帮忙。

GenerateKeyAndIV function code:- GenerateKeyAndIV 函数代码:-

 public static byte[][] GenerateKeyAndIV(int keyLength, int ivLength, int iterations, byte[] salt, byte[] password, MessageDigest md) {

    int digestLength = md.getDigestLength();
    int requiredLength = (keyLength + ivLength + digestLength - 1) / digestLength * digestLength;
    byte[] generatedData = new byte[requiredLength];
    int generatedLength = 0;

    try {
        md.reset();

        // Repeat process until sufficient data has been generated
        while (generatedLength < keyLength + ivLength) {

            // Digest data (last digest if available, password data, salt if available)
            if (generatedLength > 0)
                md.update(generatedData, generatedLength - digestLength, digestLength);
            md.update(password);
            if (salt != null)
                md.update(salt, 0, 8);
            md.digest(generatedData, generatedLength, digestLength);

            // additional rounds
            for (int i = 1; i < iterations; i++) {
                md.update(generatedData, generatedLength, digestLength);
                md.digest(generatedData, generatedLength, digestLength);
            }

            generatedLength += digestLength;
        }

        // Copy key and IV into separate byte arrays
        byte[][] result = new byte[2][];
        result[0] = Arrays.copyOfRange(generatedData, 0, keyLength);
        if (ivLength > 0)
            result[1] = Arrays.copyOfRange(generatedData, keyLength, keyLength + ivLength);

        return result;

    } catch (DigestException e) {
        throw new RuntimeException(e);

    } finally {
        // Clean out temporary data
        Arrays.fill(generatedData, (byte)0);
    }
}

Your ciphertext has "Salted__<8 byte salt>" at the beginning, which you skip when decrypting.您的密文开头有“Salted__<8 byte salt>”,解密时跳过。 You need to prefix the same in your encryption mode if you want to create OpenSSL compatible ciphertext.如果要创建与 OpenSSL 兼容的密文,则需要在加密模式中添加相同的前缀。

Your encryption code ciphertext seems correct when you view it in a base64 to hex decoder, eg the one provided here .当您在 base64 到十六进制解码器(例如此处提供的解码器)中查看时,您的加密代码密文似乎是正确的。 However, because each character only contains 64 bits and since the bytes have shifted 16 places (which is not divisible by 3), it just seams that your entire ciphertext is incorrect, while it is just missing 16 bytes at the front.然而,因为每个字符只包含 64 位,并且由于字节移动了 16 位(不能被 3 整除),所以它只是接缝你的整个密文是不正确的,而它只是在前面缺少 16 个字节。

Here posting my working code for android I have used crypto for decryption on the server.在这里发布我的 android 工作代码,我在服务器上使用了加密进行解密。 Below code is using AES Algorithm下面的代码使用 AES 算法

  private static final String key = "aesExamplekey";
  private static final String initVector = "exampleintvec";

public static String encrypt(String value) {
    try {
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

        byte[] encrypted = cipher.doFinal(value.getBytes());

       // byte[] finalCiphertext = new byte[encrypted.length+2*16];
          return Base64.encodeToString(encrypted, Base64.NO_WRAP);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}`

Server side code asp.net服务器端代码asp.net

        public string DecryptStringAES(string cipherText)
    {
        //  var keybytes = Encoding.UTF8.GetBytes("7061737323313233");
        //  var iv = Encoding.UTF8.GetBytes("7061737323313233");
        var keybytes = Encoding.UTF8.GetBytes("aesExamplekey");
        var iv = Encoding.UTF8.GetBytes("exampleintvec");

        var encrypted = Convert.FromBase64String(cipherText);
        var decriptedFromJavascript = DecryptStringFromBytes(encrypted, keybytes, iv);
        return string.Format(decriptedFromJavascript);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM