将加密的数据保存到文件中

时间:2019-06-18 16:32:28

标签: android encryption

将加密的字符串保存到txt文件时出现问题。没有加密,一切正常。保存后,我看到一个空文件,里面没有任何数据,但是正如我已经说过的,没有加密,一切都很好

这是我到目前为止所拥有的:

public void save(String filename, String content) {
    FileOutputStream fos = null;


    try {

        fos = this.context.openFileOutput(filename, MODE_PRIVATE);
        fos.write(encryptMsg(content, generateKey("password")));

        //Toast.makeText(this.context, "Saved to " + this.context.getFilesDir() + "/" + filename, Toast.LENGTH_LONG).show();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } finally {
        if(fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } 
}

public static SecretKey generateKey(String password)
{
    return new SecretKeySpec(password.getBytes(), "AES");
}

public static byte[] encryptMsg(String message, SecretKey secret) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException
{
    Cipher cipher;
    cipher = Cipher.getInstance("AES/CTR/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    byte[] cipherText = cipher.doFinal(message.getBytes("UTF8"));
    return cipherText;
}

public static String decryptMsg(byte[] cipherText, SecretKey secret) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException
{
    Cipher cipher;
    cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, secret);
    String decryptString = new String(cipher.doFinal(cipherText), "UTF-8");
    return decryptString;
}

我非常喜欢stackoverflow,因为他不让我保存错误日志,因为它的代码太多,所以,我需要这样写文本,对不起

错误日志:

        at javax.crypto.Cipher.tryCombinations(Cipher.java:2891)
        at javax.crypto.Cipher$SpiAndProviderUpdater.updateAndGetSpiAndProvider(Cipher.java:2796)
        at javax.crypto.Cipher.chooseProvider(Cipher.java:773)
        at javax.crypto.Cipher.init(Cipher.java:1143)
        at javax.crypto.Cipher.init(Cipher.java:1084)
        at org.mad.mad.Cache.encryptMsg(Cache.java:159)
        at org.mad.mad.Cache.save(Cache.java:58)
        at org.mad.mad.Cache.explodeBook(Cache.java:95)
        at org.mad.mad.READERActivity$SendPostRequest.onPostExecute(READERActivity.java:306)
        at org.mad.mad.READERActivity$SendPostRequest.onPostExecute(READERActivity.java:236)
        at android.os.AsyncTask.finish(AsyncTask.java:695)
        at android.os.AsyncTask.access$600(AsyncTask.java:180)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
        at android.os.Handler.dispatchMessage(Handler.java:106)
06-18 19:17:06.209 3455-3455/org.mad.mad W/System.err:     at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
    Caused by: java.lang.IllegalArgumentException: Key length not 128/192/256 bits.
        at com.android.org.bouncycastle.crypto.engines.AESEngine.generateWorkingKey(AESEngine.java:288)
        at com.android.org.bouncycastle.crypto.engines.AESEngine.init(AESEngine.java:444)
        at com.android.org.bouncycastle.crypto.modes.SICBlockCipher.init(SICBlockCipher.java:70)
        at com.android.org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher.init(PaddedBufferedBlockCipher.java:75)
06-18 19:17:06.210 3455-3455/org.mad.mad W/System.err:     at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher$BufferedGenericBlockCipher.init(BaseBlockCipher.java:1286)
        at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineInit(BaseBlockCipher.java:944)
        ... 21 more
06-18 19:17:06.211 3455-3455/org.mad.mad V/data: {"text":[[["At","last","it","was","the","Little","Mermaid’s","fifteenth","birthday","and,"],["","towards","the","end","of","the","day,"],["","her","father","looked","at","her","and","said,"],["","’The","time","has","come,","little","one.",""],["","Come","back","and","tell","us","what","you","find.","’",""]],[["The","Little","Mermaid","kissed","her","father,"],["","said","goodbye","to","her","five","sisters"],["","and","began","the","long","swim","to","the","surface.",""]],[["Up","and","up","she","swam"],["","and","it","was","night","time","before","she","came","close","to","the","surface.",""],["","She","saw","a","bright","light","dancing","on","the","water,"],["","then","moments","later","her","face","burst","through","the","waves","into","the","moonlight.",""]],[["For","the","first","time"],["","the","Little","Mermaid","saw","stars","shining","in","the","dark","night","sky"],["","and","felt","the","gentle","sea","winds","on","her","cheeks.",""],["","She","saw","a","sailing","ship","lit","by","hundreds","of","lanterns"],["","and","thought","that","she","had","never","seen","anything","so","beautiful","in","all","her","life.",""],["","She","swam","closer","to","the","ship...","and,"],["","upon","hearing","strange","music,"],["","she","just","had","to","find","out","what","creatures","made","those","wonderful","sounds.",""]],[["Looking","through","a","window","in","the","side","of","the","ship,"],["","she","saw","what","seemed","to","be","a","birthday","party"],["","and","the","special","guest","was","a","young","prince.",""],["","He","stood","in","the","center","of","the","room"],["","and","everybody","seemed","to","be","smiling","at","him.",""]],[["He","was","the","most","handsome","thing","she","had","ever","seen.",""],["","When","he","smiled,","his","eyes","seemed","to","light","up","the","whole","room","and,"],["","by","the","time","the","party","had","ended","and","the","guests","had","gone","to","bed,"],["","the","Little","Mermaid","had","fallen","in","love.",""]],[["’It’s","getting","late,’"],["","she","sighed.",""],["","’I","must","go","back","to","my","father","and","sisters"],["","and","tell","them","what","I","have","seen.",""],["","But","then","came","a","sound"],["","which","the","Little","Mermaid","had","never","heard","before.",""]]]
06-18 19:17:06.214 3455-3455/org.mad.mad W/System.err: com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher$InvalidKeyOrParametersException: Key length not 128/192/256 bits.
        at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineInit(BaseBlockCipher.java:963)
        at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineInit(BaseBlockCipher.java:1076)
        at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:2984)
06-18 19:17:06.215 3455-3455/org.mad.mad W/System.err:     at javax.crypto.Cipher.tryCombinations(Cipher.java:2891)
        at javax.crypto.Cipher$SpiAndProviderUpdater.updateAndGetSpiAndProvider(Cipher.java:2796)
        at javax.crypto.Cipher.chooseProvider(Cipher.java:773)
        at javax.crypto.Cipher.init(Cipher.java:1143)
        at javax.crypto.Cipher.init(Cipher.java:1084)
        at org.mad.mad.Cache.encryptMsg(Cache.java:159)
        at org.mad.mad.Cache.save(Cache.java:58)
06-18 19:17:06.216 3455-3455/org.mad.mad W/System.err:     at org.mad.mad.Cache.explodeBook(Cache.java:95)
        at org.mad.mad.READERActivity$SendPostRequest.onPostExecute(READERActivity.java:306)
        at org.mad.mad.READERActivity$SendPostRequest.onPostExecute(READERActivity.java:236)
        at android.os.AsyncTask.finish(AsyncTask.java:695)
        at android.os.AsyncTask.access$600(AsyncTask.java:180)
06-18 19:17:06.217 3455-3455/org.mad.mad W/System.err:     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
06-18 19:17:06.218 3455-3455/org.mad.mad W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
    Caused by: java.lang.IllegalArgumentException: Key length not 128/192/256 bits.
        at com.android.org.bouncycastle.crypto.engines.AESEngine.generateWorkingKey(AESEngine.java:288)
        at com.android.org.bouncycastle.crypto.engines.AESEngine.init(AESEngine.java:444)
        at com.android.org.bouncycastle.crypto.modes.SICBlockCipher.init(SICBlockCipher.java:70)
        at com.android.org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher.init(PaddedBufferedBlockCipher.java:75)
        at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher$BufferedGenericBlockCipher.init(BaseBlockCipher.java:1286)
06-18 19:17:06.220 3455-3455/org.mad.mad W/System.err:     at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineInit(BaseBlockCipher.java:944)
        ... 21 more
06-18 19:17:06.221 3455-3455/org.mad.mad V/data:```


1 个答案:

答案 0 :(得分:1)

InvalidKeyOrParametersException: Key length not 128/192/256 bits.

好吧,似乎passowrd.getBytes未能生成您期望的密钥长度,请尝试将您的generate key方法更改为以下内容:

KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
return keyGen.generateKey();