在Android中解密SJCL加密字符串

时间:2014-08-04 21:11:51

标签: android cryptography bouncycastle spongycastle sjcl

我有一个由SJCL服务器端加密的字符串,需要在Android中使用任何可用的库进行解密。我尝试了BouncyCastle,直到我遇到无法从PBKDF2生成密钥的问题。现在我正在使用SpongyCastle,我仍然遇到问题。到目前为止,这是我生成密钥和解密字符串的代码:

private static byte[] decrypt(SecretKey key, byte[] encrypted, byte[] iv) throws Exception {
    IvParameterSpec ivSpec = new IvParameterSpec(iv);
    Cipher cipher = Cipher.getInstance("AES/CCM/NoPadding");
    cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
    byte[] decrypted = cipher.doFinal(encrypted);
    return decrypted;
}

public static SecretKey generateKey(char[] passphraseOrPin, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
    // Number of PBKDF2 hardening rounds to use. Larger values increase
    // computation time. You should select a value that causes computation
    // to take >100ms.
    final int iterations = 1000;

    // Generate a 128-bit key
    final int outputKeyLength = 128;

    /*SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    KeySpec keySpec = new PBEKeySpec(passphraseOrPin, salt, iterations, outputKeyLength);
    SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);*/

    PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator(new SHA256Digest());
    generator.init(PBEParametersGenerator.PKCS5PasswordToBytes(passphraseOrPin), salt, iterations);
    KeyParameter key = (KeyParameter) generator.generateDerivedMacParameters(outputKeyLength);
    SecretKey secretKey = new SecretKeySpec(key.getKey(), "AES");
    return secretKey;
}

以下是我在函数中调用它的方法:

char[] key = * put PBKDF2 password here *;

// Generate key from password
    SecretKey decryptionKey = null;
    try {
        decryptionKey = generateKey(key, decodedObject.get("salt").getAsString().getBytes());
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }

    byte[] decryptedTicketBytes = null;

    // Decrypt the ticket
    try {
        decryptedTicketBytes = decrypt(decryptionKey, decodedObject.get("ct").getAsString().getBytes(), decodedObject.get("iv").getAsString().getBytes());
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }

在使用UTF-8运行JsonParser并进行Base64解码后,decodingObject是来自SJCL的字符串。我拿了它并通过密码运行SJCL Demo并解密了字符串没问题。我必须在这里错过一些简单的东西。

我得到的错误是cipher.doFinal步骤,如下:

java.security.InvalidKeyException: nonce must have length from 7 to 13 octets

我不认为SJCL在其密码上没有使用填充,所以我尝试在getInstance上使用“AES / CCM / PKCS5Padding”,但后来出现了这个错误:

javax.crypto.NoSuchPaddingException: Only NoPadding can be used with AEAD modes.

TLDR:我正在寻找解密Android中SJCL字符串的最简单方法。建议将不胜感激。

谢谢!

3 个答案:

答案 0 :(得分:2)

虽然这不是用Java完成的,但事实上它是在Android中完成的。我知道这不是我想要的解决方案,但它起作用并且是一种解决方案。

您可以使用WebView在Android中运行SJCL来解密文件。您需要一个WebView JavaScript可以与之交谈的界面。

public static class JavaScriptInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    JavaScriptInterface(Context c) {
        mContext = c;
    }

    //This is the function that is callable from the Javascript.
    @JavascriptInterface
    public void doJavaStuff(String dycryptedData)
    {
        //Do what you want with the decrypted data
    }
}

从那里你需要创建一个方法来获取带有SJCL的脚本

public static String getSJCL() { return "<script>\n" + "SJCL_HERE" + "<script>\n";

然后创建HTML以运行代码。这一切都可以使用.html文件和.script文件完成,但我希望我的密钥和加密文件是动态的。

 public static String getHtmlForDecrypting(String encryptedData, String key) {
    return "<html>\n" +
            "    <head>\n" +
                    getSJCL() +
            "        <script type=\"text/javascript\">\n" +
            "            function displaymessage()\n" +
            "            {\n" +
            "                var obj = " + encryptedData + ";\n" +
            "                var objString = JSON.stringify(obj);\n" +
            "                var data = sjcl.decrypt(\"" + key + "\", objString);\n" +
            "                JSInterface.doJavaStuff(data);\n" +
            "            }\n" +
            "        </script>\n" +
            "    </head>\n" +
            "    <body onload=\"displaymessage()\"></body>\n" +
            "</html>\n";
}

接下来创建解密方法。

private static WebView wv;

private static JavaScriptInterface JSInterface;

private static String key1 = "YOURKEY";

public static void decrypt(Context context, String data) {
    JSInterface = new JavaScriptInterface(context);
    wv = new WebView(context);
    wv.addJavascriptInterface(JSInterface, "JSInterface");
    wv.getSettings().setJavaScriptEnabled(true);

    wv.loadData(getHtmlForDecrypting(data, key1), "text/html", null);
}

答案 1 :(得分:0)

问题是Java不能使用默认的sclj iv编号,它使用4个字。 解决方案是告诉sclj用3个字生成iv值:

aesEncrypt:function (pass,data) {
var param = { // Java does not accepts the default 4 word size
        iv: sjcl.random.randomWords(3, 0)
};
return sjcl.encrypt(pass,data,param);
}

不要忘记将iv和salt值与加密邮件一起传递。 如果你不能告诉sclj生成一个较小的iv号,你将不得不改变java实现,或者尝试找一个支持iv的16字节。

答案 2 :(得分:0)

虽然使用WebView可能会有所帮助,但我更喜欢使用ScriptEngine(SE)及其ScriptEngineManager(SEM),这也将最终加载WebView,但至少代码看起来更容易理解和维护。

首先要做的是,由于SE和SEM在Android上本机不可用,因此您可以导入“ rhino-library”来解决此问题。我已找到有关此here的信息,以供参考。

因此,第一步,在您的build.gradle文件中添加依赖项:

    implementation 'io.apisense:rhino-android:1.0'

完成后,其余的操作将非常简单,这里是有关我的操作方式的注释代码。 :

package com.example;

import android.content.Context;

import java.io.InputStream;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import com.example.Constants;

public class SJCL {

    private Invocable invocable;

    public SJCL() {

    }

    public void init(Context c) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        try {
            //in this case the constant points to assets/SJCL.js
            InputStream is = c.getAssets().open(Constants.SJCL_FILE_PATH);
            //put that into a string (function further) 
            String sjcl = convertStreamToString(is);

            // read script file
            engine.evals(sjcl);

            invocable = (Invocable) engine;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //call js function from wrapper function, this is just one as example
    public String encrypt(Object password, String plainText, String[] params) {
    try {
        //first argument is the function name, second is a Object... with your arguments
        return invocable.invokeFunction("encrypt",password,plainText,params).toString();
    } catch (ScriptException | NoSuchMethodException e) {
        return null;
    }
}

    public String convertStreamToString(InputStream is) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        reader.close();`enter code here
        return sb.toString();
    }
}

我还在github上发布了要点,您可以看看here

希望有帮助