Common encryption algorithms
Basic one-way encryption algorithm:
BASE64 Strictly speaking, it belongs to the encoding format, not the encryption algorithm
MD5 (MessageDigestalgorithm5, information digest algorithm)
SHA (SecureHashAlgorithm, Secure Hash Algorithm)
HMAC (HashMessageAuthenticationCode, hash message authentication code)
Complex symmetric encryption (DES, PBE), asymmetric encryption algorithms:
DES (DataEncryptionStandard, data encryption algorithm)
PBE (Password-basedencryption, based on password verification)
RSA (the name of the algorithm is named after the inventor: RonRivest, Adi Shamir and Leonard Adleman)
DH (Diffie-Hellman algorithm, key consistency protocol)
DSA (DigitalSignature Algorithm, digital signature)
ECC (Elliptic Curves Cryptography)
Digital signature
Brief description of the algorithm
The digital signature algorithm can be regarded as a message digest algorithm with a key, and this key contains both a public and a private key. That is to say, the digital signature algorithm is a combination of asymmetric encryption algorithm and message digest algorithm.
Features
Digital signature algorithms require the ability to verify data integrity, authenticate data sources, and play a role in resisting denial.
principle
The digital signature algorithm includes two operations: signature and verification, which follows the methods of private key signature and public key verification.
When signing, the private key and data to be signed should be used. When verifying, the public key, signature value and data to be signed should be used. The core algorithm is mainly the message digest algorithm.
1. Message summary
String beforeDegist = "asdf"; System.out.println("Before"Summary:"+beforeDegist); //Initial information should be converted into a byte stream byte[] plainText = beforeDegist.getBytes("UTF8"); //Use getInstance("Algorithm") to obtain the message digest. Here, SHA-1's 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 use the algorithm messageDigest.update(plainText); //Output algorithm operation result String afterDegist = new String(messageDigest.digest(),"UTF8"); System.out.println("After summary:"+afterDegist);2. Private key encryption
/** * This example is to encrypt a string information with a private key, and then decrypt it with the private key to verify whether it is consistent. The private key is encrypted, which is symmetric encryption* using a symmetric algorithm. For example: A uses a key to encrypt a file, and B needs the same key as A, and both parties share a * private key (and in the web environment, the private key is easily listened when passed) * * Attachment: The main symmetric algorithms are: DES (the actual key only uses 56 bits) * AES (supports three key lengths: 128, 192, 256 bits), usually 128 bits first, and the others are 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 an instance of KeyGenerator using the AES algorithm KeyGenerator keyGen = KeyGenerator.getInstance("AES");//Define the key length 128-bit keyGen.init(128);//Generate a key through KeyGenerator (the key algorithm has just been defined, AES) Key key = keyGen.generateKey();System.out.println("Finish generating AES key="+key);//STEP 2.
//Get a private key encryption class Cipher, defining the basic information of Cipher: ECB is the encryption method, and PKCS5Padding is the filling method Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); //System.out.println("/n" + cipher.getProvider().getInfo());//STEP 3.
// Use the private key to encrypt System.out.println("/n Encrypt with the private key...");// Use the key just generated as a parameter, and initialize the encryption class using the private key obtained just now. Cipher.ENCRYPT_MODE means encryption cipher.init(Cipher.ENCRYPT_MODE, key);// The private key encryption class Cipher is encrypted, and after encryption, a byte stream is returned byte[] byte[] cipherText = cipher.doFinal(plainText);// Convert the byte stream into String in UTF8 format 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 encrypted just now to see if it is consistent. Cipher.DECRYPT_MODE means the decryption key System.out.println("/n decrypts with the private key...");cipher.init(Cipher.DECRYPT_MODE, key);//Decrypts the byte stream encrypted just now, and returns a byte stream after decryption byte[] byte[] newPlainText = cipher.doFinal(cipherText);String after2 = new String(newPlainText, "UTF8");System.out.println("Decrypted with the private key: "+after2);3. Public key encryption
String before = "asdf";byte[] plainText = before.getBytes("UTF8");// Generate an RSA key generator KeyPairGenerator (as the name implies: a pair of key generators) KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");// Define the key length 1024 bits keyGen.initialize(1024);// Generate a key through KeyPairGenerator, note: the key here is a pair of keys! ! KeyPair key = keyGen.generateKeyPair();//Get a RSA Cipher class, encrypted using public key Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");//System.out.println("/n" + cipher.getProvider().getInfo()); System.out.println("/n Encrypted with public key...");//Cipher.ENCRYPT_MODE means encryption, get the public key from a pair of keys.getPublic() cipher.init(Cipher.ENCRYPT_MODE, key.getPublic());//Encrypt with public key and return a byte stream byte[] cipherText = cipher.doFinal(plainText);//Convert byte stream into String in UTF8 format String after1 = new String(cipherText, "UTF8"); System.out.println("Use public key encryption: "+after1);//Decrypt System.out.println("/nDecrypt with private key...");//Cipher.DECRYPT_MODE means decryption mode, obtain the private key from a pair of keys key.getPrivate() cipher.init(Cipher.DECRYPT_MODE, key.getPrivate());//Decrypt with the private key and return a byte stream byte[] newPlainText = cipher.doFinal(cipherText);String after2 = new String(newPlainText, "UTF8");System.out.println("Decryption with the private key: "+after2);4. Digital Signature
/** * This example is an example of digital signature. Use the RSA private key to sign the message digest (here refers to the original data), and then use the public key to verify the signature* * A encrypts the data with B's public key and sends it to B. B uses B's private key to decrypt it to obtain the required data (the data encrypted by B's public key can only be decrypted by B's private key. C does not have B's private key, so C cannot decrypt it, but C can use B's public key to encrypt a copy of data and send it to B. In this way, the question is, is the data received by B? Is A sent by A or C sent by C?) * Since the private key is unique, A can use A's own private key to encrypt it, and then B uses A's public key to decrypt it, and you can determine: it must be A's message, and the principle of digital signature is based on this* * Summary: A wants to pass the target data to B, and A needs to prepare two parts: 1 and 2* 1: A uses B's public key to encrypt the original information to serve as a confidentiality (only B's private key can be unwrapped, but others cannot unwrap other keys, of course it is confidential) * 2: A uses A's private key to sign the digest of the original information to serve as the receiver B's function to determine that it was sent by A (A uses A's private key to sign the digest of the target data * and then pass it to B. At the same time, C uses C's private key to sign any information to B. What B wants to accept is A's data (such as a transfer request), so B * decrypts the two information received through A's public key, and what is unwrapped is A (A's public key can and can only unwrap the encrypted data of A's private key)) */String before = "asdf";byte[] plainText = before.getBytes("UTF8");//Form an RSA public key pair 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 obtains the private key//Signed object obtains the original data sig.update(plainText);//sig object obtains the original data (in reality, the digest of the original data is used, and the digest is one-way, that is, it cannot be decrypted after the digest algorithm) byte[] signature = sig.sign();//sig object uses the private key to sign the original data, and gets the signature after signing signature em.out.println(sig.getProvider().getInfo()); String after1 = new String(signature, "UTF8");System.out.println("/nSign with private key:"+after1);//Use public key to verify sig.initVerify(key.getPublic());//Sig object gets the public key//Sign object gets the original information sig.update(plainText);//Sig object gets the original data (in reality it is a summary) try {if (sig.verify(signature)) {//Sig object decrypts the signature with public key to obtain the original data (i.e., summary), if true System.out.println("Signature verification is correct!!" +new String(plainText, "UTF8"));} else {System.out.println("Signature verification failed!!");}}catch (SignatureException e) {System.out.println("Signature verification failed!!");}5. Digital Certificate
/** * This example is an operation on the "digital certificate" file* The java platform (installing jdk on the machine) provides you with a keystore (certificate library). The keytool command is provided under cmd to create the certificate library* * Before running this example: * Create a certificate in the c disk directory, specify the certificate library to be BocsoftKeyLib, and create a certificate with the alias TestCertification. It specifies that it is generated using the * RSA algorithm, and the key length is 1024, and the certificate is valid for 1 year* The export certificate file is TC.cer, which is already stored on the local disk C:/ * The password is qazzaq */try {//Preparation: Export a certificate from the certificate library to the certificate file (the certificate file in the example I wrote is TC.cer) //Read certificate information from the certificate file TC.cer CertificateFactory cf = CertificateFactory.getInstance("X.509");FileInputStream in = new FileInputStream("C:/TC.cer");//Read the file into the certificate class Certificate in the form of a file stream Certificate c = cf.generateCertificate(in);System.err.println("Certificate information after converting to String: "+c.toString());*//Or do not use the above code method, read the certificate information directly from the certificate library, which is exactly the same as the above String pass="qazzaq";FileInputStream in2=new FileInputStream("C:/BocsoftKeyLib");KeyStore ks=KeyStore.getInstance("JKS");ks.load(in2,pass.toCharArray());String alias = "TestCertification";//alias is the alias Certificate c=ks.getCertificate(alias);System.err.println("Certificate information after converting to String: "+c.toString());//Get to obtain an object of type X509Certificate. This is a subclass of the certificate class to obtain Certificate, and implements more methods X509Certificate t=(X509Certificate)c;//Extract the required information from the information System.out.println("version number:"+t.getVersion());System.out.println("serial number:"+t.getSerialNumber().toString(16));System.out.println("subject name" : "+t.getSubjectDN());System.out.println("Issuer: "+t.getIssuerDN());System.out.println("Validity period: "+t.getNotBefore());System.out.println("Signature algorithm: "+t.getSigAlgName());byte [] sig=t.getSignature();//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 a valid date interval Date TimeNow=new Date();t.checkValidity(TimeNow);System.out.println("Certificate Date Validity Check: Valid Certificate Date!");//Verify the validity of the certificate signature and issue CA certificate to the customer through the Digital Certificate Certification Center (CA) organization, such as: caroot.crt file//I don't have the certificate issued to me by the CA, so the following code cannot be executed/*FileInputStream in3=new FileInputStream("caroot.crt"); //Get the CA certificate Certificate cac = cf.generateCertificate(in3); //Get the CA's public key PublicKey pbk=cac.getPublicKey(); //c is the local certificate, that is, the certificate to be verified. Use the public key of the CA to verify the validity of the digital certificate c.verify(pbk); } catch(CertificateExpiredException e){//Certificate's date validity check: expired System.out.println("Certificate's date validity check: expired"); } catch(Certificate's date validity check: expired"); } catch(Certificate's date validity check: expired"); } catch(Certificate's date validity check: expired"); } catch(Certificate's date validity check: expired"); } catch (FileNotFoundException ce) { ce.printStackTrace(); } catch (FileNotFoundException fe) { fe.printStackTrace(); } /*catch (IOException ioe){ } catch (KeyStoreException kse){ }*/catch (Exception e){e.printStackTrace();}}Summarize
The above is all about the complete code examples of Java encryption and decryption and digital signatures. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!