Android: Encrypt a string with AES 256bit Encryption with iv and secret key

后端 未结 2 837
无人及你
无人及你 2020-12-30 18:03
SecureRandom random = new SecureRandom(); // quite heavy, look into a lighter method.

String stringToEncrypt = \"mypassword\";
byte[] realiv = new byte[16];
random.         


        
2条回答
  •  南方客
    南方客 (楼主)
    2020-12-30 18:39

    In general you don't need something that generates random numbers for an algorithm that has deterministic behavior. Furthermore, you don't need an IV when you are using ECB block mode, which is what Java defaults to. To be precise, Java defaults to "AES/ECB/PKCS5Padding" for in Cipher.getInstance("AES").

    So you should be OK with code like this:

    // lets use the actual key value instead of the platform specific character decoding
    byte[] secret = Hex.decodeHex("25d6c7fe35b9979a161f2136cd13b0ff".toCharArray());
    
    // that's fine
    SecretKeySpec secretKey = new SecretKeySpec(secret, "AES");
    
    // SecureRandom should either be slow or be implemented in hardware
    SecureRandom random = new SecureRandom();
    
    // first create the cipher
    Cipher eCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    
    // filled with 00h characters first, use Cipher instance so you can switch algorithms
    byte[] realIV = new byte[eCipher.getBlockSize()];
    
    // actually fill with random
    random.nextBytes(realIV);
    
    // MISSING: create IvParameterSpec
    IvParameterSpec ivSpec = new IvParameterSpec(realIV);
    
    // create the cipher using the IV
    eCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
    
    // NOTE: you should really not encrypt passwords for verification
    String stringToEncrypt = "mypassword";
    
    // convert to bytes first, but don't use the platform encoding
    byte[] dataToEncrypt = stringToEncrypt.getBytes(Charset.forName("UTF-8"));
    
    // actually do the encryption using the data
    byte[] encryptedData = eCipher.doFinal(dataToEncrypt);
    

    Now that looks a whole lot better. I've used the Apache commons codec for decoding the hexadecimal string.

    Note that you need to save the realIV with the encryptedData, and that you haven't included integrity protection, e.g. a MAC (for passwords, you may not need that though).

提交回复
热议问题