Java encryption and decryption and digital signature complete code example

  • 2020-12-07 04:04:42
  • OfStack

Common encryption algorithms

Basic one-way encryption algorithm:

BASE64 is strictly a coding format, not an encryption algorithm
MD5(MessageDigestalgorithm5, Information Summary Algorithm)
SHA(SecureHashAlgorithm, secure Hashing algorithm)
HMAC(HashMessageAuthenticationCode, Hash message Authentication Code)

Complex symmetric encryption (DES, PBE), asymmetric encryption algorithm:

DES(DataEncryptionStandard, Data encryption algorithm)
PBE(ES25en-ES26en, based on password authentication)
RSA(The algorithm is named after its inventor: RonRivest,AdiShamir and LeonardAdleman)
DH(Diffie-ES35en algorithm, Key 1 to protocol)
DSA(DigitalSignatureAlgorithm, Digital Signature)
ECC(EllipticCurvesCryptography, Elliptic curve Cryptography)

A digital signature

Algorithm is briefly

A digital signature algorithm can be thought of as a message digest algorithm with a key that contains both public and private keys. In other words, the digital signature algorithm is a combination of asymmetric encryption algorithm and message digest algorithm.

The characteristics of

Digital signature algorithm is required to verify data integrity, authenticate data source, and play the role of denying.

The principle of

The digital signature algorithm includes two operations: signature and verification, and follows the methods of private key signature and public key verification.

Private key and data to be signed are used for signature, while public key, signed value and data to be signed are needed for verification. The core algorithm is the message digest algorithm.

1. Message summary


String beforeDegist = "asdf";  
System.out.println(" The former :"+beforeDegist);     
// The initial information is converted to a byte stream   
byte[] plainText = beforeDegist.getBytes("UTF8");   
// use getInstance(" algorithm ") To get the message summary , Used here SHA-1 the 160 Bit algorithm or MD5 algorithm  
geDigest messageDigest = MessageDigest.getInstance("SHA-1");  
MessageDigest messageDigest = MessageDigest.getInstance("MD5");    
System.out.println("/n" + messageDigest.getProvider().getInfo());    
// Start using algorithms   
messageDigest.update(plainText);    
// Output the result of arithmetic operation   
String afterDegist = new String(messageDigest.digest(),"UTF8");  
System.out.println(" After the :"+afterDegist);  

2. Private key encryption


 /** 
  *  This example is true 1 A string of information, using 1 Private key (key) Encrypt, and then decrypt with the private key to verify if 1 to  
  *  Private key encryption is symmetric encryption  
  *  Use a symmetric algorithm. Such as: A with 1 A key pair 1 A file is encrypted while B To read this file, you need and A1 Like the key, shared by both parties 1 
  *  A private key (and in web In the environment, the private key is easy to be listened on when passing)  
  *  
  *  Additional: The main symmetric algorithms are: DES Only the actual key is used 56  A)  
  * AES (support 3 Key length: 128 , 192 , 256 Bits), usually first 128 Bits, and so on DESede Etc.  
  */  
<span style="white-space: pre; ">  </span>String before = "asdf";      
    byte[] plainText = before.getBytes("UTF8");        
    // STEP 1. 

System.out.println("Start generate AES key.");
// get 1 using AES The algorithm KeyGenerator An instance of the   
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
// Define key length 128 position   
keyGen.init(128);
// through KeyGenerator produce 1 a key (The key algorithm has just been defined, is AES )   
Key key = keyGen.generateKey();
System.out.println("Finish generating AES key="+key);

//STEP 2.


    // To obtain 1 Private key encryption class Cipher To define Cipher Basic Information of: ECB It's encryption, PKCS5Padding It's the filling method   
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");  
//System.out.println("/n" + cipher.getProvider().getInfo());  

//STEP 3.


//  Encrypt with private key   
System.out.println("/n Encrypt with private key ...");
//  Let's take what we just generated key As a parameter, initialize the encryption class with the private key you just obtained, Cipher.ENCRYPT_MODE Meaning encryption   
cipher.init(Cipher.ENCRYPT_MODE, key);
// Private key encryption class Cipher Encrypt, encrypt and return 1 A byte stream byte[]  
byte[] cipherText = cipher.doFinal(plainText);
// In order to UTF8 Format converts a byte stream to String  
String after1 = new String(cipherText, "UTF8");
System.out.println(" Complete with private key encryption: "+after1);

// STEP 4.


[java] view plain copy
// Use the private key to decrypt the information you just encrypted and see if it is not 1 Cause, Cipher.DECRYPT_MODE This means unlocking the key   
System.out.println("/n Decrypt with private key ...");
cipher.init(Cipher.DECRYPT_MODE, key);
// Decrypt the byte stream encrypted by the private key, and return after decryption 1 A byte stream byte[]  
byte[] newPlainText = cipher.doFinal(cipherText);
String after2 = new String(newPlainText, "UTF8");
System.out.println(" Decryption with private key: "+after2);

3. Public key encryption


String before = "asdf";
byte[] plainText = before.getBytes("UTF8");
// produce 1 a RSA Key generator KeyPairGenerator( As the name implies: 1 Pair key generator )  
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
// Define key length 1024 position   
keyGen.initialize(1024);
// through KeyPairGenerator Have the key , Note: here key is 1 Right keys!!   
KeyPair key = keyGen.generateKeyPair();
// To obtain 1 a RSA the Cipher Class, using public key encryption   
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
//System.out.println("/n" + cipher.getProvider().getInfo());  
System.out.println("/n Encrypt with public key ...");
//Cipher.ENCRYPT_MODE It means encrypt, from 1 The public key is obtained from the pair key  key.getPublic()  
cipher.init(Cipher.ENCRYPT_MODE, key.getPublic());
// Encrypt with public key, return 1 A byte stream   
byte[] cipherText = cipher.doFinal(plainText);
// In order to UTF8 Format converts a byte stream to String  
String after1 = new String(cipherText, "UTF8");
System.out.println(" Complete with public key encryption: "+after1);
// Decryption with private key   
System.out.println("/n Decrypt with private key ...");
//Cipher.DECRYPT_MODE Meaning decrypt mode, from 1 The private key is obtained from the pair key  key.getPrivate()  
cipher.init(Cipher.DECRYPT_MODE, key.getPrivate());
// Decrypt with private key, return 1 A byte stream   
byte[] newPlainText = cipher.doFinal(cipherText);
String after2 = new String(newPlainText, "UTF8");
System.out.println(" Decryption with private key: "+after2);

4. Digital signatures


/** 
 *  This example is an example of a digital signature that is used RSA The private key signs the message digest (in this case, the raw data) and then verifies the signature using the public key  
 *  
 * A Through the use of B Encrypt the data and send it to B . B using B Decrypted the private key to get the required data (in B The public key encrypts only data B The private key of  
 *  To unlock, C There is no B Private key of, so C It doesn't work, but C You can use B Public key encryption 1 Send the data to B So that the 1 Here's the question. B Received data to  
 *  The bottom is A It's still coming through C Did you send it?)  
 *  Because the private key is unique 1 , then A You can use A Encrypt your own private key, then B recycling A To decrypt, it can be determined that: 1 It is A The elimination  
 *  The principle of digital signature is based on this  
 *  
 *  Conclusion: A You want to send target data to B At this time, A Need to prepare 1 and 2 Two parts  
 * 1 : A use B The public key of, encrypts the original information for the purpose of confidentiality (only B Can be solved, others use other keys can not be solved, of course, it is confidential.)  
 * 2 : A use A The private key of will sign the summary of the original message to play to the receiver B Sure is A The role of the post ( A with A The private key of is used to sign the summary of the target data  
 *  Name, and then pass it on B, At the same time, C with C The private key to sign any message is also passed B . B What you want to accept is A Data (e.g 1 A transfer request), so B 
 *  through A Of the public key docking received by the two information to decrypt, unlock is A ( A Can and can only be unlocked A Of the private key encrypted data)  
 */
String before = "asdf";
byte[] plainText = before.getBytes("UTF8");
// The formation of RSA Public key for   
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair key = keyGen.generateKeyPair();
// Sign with private key **********************************************************  
Signature sig = Signature.getInstance("SHA1WithRSA");
sig.initSign(key.getPrivate());
//sig Object gets the private key   
// The signature object gets the raw data   
sig.update(plainText);
//sig Object gets the raw data ( In reality, the abstract of the original data is used, and the abstract is one-way, that is, it cannot be decrypted after the abstract algorithm )  
byte[] signature = sig.sign();
//sig The object signs the original data with the private key, and the signature is obtained after the signature signature  
em.out.println(sig.getProvider().getInfo());
String after1 = new String(signature, "UTF8");
System.out.println("/n After signing with the private key :"+after1);
// Using public key validation   
sig.initVerify(key.getPublic());
//sig Object gets public key   
// The signature object gets the original information   
sig.update(plainText);
//sig Object gets the raw data ( In reality, the abstract )  
try {
	if (sig.verify(signature)) {
		//sig Object decrypts the signature with the public key signature Get the raw data ( Namely the ) . 1 To the true  
		System.out.println(" Signature verification correct!! "+new String(plainText, "UTF8"));
	} else {
		System.out.println(" Signature verification failed!! ");
	}
}
catch (SignatureException e) {
	System.out.println(" Signature verification failed!! ");
}

Digital certificates


/** 
 *  This example is an operation on a digital certificate file  
  * java Platform (installed on the machine jdk ) provides you with a keystore ( Certificate store ) . cmd Under the keytool Command to create a certificate library  
  *  
  *  Before running this example:  
  *  in c Create under disk directory 1 The specified certificate library is BocsoftKeyLib , create the alias as TestCertification the 1 Bar certificate, which specifies the use of   
  * RSA  Algorithm is generated and the specified key length is 1024 , the certificate is valid for 1 years  
  *  The export certificate file is TC.cer Saved on local disk C:/ 
  *  The password is qazzaq 
  */
try {
	// Premise: will be in the certificate library 1 Export a certificate to a certificate file ( The certificate file in my example is called TC.cer)  
	// Certificate document TC.cer To read the certificate information   
	CertificateFactory cf = CertificateFactory.getInstance("X.509");
	FileInputStream in = new FileInputStream("C:/TC.cer");
	// Read the file as a file stream into the certificate class Certificate In the   
	Certificate c = cf.generateCertificate(in);
	System.err.println(" Converted to String Certificate information: "+c.toString());
	*/  
	    // Or read the certificate information directly from the certificate library, and the results above, without using the code above 1 touch 1 sample   
	String pass="qazzaq";
	FileInputStream in2=new FileInputStream("C:/BocsoftKeyLib");
	KeyStore ks=KeyStore.getInstance("JKS");
	ks.load(in2,pass.toCharArray());
	String alias = "TestCertification";
	//alias Alias for an entry   
	Certificate c=ks.getCertificate(alias);
	System.err.println(" Converted to String Certificate information: "+c.toString());
	// Capture the X509Certificate Object of type, which is the certificate class fetch Certificate Subclass, which implements more methods   
	X509Certificate t=(X509Certificate)c;
	// Extract the required information from the information   
	System.out.println(" The version number :"+t.getVersion());
	System.out.println(" The serial number :"+t.getSerialNumber().toString(16));
	System.out.println(" Principal name: "+t.getSubjectDN());
	System.out.println(" Issued to: "+t.getIssuerDN());
	System.out.println(" The period of validity: "+t.getNotBefore());
	System.out.println(" Signature algorithm: "+t.getSigAlgName());
	byte [] sig=t.getSignature();
	// The signature value   
	PublicKey pk = t.getPublicKey();
	byte [] pkenc=pk.getEncoded();
	System.out.println(" Public key: ");
	for (int i=0;i<pkenc.length;i++){
		System.out.print(pkenc[i]+",");
	}
	System.err.println();
	// Certificate date validity check, issued certificates have 1 A valid date interval   
	Date TimeNow=new Date();
	t.checkValidity(TimeNow);
	System.out.println(" Date validity check of certificate : Valid certificate date! ");
	// Verify the validity of the certificate signature through the digital certificate certification center (CA) Issued by the organization to the client CA Certificates, such as: caroot.crt file   
	// I don't have it in my hand CA Certificate issued to me, so the following code will not execute   
	/*FileInputStream in3=new FileInputStream("caroot.crt");   
    // To obtain CA certificate  
    Certificate cac = cf.generateCertificate(in3); 
    // To obtain CA The public key    
    PublicKey pbk=cac.getPublicKey();   
    //c For the local certificate, that is, the certificate to be inspected CA Public key verification digital certificate c The effectiveness of the  
    c.verify(pbk);        
  } catch(CertificateExpiredException e){// Date validity check of certificate : overdue    
    System.out.println(" Date validity check of certificate : overdue ");     
  } catch(CertificateNotYetValidException e){ // Date validity check of certificate : Has yet to take effect    
    System.out.println(" Date validity check of certificate : Has yet to take effect ");   
  } catch (CertificateException ce) {  
    ce.printStackTrace();  
  } catch (FileNotFoundException fe) {  
    fe.printStackTrace();  
  } /*catch (IOException ioe){ 
  } catch (KeyStoreException kse){ 
  }*/
	catch (Exception e){
		e.printStackTrace();
	}
}

conclusion

That's the end of this article on Java encryption, decryption and digital signature complete code examples, I hope to help you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: