Java Basic encryption algorithm

Source: Internet
Author: User
Tags base64 hmac md5 digest md5 encryption

The simple Java encryption algorithm is:

    1. BASE64 strictly speaking, it belongs to the encoding format, not the encryption algorithm
    2. MD5 (Message Digest algorithm 5, Information Digest algorithm)
    3. SHA (Secure Hash algorithm, security hashing algorithm)
    4. HMAC (Hash message authentication code, hash messages authentication code)

1. BASE64

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 encoding can be used to pass longer identity information in an HTTP environment. For example, in the Java Persistence System hibernate, Base64 is used to encode a long unique identifier (typically 128-bit uuid) as a string that is used as a parameter in an HTTP form and an HTTP GET URL. In other applications, it is often necessary to encode binary data as appropriate in the form of URLs (including hidden form fields). At this time, the use of BASE64 encoding is not readable, that is, the encoded data will not be directly visible to the naked eye. (Source Baidu Encyclopedia)

Java implementation code:

Import Sun.misc.BASE64Encoder; /* Encryption and decryption of BASE64 is bidirectional, can be reverse-solved.
Base64encoder and Base64decoder are unofficial JDK implementation classes. Although it can be found and used in the JDK, it is not available in the API.
The classes in the JRE, Sun and Com.sun, are not documented, they belong to the Java, Javax Class library, where most of the implementations are related to the underlying platform,
The main is Base64encoder, base64decoder two classes, we just need to know how to use the corresponding method.
As defined by RFC2045, Base64 is defined as: the Base64 content transfer encoding is designed to describe an arbitrary sequence of 8-bit bytes as a form that is not easily recognizable by humans.
} public static void Main (string[] args) {
String str= "12345678"; try {
String result1= base64.encryptbase64 (Str.getbytes ());
SYSTEM.OUT.PRINTLN ("result1===== Encrypted Data ==========" +RESULT1); byte result2[]= base64.decryptbase64 (RESULT1);
String Str2=new string (RESULT2);
System.out.println ("str2======== decryption Data ========" +STR2);
} catch (Exception e) {
E.printstacktrace ();
}

2. MD5

MD5 is message-digest algorithm 5 (Information-Digest algorithm 5), which is used to ensure complete and consistent information transmission. is one of the widely used hashing algorithms (also translation digest algorithm, hashing algorithm), mainstream programming language has been widely MD5 implemented. The calculation of data (such as Chinese characters) as another fixed length value is the basic principle of the hashing algorithm, and the predecessor of MD5 is MD2, MD3 and MD4. Widely used in encryption and decryption technology, often used for file verification. Check? No matter how large the file is, a unique MD5 value can be generated after MD5. Like now the ISO check, all is MD5 check. How to use it? It is of course the value of MD5 after the ISO has been MD5. General Download Linux-iso friends have seen the download link next to the MD5 string. is used to verify that the files are consistent.

Java implementations:

Usually we do not use the above MD5 encryption directly. Usually the byte array produced by the MD5 is given to BASE64 and then encrypted to get the corresponding string
Digest: Assembly */public class MD5 {public static final string key_md5 = ' MD5 '; public static string GetResult (String InputS Tr
{
System.out.println ("======= Data before Encryption:" +INPUTSTR);
BigInteger Biginteger=null; try {
} catch (Exception e) {e.printstacktrace ();}
System.out.println ("MD5 after encryption:" + biginteger.tostring (16)); return biginteger.tostring (16);
} public static void Main (String args[])
{try {
GetResult (INPUTSTR);
} catch (Exception e) {
E.printstacktrace ();
}
}
}

The MD5 algorithm has the following characteristics:

1, compressibility: Any length of data, calculated the length of the MD5 value is fixed.

2, easy to calculate: It is easy to calculate the MD5 value from the original data.

3, anti-modification: Any changes to the original data, even if only 1 bytes modified, the resulting MD5 value is very different.

4, weak anti-collision: known raw data and its MD5 value, it is very difficult to find a data with the same MD5 value (that is, falsification of data).

5, strong anti-collision: To find two different data, so that they have the same MD5 value, is very difficult.

MD5 's role is to allow bulk information to be "compressed" into a confidential format before signing a private key with a digital signature software (that is, converting an arbitrary-length byte string into a long hexadecimal string). In addition to MD5, among them the more famous are sha-1, Ripemd and Haval and so on.

3.SHA

Secure Hash algorithm is primarily intended for digital Signature algorithm DSA, which is defined in the digital Signature standard DSS. For messages that are less than 2^64 bits in length, SHA1 produces a 160-bit message digest. The algorithm has been developed and improved by cryptographic experts for many years and is widely used. The idea of the algorithm is to receive a piece of plaintext, and then convert it into a paragraph (usually smaller) ciphertext in an irreversible way, or simply to take a string of input codes (called Pre-mapping or information) and convert them to shorter lengths, A fixed number of bits of output sequence is the process of hashing values (also known as information digests or information authentication codes). The hash function value can be said to be a "fingerprint" or "digest" of the plaintext, so the digital signature of the hash value can be regarded as the digital signature of this plaintext.

Java implementations:

Import Java.security.MessageDigest; /* SHA (Secure Hash algorithm, secure Hash algorithm), a key tool in cryptography applications such as digital signatures,
However, SHA is still recognized as a secure cryptographic algorithm that is more secure than MD5 * * public class SHA {public static final string Key_sha = "SHA"; public static string Getres Ult (String inputstr)
{
BigInteger Sha =null;
System.out.println ("======= Data before Encryption:" +INPUTSTR); byte[] Inputdata = Inputstr.getbytes (); try {
Messagedigest.update (Inputdata);
} catch (Exception e) {e.printstacktrace ();} return sha.tostring (32);
} public static void Main (String args[])
{try {
GetResult (INPUTSTR);
} catch (Exception e) {
E.printstacktrace ();
}
}
Comparison of SHA-1 and MD5

Because both are exported by MD4, SHA-1 and MD5 are very similar to each other. Correspondingly, their strength and other characteristics are similar, but there are several differences:

• Security for brute force attacks: the most significant and important difference is that the SHA-1 digest is 32 bits longer than the MD5 digest. Using the brute force technique, generating any message to make its digest equal to the difficulty of a given report digest is a 2^128 order of magnitude, while for SHA-1 it is a 2^160 order of magnitude of operation. MD5 In this way, the SHA-1 has greater strength for brute force attacks.

Security of password Analysis: Because of the MD5 design, vulnerable to password analysis attacks, SHA-1 appear to be vulnerable to such attacks.

L Speed: On the same hardware, the SHA-1 runs slower than MD5.

4.HMAC

HMAC (Hash message authentication code, hash messages identification code, cryptographic hash algorithm based on the key authentication protocol. The principle of authentication of message identification code is to use public functions and keys to generate a fixed-length value as a certification identifier, which is used to identify the integrity of the message. Use a key to generate a small, fixed-size block of data, the Mac, and add it to the message and transfer it. The receiver uses the key shared with the sender for authentication, and so on.

Java implementation code:

HMAC (Hash message authentication code, hash messages identification code, cryptographic hash algorithm based on the key authentication protocol.
The principle of authentication of message identification code is to use public functions and keys to generate a fixed-length value as a certification identifier, which is used to identify the integrity of the message.
Use a key to generate a small, fixed-size block of data,
}/** * HMAC encryption: Main method
} public static string GetResult1 (String inputstr)
{
String Path=tools.getclasspath ();
String filesource=path+ "/file/hmac_key.txt";
System.out.println ("======= Data before Encryption:" +INPUTSTR);
String key = Hmac.initmackey (); /* Generate key */SYSTEM.OUT.PRINTLN ("mac key: = = =" + key); /* Write the key file */Tools.writemyfile (Filesource,key);
result= Hmac.encrypthmac (Inputdata, key);
} catch (Exception e) {e.printstacktrace ();} return result.tostring ();
} public static string GetResult2 (String inputstr)
{
System.out.println ("======= Data before Encryption:" +INPUTSTR);
String Path=tools.getclasspath ();
String filesource=path+ "/file/hmac_key.txt";
String key=null;; try {/* will read the key from the file */Key=tools.readmyfile (Filesource);
} catch (Exception E1) {
E1.printstacktrace ();}
try {byte[] Inputdata = Inputstr.getbytes ();/* Encrypt data */result= Hmac.encrypthmac (Inputdata, key);
} catch (Exception e) {e.printstacktrace ();} return result.tostring ();
} public static void Main (String args[])
{try {
GETRESULT2 (INPUTSTR);
} catch (Exception e) {
E.printstacktrace ();
}
}

Java Basic encryption algorithm

Related Article

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.