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

后端 未结 2 826
无人及你
无人及你 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).

    0 讨论(0)
  • 2020-12-30 18:50

    I strongly suspect that what you want to do is call ecipher.doFinal(stringToEncrypt), possibly after a series of doUpdate(...) if you have longer strings.

    .init() creates the cipher object, update() and doFinal() populate the encrypted output and take the plaintext as input.

    Of course, you'll need to convert between String and a byte array.

    0 讨论(0)
提交回复
热议问题