Java encryption and decryption notes (i) Base64 and data digest algorithms

Source: Internet
Author: User
Tags base64 decrypt hmac asymmetric encryption

It is important to understand the following for encryption and decryption:

The two sides want to communicate, the middle connection may be bugged or even tampered with. The solution is to encrypt the contents of the transmission, using ciphertext to transmit, so that even if the listener can not know the specific content of the information.

When encrypting, both parties can contract a password A, a with a encryption, B with a decryption, which is symmetric encryption . One problem with symmetric cryptography is: how do keys pass to each other?

Seemingly no solution, so there is asymmetric encryption , asymmetric encryption when there are two keys, is the public key is also a private key. Public key encryption can only be decrypted with the private key, whereas the private key encryption can only be decrypted with the public key. This has changed a little in the process.

Originally in symmetric encryption, the key can not be passed, now good, the key is not to pass, because the public key is public, anyone could get. The process is as follows:

    1. A To send information to B, then a need to know the public key B;
    2. A is encrypted with the public key of B, and the data is passed to B;
    3. b Decrypt it with its own private key to get the data

In the process:

    1. If someone has tapped the data, because this person does not have the private key of B, so cannot decrypt, therefore cannot see the data content;
    2. What if someone wants to tamper with the data? The answer can not be done, because even a hair of what content is not known, so there is no tampering.

A little bit of detail here is that when a is sending data, it is not making the public key, but asking the receiver for the public key.

The above process also missed a problem: although the problem can not be tampered with, then I could always fake data it?

Because B's public key is public, then I can hold B's public key to B want to send what?

b How do you know the data a sent over it? The answer is to verify with a digital signature .

Asymmetric encryption RSA supports digital signatures, and the process is:

    1. A signature is generated using one of its own private key data;
    2. A when sending data to B, the signature is also sent in the past;
    3. b at the time of receiving the data, use a public key published by A to verify the received signature;

In general, the solution to the security problem is as follows:

    1. Data integrity issues: Data Digest validation
    2. Data privacy issues: Symmetric encryption & Asymmetric encryption
    3. Authentication issues: Digital signatures
Simple Data Conversion Base64

converting data into data that is not easily identifiable is one of the simplest encryption, such as BASE64 encoding:

 Public classBase64util { Public Static voidMain (string[] args)throwsexception{String str= "Hello"; byte[] bytes =str.getbytes (); String Encodedstr=encode (bytes);                System.out.println (ENCODEDSTR); byte[] Decodedbytes =decode (ENCODEDSTR); System.out.println (NewString (decodedbytes)); }         Public StaticString Encode (byte[] bytes) {        return NewBase64encoder (). Encode (bytes); }         Public Static byte[] Decode (String encodestr)throwsioexception{return NewBase64decoder (). Decodebuffer (ENCODESTR); }}

The implementation of the JAVA8 built-in Base64 can be used through the Java.util.Base64 tool class.

The output is as follows:

sgvsbg8=Hello

This encoding is reversible, so the longer the data is encrypted, the longer the result is because the data stores all the details of the original data. Other, such as the MD5 algorithm, is irreversible, it belongs to the content summary, how long the data to get over, the final result of the summary results are the same length. Because of this feature, it is often used to verify that a file has been modified.

Data Digest Algorithm MD5
 Public class Md5util {    publicstaticvoidthrows  Exception {        = Messagedigest.getinstance ("MD5");         = "a";                 byte [] md5bytes = Md.digest (Pwd.getbytes ("UTF-8"));        System.out.println (new  String (Hex.encode (md5bytes)));        System.out.println (Base64util.encode (Md5bytes));}                    }

MD5 is used in conjunction with BASE64, which is used to encrypt a fixed-length Base64 code. If you don't use BASE64 encoding, Spring's hex has a friendly output of the MD5 data.

MD is the abbreviation of message Digest algorithm, Chinese name Messages Digest algorithm, the latest fifth edition is MD5, the historical version of MD4, MD2, etc., due to the existence of defects are no longer used. The result of the message digest algorithm is different between versions.

The MD2 algorithm was produced in 1989;
The MD4 algorithm was produced in 1990;
The MD5 algorithm was generated in 1991.

MD5 is a widely used version, but its security has been questioned many years ago (collision algorithm). In 2008, the MD6 algorithm was proposed, and after several improvements, the MD6 was still a pilot phase and was not formally used.

Also, from the JDK API, there are other message digest algorithms in addition to the MDX family:

SHA

The full name of Sha is called the Secure Hash algorithm (Secure Hash algorithm), which is a more secure message digest algorithm than MD5.

 Public class Shautil {    publicstaticvoidthrows  exception{        = Messagedigest.getinstance ("SHA-1");         = "Hello";         = Base64util.encode (md.digest (Str.getbytes ()));        System.out.println (STR2);    }}

HMAC  

The full name of the HMAC is the hash message authentication code (hash MSG authentication code). Personally, all message digests are nothing more than data validation. An important example is that we do not save the plaintext user password in the database, but save the digest of the password. Because the digest algorithm is transparent, in order to prevent the collision, it is necessary to "add salt" to the digest. The added salt actually has the fastidious, the random number? Current system time? In fact, it is easy to guess. HMAC is the solution to this problem. It does not matter what the specific message digest is, it can be used with MD5 or SHA. It focuses on how to generate this random salt, which is the key. In HMAC, the digest is required secret key, thus guaranteeing the concealment of the digest, so it is not easy to be hit the library.

 Public classHmacutil { Public Static voidMain (string[] args)throwsException {String data= "Hello"; String Key=GetKey (); System.out.println ("Key:" +key); String mac=Encrypthmac (Key.getbytes (), data.getbytes ());                System.out.println (MAC); System.out.println (Encrypthmac (Key.getbytes (),"Hello2". GetBytes ())); }         Public StaticString GetKey ()throwsexception{keygenerator Generator= Keygenerator.getinstance ("HmacMD5"); Secretkey Key=Generator.generatekey (); byte[] bytes =key.getencoded (); returnBase64util.encode (bytes); }         Public StaticString Encrypthmac (byte[] Key,byte[] data)throwsexception{Secretkey Secretkey=NewSecretkeyspec (Key, "HmacMD5"); Mac Mac= Mac.getinstance ("HmacMD5");                Mac.init (Secretkey); byte[] Resultbytes =mac.dofinal (data); String resultstring=Base64util.encode (resultbytes); returnresultstring; }}

The summary algorithm name that is available for HMAC:

Encryption and decryption fields are everywhere "key", the JDK itself implemented a number of algorithms to generate the secret key method (Keygenerator), these algorithms include:

Resources:

http://snowolf.iteye.com/blog/379860

Java encryption and decryption notes (i) Base64 and data digest algorithms

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.