Encrypted save and decrypted load of an ArrayList of serializable objects

前端 未结 3 1536
情书的邮戳
情书的邮戳 2021-02-04 17:37

I save and load in sd card a file that contains an ArrayList of serializable object with these two methods

save method

public static void sa         


        
3条回答
  •  终归单人心
    2021-02-04 17:47

    You could simply use AES Encoding:

    private static byte[] getEncrypt(final String key, final String message) throws GeneralSecurityException {
      final byte[] rawData = key.getBytes(Charset.forName("US-ASCII"));
      if (rawData.length != 16) {
        // If this is not 16 in length, there's a problem with the key size, nothing to do here
        throw new IllegalArgumentException("You've provided an invalid key size");
      }
    
      final SecretKeySpec seckeySpec = new SecretKeySpec(rawData, "AES");
      final Cipher ciph = Cipher.getInstance("AES/CBC/PKCS5Padding");
    
      ciph.init(Cipher.ENCRYPT_MODE, seckeySpec, new IvParameterSpec(new byte[16]));
      return ciph.doFinal(message.getBytes(Charset.forName("US-ASCII")));
    }
    
    private static String getDecrypt(String key, byte[] encrypted) throws GeneralSecurityException {
      final byte[] rawData = key.getBytes(Charset.forName("US-ASCII"));
      if (rawData.length != 16) {
        // If this is not 16 in length, there's a problem with the key size, nothing to do here
        throw new IllegalArgumentException("Invalid key size.");
      }
    
      final SecretKeySpec seckeySpec = new SecretKeySpec(rawData, "AES");
    
      final Cipher ciph = Cipher.getInstance("AES/CBC/PKCS5Padding");
      ciph.init(Cipher.DECRYPT_MODE, seckeySpec, new IvParameterSpec(new byte[16]));
      final byte[] decryptedmess = ciph.doFinal(encrypted);
    
      return new String(decryptedmess, Charset.forName("US-ASCII"));
    }
    

    Then, for trying it, this example may be valid for you:

    final String encrypt = "My16inLengthKey5";
    final byte[] docrypt = getEncrypt(encrypt, "This is a phrase to be encrypted!");
    final String douncrypt = getDecrypt(encrypt.toString(), docrypt);
    Log.d("Decryption", "Decrypted phrase: " + douncrypt);
    

    Of course, douncrypt must match This is a phrase to be encrypted!

提交回复
热议问题