Java encryption and digital signature programming quick start

xiaoxiao2021-03-06  41

This article mainly talks about encryption and digital signatures in cryptography, and how it is used in Java. Partners who are interested in passwords, recommend watching Bruce Schneier: Applied Crypotography. There is a great improvement in security in JDK1.5 release, and also provides direct support for RSA algorithms. Now we will solve problems from instances (this article is only a simple introduction): First, password is common Concept 1) Message Abstract: This is a technique that is combined with message authentication code to ensure message integrity. Mainly uses a one-way hash function algorithm, which can be used to inspect the integrity of the message, and is saved directly through the hash password, etc., the currently used algorithms are MD4, MD5, SHA-1, JDK1.5 provides above. Support, the message summary in Java is very simple, java.security.MessageDigest provides a simple method:

/***MessageDigestexample.java*copyright 2005-2-16 * / Import Java.security.MessageDigest; / *** Single message summary algorithm, not using password. Can be used to hide the plain text message (such as: password) * / public class MessageDigestExample {public static void main (String [] args) throws Exception {if (args.length = 1!) {System.err.println ( "Usage: java MessageDigestExample text"); System.exit (1) } Byte [] plaintext = args [0] .GetBytes ("UTF8"); // Use GetInstance ("Algorithm") to get a message summary, use SHA-1 160-bit algorithm MessageDigest MessageDigest = MessageDigest.getInstance (" SHA-1 "); system.out.println (" / n " messagedigest.getProvider (). GetInfo ()); // Start using Algorithm MessageDigest.Update (PlainText); System.out.println (" / NDigest: "); // Output algorithm operation result system.out.println (new string (messagedigest.digest ()," UTF8 "));}} can also be encrypted through the message authentication code, javax.crypto.mac provides A solution, interesters can refer to the relevant API documentation, this article is just a simple introduction to what is a summary algorithm. 2) Private Key Encryption: The message summary can only check the integrity of the message, but one-way, the text message cannot be encrypted, if you want to encrypt the text, you need to use other algorithms, to ensure confidentiality, we need to use Private key cryptography to exchange private messages. This is best understood, using a symmetric algorithm. For example: A uses a key to encrypt a file, and the B is read, the key is needed, and the two sides share a private key (while in the web environment, the private key is easily listened when passed. : Use the private key encryption, first require a key to generate a key (Java.Security.Key), then pass to a javax.crypto.cipher, the tool reuse The corresponding algorithm is encrypted, the main symmetric algorithm is: DES (actual key only 56 bits), AES (support three key lengths: 128, 192, 256), usually 128 bits, other DeSede et al, JDK1.5 also provides support for symmetric algorithms, the following examples use the AES algorithm to encrypt:

/***PrivateexMaple.java*copyright 2005-2-16 * / Import javax.crypto.cipher; import javax.crypto.keygenerator; import java.security.key; / *** Private encryption, guarantee message confidentiality * / public class privateexample {public static void main (string [] args) throws exception {if (args.length! = 1) {system.err.println ("Uste: Java Privateexample ); System.exit (1 );} Byte [] plaintext = args [0] .GetBytes ("UTF8"); // Form a key system.out.println ("/ NStart Generate AES Key"); keygenerator.getInstance ("" by KeyGenerator "); Keygen.init (128); key key = keygen.generateKey (); system.out.println; // Get a private encryption class Cipher, ECB is encryption, pkcs5padding It is a filling method cipher cipher = copher.getInstance ("AES / ECB / PKCS5PADDING"); system.out.println ("/ n" cipher.getProvider (). GetInfo ()); // Use private 鈅 encryption system.out .println ("/ nStart Encryption:"); cipher.init (cipher.encrypt_mode, key); Byte [] ciphertext = cipher.dofinal (Plaintext); System.out.println ("Finish Encryption:"); System.out .println (New String (Ciphertext, "UTF8") ); System.out.println ("/ nStart Decryption:"); cipher.init (cipher.decrypt_mode, key); Byte [] newplaintext = cipher.dofinal (ciphertext); system.out.println ("Finish Decryption:" ); System.out.println (New String (New StringText, "UTF8"));}} 3) Public key encryption: The above mentioned that private key encryption requires a shared key, how to transfer keys? In the web environment, the words directly transmitted are easily detected, but fortunately, there is a public key encryption. Public key is also called asymmetric encryption, asymmetric algorithm uses a pair of key pairs, a public key, a private key, using the public key encrypted data, only the private key can be unfolded (available for encryption); at the same time, use private The key encrypted data, only the public key can be unproced (signature).

However, the speed is very slow (100 to 1000 times more encryption than the private key), and the main algorithm of the public key has RSA, including Blowfish, Diffie-Helman, etc., JDK1.5 provides support for RSA, is a way of improvement: /***PublicExample.java*Copyright 2005-2-16 * / import java.security.Key; import javax.crypto.Cipher; import java.security.KeyPairGenerator; import java.security.KeyPair; / ​​*** a simple Public Class encryption example, Cipher class uses KeypairGenerator generated public 鈅 and private * / public class public "{iver (string [] args) throws exception {if (args.length! = 1) {system.err. Println ("Usage: Java PublicExample ); System.exit (1);} byte [] plaintext = args [0] .getbytes (" UTF8 "); // constitutes an RSA key system.out.println ( "/ nStart generating RSA key"); KeyPairGenerator keyGen = KeyPairGenerator.getInstance ( "RSA"); keyGen.initialize (1024); KeyPair key = keyGen.generateKeyPair (); System.out.println ( "Finish generating RSA key" ); // Get a Cipher class of RSA, use public encryption cipher copher = copher.getinstance ("RSA / ECB / PKCS1PADDING"); system.out.println ("/ n" cipher.getProvider (). GetInfo )); System.out.println ("/ nStart Encryption"); cipher.init (cipher.encrypt_mode, key.getp Ublic ()); Byte [] ciphertext = cipher.dofinal (plaintext); System.out.Println ("Finish Encryption:"); System.out.Println (New String (Ciphertext, "UTF8")); // Use Privately decryption system.out.println ("/ nStart Decryption"); cipher.init (cipher.decrypt_mode, key.getprivate ()); Byte [] newplaintext = cipher.dofinal (ciphertext); system.out.println (" FINISH DECRYPTION: "); System.out.println (New String (New String (NewPlainText," UTF8 "));}}

4) Digital Signature: Digital Signature, which is the first level of the communication party identity of the exchange message. The above A is sent to B, b, and B use the private key to decrypt the data, the problem is, since it is used to use the public key encryption, how do you verify that the message sent? The above mentioned, the private key is unique, then A can use A his own private key to encrypt, then use B to decrypt the public key of A, it is possible; the principle of digital signatures is based on this, and usually In order to demonstrate the authenticity of the transmitted data, the short message content is obtained by utilizing a message summary, and then the encrypted scheduling data and the message are transmitted together. Java provides a good support for digital signatures, and the Java.Security.Signature class provides a message signature:

/***DigitalSignature2Example.java*Copyright 2005-2-16 * / import java.security.Signature; import java.security.KeyPairGenerator; import java.security.KeyPair; import java.security.SignatureException; / *** Digital Signature Using the RSA private key to sign the message summary, then use public Class DigitalSignature2example {public static void main (string [] args) throws exception {if (args.length! = 1) {system.err. Println ("USAGE: Java DigitalSignature2example "); System.exit (1);} byte [] plaintext = args [0] .getbytes ("UTF8"); // Forming the RSA public key to system.out.println ( "/ nStart generating RSA key"); KeyPairGenerator keyGen = KeyPairGenerator.getInstance ( "RSA"); keyGen.initialize (1024); KeyPair key = keyGen.generateKeyPair (); System.out.println ( "Finish generating RSA key" ); // use private signature signature sign ("sha1withrsa"); sig.initsign (); sig.Update (plaintext); Byte [] signature = sig.sign (); system .out.Println (SIG.GETPROVIDER (). getInfo ()); System.out.Println ("/ nsignature:"); System.out.Println (NEW STRING (Signature, " UTF8 ")); // Use male to verify system.out.println (" / nStart Signature Verification "); SIG.INITVERIFY (key.getpublic ()); sig.Update (plaintext); try {if (Sig.Verify (Signature)) {system.out.println ("Signature Verified"); Else System.Out.println ("Signature Failed");} catch (signatureexception e) {system.out.println ("Signature Failed"); }}} 5) Digital Certificate.

There is also a problem, that is, the public key problem, A is encrypted with the private key, then B is accepted by the message, decrypt the public key provided by A; then there is a nasty C, he intercepts the message, then use his own Private key encryption, simultaneously send his public key to B, and tell B, that is a public key, result .... At this time, it is necessary to talk to a middle institution (believe in authority, I am correct) There is a Certificate Authority (ie CA), a famous CA organization has VeriSign, and the current digital authentication industry is: ccitt X.509: Digital certificate: It encapsulates an identity identifier along with the public key, and Digital signature is performed by a third party called an authentication center or CA. Keyport: Java platform provides you with a keystore, a repository for a key and certificate. Alternatively, the keystore is a file default name to .KeyStore (there is an option to make it an encrypted file). The key and certificate can have a name (called alia), each alias, is protected by unique password. The key library itself is also protected by password; you can choose to match each alias password with the main keystore password. Use tool Keytool, let's do a self-certified matter (I believe my certification): 1. Creating a keystool keytool -genkey -v -alias feiuserkey -keyalg RSA default in its own home directory (Windows system is C : / Documents and settings / Create a certificate of self-signed a self-signature that uses the RSA algorithm to generate an algorithm, if you use -KeyStore MM, create a key in the current directory. The library MM file to save the key and certificate. 2. View the certificate: keytool -list lists all certificates of the keystore or enters KeyTool -help to view help under DOS. Second, JAR's signature we have learned how to create your own certificate, now you can start learning how to sign the JAR file, the JAR file is equivalent to the zip file in Java, allowing multiple Java class files to a .jar extension In the name of the file, you can then digitally sign this JAR file to confirm its source and authenticity. The receiver of the JAR file can determine whether the code is trusted according to the signature of the sender, and be confident that the content is not tampered with before receiving. At the same time, in the deployment, access to machine resources can be assigned based on the signature of the access control statement in the policy file. In this way, some applets are safely inspected. Use the Jarsigner tool to sign the JAR file: Now we have a Test.jar file (you can use the JAR command line tool to generate): Jarsigner Test.jar FeiUserKey (here we create the certificate), the details can be entered Jarsigner View Help Verify its authenticity: jarsigner -verify test.jar (note that the JAR is modified, but no test is reduced, if new content is added, but also prompts, but will not be prompted.

转载请注明原文地址:https://www.9cbs.com/read-57234.html

New Post(0)