Java encryption decryption Full solution __java

Source: Internet
Author: User

1 sha Encryption:

Secure Hash algorithm is mainly applicable to digital signature algorithms (Digital Signature algorithm DSA) defined in the digital signature standard (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 encryption experts for many years, and has been widely used. The idea of the algorithm is to receive a clear text and then convert it into a paragraph (usually smaller) cipher in an irreversible way, or simply to take a string of input codes (called Pre-maps or information) and convert them to a shorter, The process of a fixed number of digits in the output sequence that is the hash value (also known as Information Digest or information authentication code). 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 considered a digital signature on the plaintext.

Secure Hash algorithm SHA (Secure hash Algorithm,sha) is a national standard FIPS pub 180 issued by the National Institute of Standards and Technology, the latest standard has been updated in 2008 to FIPS pub 180-3. It prescribes the sha-1,sha-224,sha-256,sha-384, and SHA-512 these one-way hashing algorithms. sha-1,sha-224 and SHA-256 apply to messages that are not longer than 2^64 bits. SHA-384 and SHA-512 apply to messages that are not longer than 2^128 bits.Hashing AlgorithmHashing is the refinement of information, usually of a much smaller length than information, and a fixed length. A cryptographically strong hash must be irreversible, which means that the original information of any part cannot be released by hashing the result. Any change in input information, even if only one, will result in a significant change in the hash result, which is called the avalanche effect. Hashing should also be conflict-proof, that is, two messages with the same hash result cannot be found. Hash results with these attributes can be used to verify that the information has been modified. One-way hash functions are generally used to generate message digest, key encryption, and so on, common are: l MD5 (Messages Digest algorithm 5): is a RSA data security company developed a one-way hashing algorithm. L SHA (Secure Hash algorithm): A 160-bit value can be generated for any length of data operation; SHA-1 in 1993, The Safe hashing algorithm (SHA) was presented by the National Institute of Standards and Technology (NIST) and served as a Federal Information Processing standard (FIPS PUB 180) was released and a revised version of FIPS pub 180-1, commonly called SHA-1, was released in 1995. SHA-1 is based on the MD4 algorithm, and its design is largely modeled on MD4. It is now recognized as one of the safest hashing algorithms and is widely used.principleSHA-1 is a data encryption algorithm, the idea of the algorithm is to receive a clear text and then convert it into a paragraph (usually smaller) cipher in an irreversible way, or simply to take a string of input codes (called Pre-maps or information) and convert them to a shorter, The process of a fixed number of digits in the output sequence that is the hash value (also known as Information Digest or information authentication code). The safety of one-way hash function is that the operation process of producing hash value has a strong one-way. If the password is embedded in the input sequence, then no one can produce the correct hash value without knowing the password, thus ensuring its security. The SHA blocks the input stream by 512 bits (64 bytes) per block and produces 20 bytes of output called the Information authentication Code or information digest. This algorithm input the length of the message is not limited, produces the output is a 160-bit message digest. The input is processed by a 512-bit grouping. SHA-1 is irreversible, conflict-proof, and has a good avalanche effect. Through hashing algorithm can realize digital signature, the principle of digital signature is to transmit the clear text through a function operation (Hash) conversion to the newspaper digest (different clear text corresponding to different message digest), the newspaper digest to be encrypted with plaintext sent to the receiver, The recipient will accept the clear text to produce a new digest to be sent to the sender of the digest to decrypt the comparison, the results of the comparison are consistent to indicate that the plaintext has not been altered, if it is inconsistent that the plaintext has been tampered with. Mac (information authentication code) is a hash result, where some of the input information is a password, only those who know the password can again calculate and verify the legality of the MAC code.comparison of SHA-1 and MD5Because both are derived 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: l for Brute Force attack security: the most significant and important difference is that the SHA-1 summary is 32 bits longer than the MD5 summary. The use of forced technology to produce any message to make its summary equal to the given report summary of the difficulty of MD5 is a 2^128 order of magnitude of operations, and SHA-1 is 2^160 order of magnitude of operations. In this way, SHA-1 has a greater strength for brute force attacks. • Security for password analysis: Because of the MD5 design, vulnerable to cryptanalysis, SHA-1 appears vulnerable to such attacks. L Speed: On the same hardware, SHA-1 runs slower than MD5.

JAVA has implemented the SHA-256 and SHA-512 two Hash algorithms

Using to invoke an already integrated Hash algorithm

Create a Encrypt object and call SHA256 or SHA512 and pass in the text message to be encrypted, respectively, by SHA-256 or SHA-512 two encrypted hash strings.

To change to the MD5 algorithm, the MD5 encryption function can be obtained by modifying the incoming parameter strtype to "MD5".

/** * @file * @date August 5, 2016 * @version 3.4.1 * * Copyright (c) 2013 Sihua Tech, Inc.
 All Rights Reserved.
* * Package encrypt; /** * * @author chengjian.he * @version 3.4, August 5, 2016 morning 10:05:37 * @since * * *

Import; public class Encrypt {/** * incoming text content, return SHA-256 String * * @param strText * @return/public string SHA256
  (Final String StrText)
  {return SHA (StrText, "SHA-256"); /** * Incoming text content, return SHA-512 String * * @param strText * * @return/public string SHA512 (final string StrText
  ) {return SHA (StrText, "SHA-512"); /** * String sha encryption * * @param strsourcetext * @return/private String sha (final string strText, fin

    Al string strtype) {//return value String strresult = null;
        is a valid string if (StrText!= null && strtext.length () > 0) {try {//SHA encryption started Creating encryptionThe object and the encryption type MessageDigest messagedigest = messagedigest.getinstance (strtype);
        Pass in the string Messagedigest.update (Strtext.getbytes ()) to be encrypted;

        Get byte type result byte bytebuffer[] = Messagedigest.digest ();
        Convert byte to string stringbuffer strhexstring = new StringBuffer (); The byte buffer for (int i = 0; i < bytebuffer.length i++) {String hex = integer.tohexstr
          ING (0xFF & bytebuffer[i]);
          if (hex.length () = = 1) {strhexstring.append (' 0 ');
        } strhexstring.append (hex);
      ///Get back the result strresult = Strhexstring.tostring ();
      catch (NoSuchAlgorithmException e) {e.printstacktrace ();
  } return strresult;
	  public static void Main (String args[]) {Encrypt ey = new Encrypt (); System.out.println (EY.
 SHA ("ILoveYou", "MD5"));//62accaf23ac9a73c0b28765b7dfaf75a}}

2 Base64

Base64 is one of the most common coding methods for transmitting 8Bit byte code on the network, and you can view the rfc2045~rfc2049, which has a MIME detail specification. The 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 a 128-bit uuid) as a string, as a parameter in an HTTP form and an HTTP GET URL. In other applications, it is often necessary to encode binary data into a form appropriate to the URL, including hidden form fields. At this point, the use of BASE64 encoding is not readable, that is, the encoded data will not be directly visible to the human eye.

However, standard Base64 are not suitable for direct transmission in URLs, because the URL encoder will change the "/" and "+" characters in the standard Base64 to form "%xx", these "%" numbers will need to be converted when they are stored in the database, because the ANSI SQL has "%" Number is used as a wildcard character. To solve this problem, you can use an improved BASE64 encoding for URLs, not only does it populate the ' = ' number at the end, it also changes the "+" and "/" in the standard Base64 to "-" and "_", thus eliminating the conversion to be made when the URL is encoded and stored in the database. It avoids the increase of the length of encoded information in this process, and unifies the format of object identifiers such as databases, forms, and so on. There is also an improved BASE64 variant for regular expressions, which changes "+" and "/" to "!" and "-", because "+", "*", and "[" and "]" previously used in IRCU may have special meanings in regular expressions. In addition, there are variants that change "+/" to "_-" or ". _" (used as the identifier name in the programming language) or ".-" (for NmToken in XML) or even "_:" (for name in XML). Other applications Mozilla Thunderbird and evolution use Base64 to secure e-mail passwords Base64 are often used as a simple "encryption" to protect certain data, and real encryption is often cumbersome. Spammers use Base64 to circumvent anti-spam tools, because those tools often do not translate Base64 messages. In the LDIF file, Base64 is used as an encoded string.

/** * @file * @date August 5, 2016 * @version 3.4.1 * * Copyright (c) 2013 Sihua Tech, Inc.
 All Rights Reserved.

* * Package encrypt;

Import Decoder.base64decoder;

Import Decoder.base64encoder;  /** * * @author chengjian.he * @version 3.4, August 5, 2016 morning 10:32:23 * @since Yeexun 3.4/public class Base64
		{//Encrypt public string getBase64 (String str) {byte[] b = null;
		String s = null;
		try {b = str.getbytes ("Utf-8");
		catch (Unsupportedencodingexception e) {e.printstacktrace ();
		} if (b!= null) {s = new Base64encoder (). Encode (b);
	return s;
		//Decrypt public string getFromBase64 (string s) {byte[] b = null;
		String result = null;
			if (s!= null) {Base64decoder decoder = new Base64decoder ();
				try {b = Decoder.decodebuffer (s);
			result = new String (b, "Utf-8");
			catch (Exception e) {e.printstacktrace ();
	} return result; public static void Main (StriNg args[]) {Base64 b6 = new Base64 ();
		System.out.println (B6.getbase64 ("ILoveYou"));
	System.out.println (B6.getfrombase64) (B6.getbase64 ("ILoveYou"));


3 Base64encoder

BASE64 encryption and decryption has been the use of SUN.MISC packets under the Base64encoder and Base64decoder Sun.misc.base64encoder/base64decoder class. This person class is a sun company's internal approach and is not publicly available in the Java API and is not part of the JDK standard library, but is included in the JDK and can be used directly.

/** * @file * @date August 5, 2016 * @version 3.4.1 * * Copyright (c) 2013 Sihua Tech, Inc.
 All Rights Reserved.
* * Package encrypt; /** * * @author chengjian.he * @version 3.4, August 5, 2016 morning 10:44:22 * @since Yeexun 3.4/public class base64e  
        Ncoder {public static string getBASE64 (string s) {if (s = = null) return null;  
    Return (new Sun.misc.BASE64Encoder ()). Encode (S.getbytes ());  
            ///decoding BASE64 encoded string s to decrypt public static string getFromBASE64 (string s) {if (s = = null)  
        return null;  
        Sun.misc.BASE64Decoder decoder = new Sun.misc.BASE64Decoder ();  
            try {byte[] b = Decoder.decodebuffer (s);  
        return new String (b);  
        catch (Exception e) {return null; The public static String Mtoa (Object Ming) {return base64encoder.getbase64 base64encoder.getbase64 (Bas E64encoder.getbase64 ((String)Ming))); public static string ATOm (String a) {return base64encoder.getfrombase64 base64encoder.getfrombase64 (base64e
    Ncoder.getfrombase64 (an)));
          public static void Main (string[] args) {String a = Mtoa ("100000.89". toString ());
 System.out.println (a);//Encrypt System.out.println (ATOm (a));//Decrypt}}


The RSA public key cryptography algorithm was presented in 1977 by Ronald Leevist (Ron rivest), Adi Samor (Adi Shamir) and Lennard Adman (Leonard Adleman). It was first announced in 1987, when all three were working at MIT. RSA is the beginning of their three-person surname together with the letter of the composition. RSA is currently the most influential public key encryption algorithm, it can resist the most known password attacks so far, has been recommended by the ISO public key data encryption standards. Today, only a short RSA key can be broken by brute force mode. By 2008, there was no reliable way of attacking the RSA algorithm in the world. As long as the length of the key is long enough, the information encrypted with RSA cannot actually be broken. However, with the increasingly mature of distributed computing and quantum computer theory, RSA encryption security has been challenged. The RSA algorithm is based on a very simple number theory fact: it is easy to multiply two large prime numbers, but it is extremely difficult to factor the product, so you can expose the product as an encryption key.DisadvantageEdit 1) Creating a key is cumbersome, limited by the number of prime generation technology, so it is difficult to do one time a secret. 2) security, RSA Security relies on a large number of factorization, but does not theoretically prove that the difficulty of deciphering RSA and large number of decomposition is equivalent to the difficulty, and the majority of cryptography scholars tend to factorization is not a NP problem. Today, people have been able to decompose more than 140 decimal digits of large primes, this requires a longer key and is slower; In addition, people are actively looking for ways to attack RSA, such as the choice of ciphertext attack, the general attacker is a message to disguise (blind), so that the entity with the private key signed. Then, after calculation, you get the information it wants. In fact, the attack exploits the same vulnerability: the fact that the power retains the multiplicative structure of the input: (XM) d = Xd *MD mod n has already mentioned that this inherent problem comes from the most useful feature of a public key cryptosystem--everyone can use the public key. But the algorithm can not solve the problem, the main measures are two: one is to adopt a good public key protocol to ensure that the entity does not decrypt any information generated by other entities in the course of work, and does not sign the information that it knows nothing about; the other is to never send a random document signature to a stranger, using one-way first when signing The hash function hashes the document or uses a different signature algorithm at the same time. In addition to using public modulus, people try to exploit the decryption index or φ (n) and so on. 3 The speed is too slow, because the RSA packet length is too large, to ensure security, n at least more than bits, so that the cost of the operation is very high, especially the slow, more symmetric cipher algorithm slow several orders of magnitude, and with the development of large number decomposition technology, this length is not conducive to the standardization of data format. The SET (Secure Electronic Transaction) protocol requires the CA to use a 2048-strong key, and the other entity uses a 1024-bit key. In order to speed problem, people widely use single, public key cipher combination of methods, advantages and disadvantages of complementarity: the encryption of a single key password faster, people use it to encrypt a long file, and then use RSA to encrypt the file key, excellent solution to the key distribution problem of the single key password.

/** * @file * @date August 5, 2016 * @version 3.4.1 * * Copyright (c) 2013 Sihua Tech, Inc.
 All Rights Reserved.
* * Package encrypt; /** * * @author chengjian.he * @version 3.4, August 5, 2016 morning 10:51:35 * @since Yeexun 3.4/import

Import Javax.crypto.Cipher;

Import javax.crypto.NoSuchPaddingException; public class Rsatool {public static void Makekeyfile (String pubkeyfile, String privatekeyfile) throws Nosuchalgorith Mexception, FileNotFoundException, IOException {//Keypairgenerator class for generating public and private key pairs, generating objects based on RSA algorithm Keypairgenerator KEYPAIrgen = Keypairgenerator.getinstance ("RSA");
		Initializes a key pair generator with a key size of 1024-bit keypairgen.initialize (1024);

		Generates a key pair, stored in KeyPair KeyPair KeyPair = Keypairgen.generatekeypair ();

		Get the private key rsaprivatekey Privatekey = (rsaprivatekey) keypair.getprivate ();

		Get public key Rsapublickey PublicKey = (rsapublickey) keypair.getpublic ();
		Generate private key ObjectOutputStream Oos = new ObjectOutputStream (new FileOutputStream (Privatekeyfile));
		Oos.writeobject (Privatekey);
		Oos.flush ();

		Oos.close ();
		Oos = new ObjectOutputStream (new FileOutputStream (Pubkeyfile));
		Oos.writeobject (PublicKey);
		Oos.flush ();

		Oos.close ();
	System.out.println ("Make file ok!"); /** * * @param k * @param data * @param encrypt * 1 Encryption 0 Decryption * @return * @throws nosuchpadding  Exception * @throws Exception */public static byte[] Handledata (Key K, byte[] data, int encrypt) throws Exception

			{if (k!= null) {Cipher Cipher = cipher.getinstance ("RSA"); if (encrypt = = 1) {
				Cipher.init (Cipher.encrypt_mode, k);
				byte[] Resultbytes = cipher.dofinal (data);
			return resultbytes;
				else if (encrypt = 0) {Cipher.init (Cipher.decrypt_mode, k);
				byte[] Resultbytes = cipher.dofinal (data);
			return resultbytes;
			else {System.out.println ("parameter must be: 1 Encryption 0 decryption");
	} return null;
		public static void Main (string[] args) throws Exception {String pubfile = "D:/temp/pub.key";

		 String prifile = "D:/temp/pri.key";

		Makekeyfile (Pubfile, prifile);
		ObjectInputStream ois = new ObjectInputStream (new FileInputStream (Pubfile));
		Rsapublickey PubKey = (rsapublickey) ois.readobject ();

		Ois.close ();
		OIS = new ObjectInputStream (new FileInputStream (Prifile));
		Rsaprivatekey Prikey = (rsaprivatekey) ois.readobject ();

		Ois.close ();
		Use public key to encrypt String msg = "~o (∩_∩) O haha ~";

		String enc = "UTF-8";
		Use public key to encrypt the private key to decrypt System.out.println ("Original:" + msg);
		Byte[] result = Handledata (PubKey, msg.getbytes (ENC), 1); System.out.println ("AddDense: "+ new String (result, enc));
		byte[] Deresult = Handledata (prikey, result, 0);

		System.out.println ("Decrypt:" + new String (Deresult, enc));
		msg = "Ho ho";
		Use the private key to encrypt the public key to decrypt System.out.println ("Original:" + msg);
		byte[] result2 = Handledata (Prikey, msg.getbytes (ENC), 1);
		SYSTEM.OUT.PRINTLN ("Encryption:" + new String (RESULT2, enc));
		byte[] Deresult2 = Handledata (PubKey, RESULT2, 0);

	System.out.println ("Decrypt:" + new String (DERESULT2, enc));
Make file ok!
Original: ~o (∩_∩) O haha ~
encrypt: A nډb ym R Cʇu

5 AES Symmetric encryption

The encryption technique can be divided into two kinds: symmetric and asymmetric.

Symmetric encryption, decryption, that is, encryption and decryption is the same secret key, commonly used symmetric encryption technology, such as Des,aes

and asymmetric technology, encryption and decryption is the use of different secret keys, commonly used asymmetric encryption technology, such as RSA

Why should there be asymmetric encryption, decryption technology?

Suppose such a scenario a sends a message to B, but you don't want to send it in clear text, so you need to encrypt the message. If symmetric encryption is used, encryption and decryption use the same secret key. Unless b knows the secret key of a in advance, and keeps it well. So that you can decrypt the message from a.

Since symmetric technology has only one secret key, the management of secret keys is a very troublesome problem. The birth of asymmetric technology solves this problem. Asymmetric encryption and decryption use a different secret key, and the secret key pair is one by one corresponding, that is, with a's private key encrypted ciphertext can only be decrypted with a public key.

In this case, each person has two secret keys, the private key and the public key, the private key is only know by oneself, cannot tell others, but the public key is public, everybody can know

Related Article

Beyond APAC's No.1 Cloud

19.6% IaaS Market Share in Asia Pacific - Gartner IT Service report, 2018

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.