Base64 encoded data maximum size

后端 未结 4 1986
不思量自难忘°
不思量自难忘° 2021-02-09 11:51

I have a security mechanism that implements symmetric algorithm RijndaelManaged. I managed to find information what is the maximum size of encrypted data using

相关标签:
4条回答
  • 2021-02-09 12:16

    A base 64 encoded string will use 4 characters for every 3 bytes (or part thereof). So 128 bytes would be 172 base 64 characters.

    0 讨论(0)
  • 2021-02-09 12:19

    If you need to check this programatically, you can do so by checking the modulus. Here's some psudocode (no particular language) :

    function base64Inflation (numBytes)
        minimumBase64Bytes = roundDown(numBytes / 3 * 4)    
        modulus = numberOfBytes % 3             // Assuming % is the modulo operator
        if modulus == 0 
            return minimumBase64Bytes           // Exact fit! No padding required.
        else
            return minimumBase64Bytes + 4       // Doesn't quite fit. We need to pad.
    

    I've also implemented the same logic in golang:

    http://play.golang.org/p/JK9XPAle5_

    0 讨论(0)
  • 2021-02-09 12:21

    Absolutely - Base64 takes 4 characters to represent every 3 bytes. (Padding is applied for binary data which isn't an exact multiple of 3 bytes.) So 128 bytes will always be 172 characters. (The way to work this out is that base64 represents 6 bits in each character (26 = 64); therefore 3 bytes = 24 bits = 4 base-64 characters.)

    0 讨论(0)
  • 2021-02-09 12:37

    In Java:

    byte[] bytes = new byte[128];
    int base64Length = bytes.length / 3 * 4; // Strictly integer division
    if (bytes.length % 3 != 0)
    {
        base64Length += 4; // Extra padding characters will be added
    }
    System.out.println(bytes.length + " bytes will be encoded in " + base64Length + " characters.");
    

    So, where the input bytes.length == 128, the output will be base64Length == 172 characters.

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