Java safe and quick start

xiaoxiao2021-03-06  44

I have written this blog for the next blog, which is prepared for XML Encryption. This article mainly talks about encryption and digital signatures in passwords, 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 simple, java.security.MessageDigest provides an easy way: / ** * messagedigestexample.java * Copyright 2005-2-16 * / import java.security.MESSAGEDIGEST; / * * * Single message summary algorithm, does not use password. Can be used to hide the plain text message (such as: password) hidden save * / public class messagedigestexample {public static void main (String [] args) throws exception {if (args.length! = 1) {System.err.Println ("USAGE: Java MessageDigestexample); System.exit (1);} Byte [] plaintext = args [0] .getbytes (" UTF8 "); // Use GetInstance (" Algorithm ") to obtain a message summary, here 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 Complete System.out.println (New String (Messagest.digest (), " UTF8 "));}} can also be encrypted through the message authentication code, Javax.crypto.mac provides a solution, and interesters can refer to the relevant API documentation, this article is just a brief 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 are encrypted using the AES algorithm: / ** * 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 ("usage: Java privateexample "); System.exit (1);} byte [] plaintext = args [0] .getbytes (" UTF8 "); // Form a key system.out.Println (" / NStart Generate) through KeyGenerator "); Keygenerator keygen = keygenerator.getInstance (" aes "); keygen.init (128); key key = keygen.generateKey (); system.out.println (" finish generating des key "; // A private encryption class Cipher, ECB is encrypted, pkcs5padding is a fill method cipher copher = 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.dofina l (ciphertext); System.out.Println ("Finish Decryption:"); System.out.Println (New String (New String (New String (NewPlainText, "UTF8"));}} 3) Public key encryption: mentioned above, private key encryption Need a shared key, how do you transfer a key? 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_mo De, key.getpublic (); 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 (New String (New String ");}} 4) Digital Signature: Digital Signature, It is the first to determine the communication of the communication member level.

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 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, use 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 RSA public key of 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 sig = signature.getinstance ("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 public authentication system.out.println ("/ nStart Signature Verification"); SIG.INITVERIFY (key.getpublic ()); sig.Update (plaintext); try {if (Signature (SIGNATURE) ) {System.out.prin TLN ("Signature Verified");} else system.out.println ("signature failed");} catch (signatureexcection) {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 understanding how to sign the JAR file, the JAR file is equivalent to the zip file in Java, allowing multiple Java class files to one. Jar In the extension 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 to 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.) Using Applet: then browser will prompt you: allow this session - Reject - Always Permit - View Certificate, etc. Third, SSL Secure Sockets Layer and Transport Layer Security (TLS TRANSPORT LAYER Security) are protocols for building a secure communication channel between clients and servers. It is also used to authenticate the server for the client authentication server, and (less common) to the server authentication client. This protocol is more common in the browser application, the lock at the bottom of the browser window indicates that SSL / TLS is valid: 1) When using SSL / TLS (usually using https: // URL) to request the site, from the server to the client Send a certificate. The client uses the installed public CA certificate to verify the identity of the server through this certificate, and then check if the IP name (machine name) matches the machine connected to the client. 2) The client generates some random information that can be used to generate a private key (called session key), and then encrypt it with the public key of the server and send it to the server. The server decrypts the message with its own private key, and then derives the same private session key as the client. The RSA public key algorithm is usually used at this stage. 3) The client and server communicate using a private session key and private key algorithm (usually RC4). Use another key message authentication code to ensure the integrity of the message. JavaX.Net.ssl.sslServersocketFactory class provides a good SSLServersocker factory class, familiar with Socket programming readers can practice. After writing the server-side, enter the https: // host name on the browser: The port will call via SSL / TLS.

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

New Post(0)
CopyRight © 2020 All Rights Reserved
Processed: 0.037, SQL: 12