Current location - Quotes Website - Personality signature - Java encryption and digital signature
Java encryption and digital signature
Java encryption and digital signature This paper mainly talks about encryption and digital signature in cryptography and how to use them in Java. Partners who are interested in cryptography recommend Bruce Schneier's book Applied Cryptography, which has greatly improved the security in the release version of jdk and provided direct support for RSA algorithm. Now let's solve the problem from examples (this article is just a brief introduction).

A concept commonly used in cryptography

) message summary

This is a technology combined with message authentication code to ensure the integrity of the message. It mainly adopts one-way hash function algorithm, which can be used to check the integrity of messages and save them directly in text form through hash passwords. At present, MD MD SHA jdk provides support for all the above contents. It is very simple to summarize messages in java, and java security MessageDigest provides a simple operation method.

/* * * MessageDigestExample Java * Copyright */import Java security message digest; /* * * Single message digest algorithm can be used to hide and save plaintext messages (such as passwords) */public class messagedigest {public static void main (string [] args) throwsexception {if (argslength! = ){ System err println (usage: Java message digest sample text); System exit (); }

byte[]plainText = args[]getBytes(UTF);

//Use getInstance (algorithm) to get the message digest. Here, SHA's bit algorithm Message Digest = Message Digest GetInstance (Sha) is used;

system out println(\ n+message digest get provider()getInfo()); //Start using the algorithm messageDigest update (plaintext); System output println (\ ndigest:); //Output algorithm operation result System Out Println (New String (Message Digest Digest () UTF)); }} can also be encrypted with message authentication code. Javax encrypted Mac provides a solution. Interested parties can refer to the relevant API files. This article just briefly introduces what is summarization algorithm.

Here is another example of using message digest encryption: public class TestEncrypt {

public TestEncrypt() { }

/* * * @ param strrc:strrc is the string to be encrypted * @param encName: encName is the algorithm name to be used * encname dafault to MD * @ return string */public string encrypt (string strrc string encname) {

MessageDigest md = nullString strDes = null

byte[]Bt = strrc getBytes(); try { if(encName = = null | | encName equals()){ encName = MD; } MD = message digest getInstance(enc name); Md update (Bt); strDes = bytes Hex(MD digest()); //tohexstring} catch (nosuchalgorithmexception) {system out println (invalid algorithm); Returns null} returns strDes}

Common string byteshex (byte [] BTS) {stringdes =; String tmp = nullfor(int I =; I < BTS length; i++){ tmp =(Integer to hex string(BTS[I]& amp; xFF)); if(tmp length()= =){ des+=; } des+= tmp; } return des}

public static void main(String[]args){ testen crypt te = new testen crypt(); String strSrc = can encrypt Chinese characters Oh and English; System output println (source string:+strrc); The system outputs println (encrypted string:); System output println (using def:+teencrypt (strrcnull)); System output println (using MD:+teencrypt (strrcmd)); System output println (using sha:+teencrypt (strrcsha)); System output println (using sha:+teencrypt (strrcsha)); } }

In addition, the generateGUID method in RequestHelpers in javawebparts also involves MD method codes as follows: public static string generate guid (http servlet request) {

string out =; Try {? //Construct a string containing the following contents:? //Remote IP address+Host IP address+Date (yyyyMMdd)+? //Time(hhmmsssa)+ requested path+session ID+? HashCode of ParameterMap? string buffer * * * = new string buffer(); ? * * * append(request getremote addr()); ? inet address ia = inet address getLocalHost(); ? * * * append(ia getHostAddress()); ? * * * Append (new simple date format (yyyymmdd hhmmsssa) format (new Date());); ? string path = request getServletPath(); ? string pathInfo = request getPathInfo(); ? If (pathInfo! = null){ path+= pathInfo; ? }? * * * Add (path); ? * * * append(request getSession(false)); ? * * * append(request getparameter map()hashCode()); ? string str = * * * toString(); ? //Now use MD encryption algorithm to encode the string? message digest MD = message digest getInstance(MD); ? MD update(str getBytes()); ? Byte [] digest = md digest (); ? string buffer hextr = new string buffer(); ? for(int I =; I < abstract length; i++){ str = Integer to hex string(xFF & amp; digest[I]); if(str length()& lt; ) {? str =+str; } hex str append(str); ? }? out = hex str toString(); } catch(nosuchalgorithm exception nsae){? Log error (nsae); } catch(UnknownHostException uhe){? Logarithmic error (UHE); }//Returns the encrypted string, which should be unique according to the//parts that make up the plaintext string, and it should always be//characters due to the MD algorithm return out;

} // End generateGUID()

) private key encryption

Message digest can only check the integrity of the message, and can't encrypt plaintext messages in one direction. If we want to encrypt plaintext messages, we must use other algorithms. To ensure confidentiality, we need to use private key encryption to exchange private messages.

This is best understood by a symmetric algorithm. For example, A encrypts the A file with a key and B reads the file, which requires both parties who have the same key as A to share a private key (and the private key is easily intercepted when it is transmitted in the web environment).

To encrypt with a private key, you need a key first. You can use javax crypto KeyGenerator to generate a key (java security key) and then pass it to the encryption tool (JavaX Crypto Crypto). Then, the tool uses the corresponding algorithm for encryption. The main symmetric algorithm is DES (the actual key has only bits) AES (supporting three key length bits). Usually, the first bit and other jdk types (such as DESede) also provide support for symmetric algorithms. The following example uses AES algorithm for encryption.

/* * * private exmaple Java * Copyright */import javax crypto Cipher; Import javax encryption key generator; Import java security key;

/* * * Private encryption ensures message confidentiality */public class private example {public static void main (string [] args) throwsexception {if (argslength! = ){ System err println (usage: java PrivateExample & lttext & gt); System exit (); } byte[]platext = args[]getBytes(UTF);

//form a key system outside println (\ nstart generate aeskey) through KeyGenerator; key generator key gen = key generator getInstance(AES); keyGen init(); key key = key gen generate key(); The system outputs println (DES key generation is completed);

//Obtaining the private encryption password ECB is filled by the encryption method PKCS, and the filling method cipher cipher = cipher getinstance (AES/ECB/PKCS filling); system out println(\ n+cipher get provider()getInfo());

//Use private encryption system Outprintln (\ nstart encryption:); Password initialization (password encryption mode key); Byte[] ciphertext =cipher doFinal (plaintext); The system outputs println (encryption completed:); The system outputs println (new string (ciphertext UTF)););

System output println (\ nDecryption started:); Password initialization (password decryption mode key); Byte [] new plaintext = cipher do final (ciphertext); The system outputs println (decryption completed:);

The system outputs println (new string (new plaintext UTF)););

} }

) public key encryption

As mentioned above, private key encryption requires a * * * shared key, so how to transfer the key? If it is transmitted directly in the web environment, it is easy to be intercepted. Fortunately, with the emergence of public key encryption, public key encryption is also called asymmetric encryption. Asymmetric algorithm uses a pair of keys to pair the public key and the private key. Only the private key can decrypt the data encrypted with the public key (which can be used for encryption). At the same time, only the public key can decrypt the data encrypted with the private key (signature), but the speed is very slow (twice as slow as private key encryption). The main algorithms of public key are RSA and jdk, such as Blowfish Diffie Helman, which provides support for RSA and is an improvement.

/* * * publiceexamplejava * copyright */importjava security key; Import javax encryption password; Import java security key pair generator; Import java security key pair; /* * * Simple example of public encryption Crypter class uses the public and private passwords generated by KeyPairGenerator */public class to disclose examples {public static void main (string [] args) throwsexception {if (argslength! = ){ System err println (usage: java PublicExample & lttext & gt); System exit (); }

byte[]plainText = args[]getBytes(UTF); //form an RSA key system out println (\ nstart gene rating RSA key); KeyPairGenerator keyGen = KeyPairGenerator getInstance(RSA); keyGen initialize(); key pair key = keyGen generateKeyPair(); The system outputs println (RSA key generation is completed);

//Get a password class of RSA, and use the public encryption password cipher = cipher getinstance (filled by RSA/ECB/PKCS); system out println(\ n+cipher get provider()getInfo());

system out println(\ nStart encryption); Cipher init(Cipher ENCRYPT _ MODE key getPublic()); Byte[] ciphertext =cipher doFinal (plaintext); The system outputs println (encryption completed:); The system outputs println (new string (ciphertext UTF)););

Lishi Xinzhi/Article/program/Java/hx/20 13 1 1/26898