MD5 and Base64

Source: Internet
Author: User
Tags base64 md5 md5 encryption
I. Brief description

MD5: All called message digest algorithm 5 (Information digest algorithm), can be encrypted, but not decrypted, belong to one-way encryption, usually used for file verification

BASE64: The 8-bit byte of any sequence is described as a form that is not easily recognizable and is usually used for mail, HTTP encryption. The login username and password fields are encrypted and can be encrypted and decrypted. thinking of MD5 and Base64

MD5 encryption is for arbitrary long data using the MD5 algorithm hash as 4 32-bit groups, if formatted as ASCII characters 16 characters, if formatted 16 binary representation, then 32 characters. (Please refer to the relevant books and materials for the specific algorithm of MD5)

The MD5 is widely used for data checksum integrity testing. and irreversible. Theoretically anti-collision

On August 17, 2004, MD5 suffered a hit, Shandong University's Xiao did the deciphering MD5, HAVAL-128, MD4 and RIPEMD algorithm report. It seems that MD5 will officially be located in SHA1.

Back to the point, later I found that the user password in the ASP.NET2.0 membership can be saved using MD5 encryption, and as far as I parse it, it is not a hexadecimal format string but is saved using BASE64 encoding .

Base64 is one of the most common encoding methods for transmitting 8Bit bytes of code on the network, and you can view rfc2045~rfc2049, which has a detailed specification of MIME.

Base64 requires that every three bytes of 8Bit be converted to four 6Bit bytes (3*8 = 4*6 = two), and 6Bit is then added to the four-bit high 0, which is composed of a byte in the form of a 8Bit , which means that, The converted string will theoretically be 1/3 longer than the original.

In this way, the scheme is basically set down, MD5 encryption and then BASE64 encoding. Then I found a problem, if simply doing this, there will be a problem, that is, if the two user password is the same, will result in the data stored in the database, back to the original learning certification theory, Said can use salt value to solve this problem, is to give each user to generate a random salt value, in the Save and check, you need to add the user's salt value to the original password and then the MD5 operation, so that the same password can generate a different encoding.

OK, Finish.

After the conversion, we use a code table to get the string we want (that is, the final Base64 encoding), this table is this: (from RFC2045)

Table 1:the Base64 Alphabet

value Encoding value Encoding value Encoding value Encoding
0 A (R) i-Z
1 B-S 0
2 C T-K 1
3 D U-PNS L 2 4 E V-M 3 5 F 4 6
G X  5
7 H Y P 6
8 I Z-Q 7 9
J-a R 8
Ten K B 9 s
-45 L T +
M + D
(u)/N (e)
-V (PAD) =
P + g x
Q (h)

The number of bytes in the original text should be a multiple of 3 ah, if this condition is not satisfied, then how to do it. Our solution is this: the original text of the byte is not enough to complement the full, the conversion of Base64 code with the = number instead. This is why some Base64 encodings end with one or two equals signs, but the equals sign is only two. because:

remainder = original number of bytes MOD 3

So the remainder can only be one of the three 0,1,2 in any case. If the remainder is 0, it means that the original byte count is exactly a multiple of 3 (ideally). If it is 1, in order to let the BASE64 code is a multiple of 4, it is necessary to fill 2 equal signs, similarly, if it is 2, it is necessary to fill 1 equal signs. two. Code 1. MD5:

    public class Md5utils {  
        /** 
         * uses MD5 algorithm for encryption 
         * @param plaintext encrypted plaintext 
         * @return  
        Encryption */Public static string Getdigest (string plaintext) {  
            byte[] secretbytes = null;  
            try {  
                secretbytes = messagedigest.getinstance ("MD5"). Digest (Plaintext.getbytes ());  
            } catch ( NoSuchAlgorithmException e) {  
                throw new RuntimeException ("Error Happens", e);  
            }  
            return new BigInteger (1, secretbytes). toString (+);  
        }  
    }  
2. Base64:
public class Base64util {/** * encoded with BASE64 * @param encodecontent content to be encoded * @return encoded content  */public static String encode (string encodecontent) {if (encodecontent = = null) {return  
        Null   
        } Base64encoder encoder = new Base64encoder ();  
    Return Encoder.encode (Encodecontent.getbytes ());  }/** * Encoded with BASE64 * @param encodecontent content to encode * @return encoded content */public static  
    String encode (byte[] encodetext) {return encode (new String (Encodetext));  }/** * Decode with Base64 * @param what the encodecontent needs to decode * @return decoded content */public static   
        String decode (String decodecontent) {byte[] bytes = NULL;  
        if (decodecontent = = null) {return null;  
        try {bytes = new Base64decoder (). Decodebuffer (decodecontent);  
     } catch (IOException e) {       throw new RuntimeException ("Error Happens", E);  
    } finally {} return new String (bytes);  }  
}
3. Test the code:
public class Test {  
    /** 
     * is first encrypted using the MD5 algorithm and then encoded using the base64 algorithm 
     * @param args * 
     /public  
    static void main ( String[] args) {  
         String plaintext = "pwd";    
         String Encodedpassword = md5utils.getdigest (Base64util.encode (plaintext));   
         System.out.println (Encodedpassword);  
    }  
}

Why use BASE64 encoding after using MD5 encryption? Encoded with the BASE64 algorithm is a 32-bit length string, which facilitates storage in the database. Decrypt Md5+base64 's password

See some of the following passwords

    {md5}9vpj/14pytcgxchkcuqcaq==: {md5}z7b610zqdh7/r2wqwqg1gw==: {  
    md5}k3r2hhereuoxrcuuzl5gaw==:  
    { md5}gfnjtgcqe/a7sypbnok1mq==:  
    {md5}ysdenlg9oelkzfofnbmgda==:  
    {md5}q+jknerntnahbhmcvtspzw==:  

It is MD5 encryption, the end of the = = and exposed its base64 encryption.

On the internet there is a software called Base64hex can easily revert to the standard MD5 encryption results, in turn with http://md5ss.sinaapp.com/can be decrypted. using MD5 and BASE64 in Java MD5:

MD5 can combine all the numbers into a new combination of numbers, and this new combination of numbers is 128 bits, also known as the MD5 code. MD5 code is irreversible, that is, the MD5 code can not be reversed to get the original data. MD5 applications are very many, such as saving the user password (to prevent the user password in the database is seen by the administrator, so the password in the database is not allowed to use the plaintext password), or file verification (to prevent the download of the file is modified by other people's files rather than the official original file, such as the XcodeGhost event of the Apple development tool), or the disc breakage check, etc.

In Java, the method is called by the MessageDigest object to obtain the MD5 code for some combination of numbers (by the way, messagedigest can also be used to obtain the SHA checksum code). Call the digest method with the MessageDigest object to convert the number combination into a character array:

String data = "1";    
MessageDigest MD = messagedigest.getinstance ("MD5");
byte[] MD5 = Md.digest (Data.getbytes ());
SYSTEM.OUT.PRINTLN (arrays.tostring (MD5));

The array of bytes obtained is 128 bits, or 16 bytes. In other words, there are 16 elements in the character array after MD5, because the range of byte in Java is -128~127, so each element is within this range:

Note that the character array after MD5 contains negative elements, so if you convert this character array to a string, the query GB2312 or UTF-8 are inappropriate, such as:

String sData = new String (MD5, "utf-8");
System.out.println (SData);


So how do we convert this byte array into a random number with no garbled strings. We can use the "Base64" code. Base64 Code:

The BASE64 encoding is to convert every 3 8 bytes (3*8=24) to 4 6-bit bytes (4*6=24) and 6 two in front of each 0 byte, re-form a 8-bit byte , so that the total length is the same, and that the highest bit is not 1 (that is, not a negative number).

  if the last remaining character is less than 3 characters, the upper is filled with 0, and the output character uses "=". Therefore, one or two "=" may appear at the end of the encoded string.

According to the above principle, the highest two bits are 0, then the remaining 6 are all 12 decimal is 63, so the maximum number will not exceed 63, according to the 64 number of a code value corresponding to the character, it becomes the Base64 encoding, the corresponding encoding table as shown in the following figure:

In Java we use the Base64encoder object to call the Encode method to encode a byte array.

We encode the MD5 code above base64:

Base64encoder be = new Base64encoder ();
String base64 = Be.encode (MD5);
System.out.println (base64);

You can see that this will be garbled characters are corresponding to the character:

Note that Base64encoder cannot view its API documentation because Sun does not formally publish it, and there is no corresponding Javadoc document to review it. You can download the jar package and import it online only by downloading the appropriate jar package or by checking it online, if found unable to find Sun.misc.BASE64Encode in the development IDE.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.