Java password
(Shi Den, Idealist@gcn.net.tw)
1. Password profile - encryption and decryption
Encryption is a process that will be encrypted with some mathematical operations into a group of things that can't understand; decryption is the process of converting an encrypted text back to the original text. During this process, the mathematical algorithm that plays the transition between the original text and the encrypted text is called Cipher.
Figure 1 Most of the working modern cipher in Cipher will use Key to encrypt and decrypt data. The so-called key refers to a confidential value, we can treat it as a password. Encrypted text must use the descent key to decrypt as the original text.
A. Symmetrical Cipher
The symmetrical Cipher is the same as the key used by the transmitting end and the receiving end, as shown in FIG. 2, the symmetrical Cipher is also called Private Key Cipher, because the value of Key only knows the transfer end and the receiving end. If a third party knows the Private Key value, you can solve the encrypted information.
Figure 2 Operation of symmetrical Cipher B. Asymmetric Cipher
Asymmetric Cipher is also called Public Key Cipher, Cipher In addition to Private Key, it will introduce a public key that can be distributed. The information encrypted by the public key is only the relatively reflected Private Key can be unwrapped, and the same data encrypted by Private Key is only the relatively reflected public key can be unpredictable. As shown in FIG. 3, the operation process of the asymmetric Cipher is shown.
Figure 3 Operation of non-symmetrical Cipher C. Message Digest
The message summary is a special number to calculate from a set of input data, which operates like Hash Function. In the application of cryptography, it is generally used to verify that the data is tampered.
2. JCE download
Because of the limitations of US regulations, Sun only provides a few encryption methods in JDK, and most of the remaining parts are only available in SunJCE, and SunJCE's API limits only the United States, Canada can be downloaded. Table 1 Encrypted algorithm for SUN and SunJCE respectively.
name
Pattern
Sun
MD5
Message summary
SHA-1
Message summary
DSA
signature
Sunjce
HMACMD5
Mac
Hmacsha1
Mac
DES
Symmetrical Cipher
DeSede
Asymmetric Cipher
Pbewithmd5anddes
Symmetrical Cipher
DH
KEY exchange
Table 1 Sun and SunJCE supported encryption algorithm Although the US regulations have such a defined, it has already made JCE in the United States, and can be downloaded directly on the Internet, Table 2 is a list of download URLs.
Kit
Website
free
JCE
http://java.sun.com/products/jdk/1.2/jce/
Yes
Cryptix
http://www.cryptix.org/
Yes
IAik
http://wwwjce.iaik.tu-graz.ac.at/
no
Table 2 JCE Software Download URL
3. JCE installation
Unzip into the JDK directory set classpath = c: /jdk/bin/cryptix-jce-api.jar; c: /jdk/bin/cryptix-jce-compat.jar; C: / JDK / BIN / CRYPTIX-JCE- Provider.jar ... Join security.Provider.1 = sun.security.provider.sun in JDK / lib / security / java.security (original) security.provider.2 = cryptix.jce.Provider.cryptix (join )
4. Example
Before an example, I first complete a public category, used to convert a string into a hexadecimal representation.
PUBLIC CLASS MSG {
Public static string tohexstring (byte [] b) {stringbuffer hexstring = new stringbuffer ();
String plaintext;
For (int i = 0; i Plaintext = integer.tohexstring (0xFF & B [i]); IF (plaintext.length () <2) { PlainText = "0" plaintext; } HEXSTRING.APpend (Plaintext); } Return HexString.toString (); } } 5. Information summary (Message Digest, as an example of SHA1) Steps to generate a message summary: Call GetInstance gets the MessageSt entity call update to feed the information to the MessageDigest call Digest generation message summary Import java.security. *; Public Class Sha Extends Object { Public static void main (string [] args) Throws Exception { MessageDigest Md = MessageDigest.getInstance ("SHA"); Md.Update (Args [0] .getbytes ()); Byte [] Digest = md.digest (); System.out.println (msg.tohexstring (digest)); } } PS. When comparing whether the two message summary is the same, you can call ISEQUAL. 6. Message Certification Code (Mac, take HMACSHA1 as an example) The message authentication code is just a result of the message summary, adding a key as a protection, the purpose is to make the message summary more difficult to crack. Steps to generate a message authentication code: Use the password to generate a key call GetInstance to get the MAC entity call init, initialize the Mac call Update to feed the Mac call DOFINAL to generate a message authentication code Import java.security. *; Import javax.crypto. *; Import javax.crypto.spec. *; Public class macsha { Public static void main (string [] args) { Securerandom SR = New SecurerandM (); Byte [] Keybytes = New byte [20]; Sr.NextBytes (keybytes); SecretKey Key = New SecretKeyspec (Keybytes, "HmacSha"); Try { Mac m = mac.getInstance ("hmacsha"); M.INIT (KEY); M.UPDATE (Args [0] .getbytes ()); Byte [] mac = m.dofinal (); System.out.println (Msg.tohexString (Mac)); } Catch (Exception E) { System.out.println ("Exception !!"); } } } 7. Encryption and decryption (Take DES as an example) The encryption / decryption here is a symmetrical Cipher; in the financial transaction, commonly used Cipher to add / decrypt data. The step of encryption / decryption: Generate a Cipher call GetInstance with a password to generate a CIPHER object call init setting to encrypt or decrypt encryption / decryption Import java.io. *; import java.security. *; Import javax.crypto. *; Public class pwddes { PUBLIC Static Final Int Kbuffersize = 8192; Public static void main (string [] args) throws exception { IF (args.length <4) { System.out.println ("USAGE: Cloak -e | -d Passwd InputFile OutputFile); Return; } // Get or create key. Key Key; KeyGenerator generator = keygenerator.getInstance ("des"); Generator.init (New Securerandom (Args [1] .getbytes ())); Key = generator.generateKey (); // Get a cipher object Cipher cipher = copher.getinstance ("DES / ECB / PKCS # 5"); // Encrypt or Decrypt IF (args [0] .indexof ("e")! = -1) Cipher.init (cipher.encrypt_mode, key); Else Cipher.init (cipher.decrypt_mode, key); FileInputStream in = New fileinputstream (args [2]); FileOutputStream Fileout = New FileoutputStream (Args [3]); CipherOutputStream out = new cipheroutputstream (Fileout, Cipher); Byte [] buffer = new byte [kBuffersize]; Int length; While ((Length = in.read (buffer))! = -1) Out.write (Buffer, 0, Length); In.Close (); Out.close (); } } 8. Generate a signature and certification (take DSA as an example) Digital signature is commonly used to confirm on the Internet. Procedure for generating a signature: Call GetInstance gets a signature entity call INITSIGN initializes Signature call SIGN generation signature Procedure for certification: Call GetInstance gets a signature entity call initverify Initialize Signature Call Verify Certification Sample1: Generate Private / Public Key Import java.security. *; Import java.security.Keypairgenerator; Import java.security.Keypair; Import java.io. *; PUBLIC CLASS Keypair1 { Public static void main (string [] args) { Try { Keypairgenerator genkeypair = keypairgenerator.getInstance ("DSA"); GenkeyPair.Initialize (1024, New Securerandom ()); Keypair kpkey = genkeypair.genkeypair (); PrivateKey PRKEY = kpkey.getprivate (); Publickey pukey = kpkey.getpublic (); ObjectOutputStream Osprivate = New ObjectOutputStream (New FileoutputStream ("D: //private.key"); ObjectOutputStream Ospublic = New ObjectOutputStream (New FileoutputStream ("D: //public.key"); Osprivate.writeObject (prkey); Ospublic.writeObject (pukey); Osprivate.close (); Ospublic.close (); } Catch (Exception E) { System.out.println ("Error"); } } } Sample2: Generate a signature and certification Import java.io. *; Import java.security. *; Import java.security.signature; Import java.security.cert. *; Public class gensign { Public static void main (string [] args) throws exception { String Options = args [0]; String messagefile = args [1]; String signaturefile = args [2]; Signature Signature = Signature.getInstance ("DSA"); IF (Options.indexOf ("s")! = -1) { ObjectInputStream IS = New ObjectInputStream (New FileInputStream ("D: //Private.Key)); PrivateKey PriKey = (privatekey) is.readObject (); Signature.initsign (Prikey); Is.close (); } Else { ObjectInputStream IS = New ObjectInputStream (New FileInputStream ("D: //public.key")); Publickey Pubkey = (publickey) is.readObject (); Signature.Initverify (Pubkey); Is.close (); } FileInputStream in = new fileinputstream (messagefile); Byte [] buffer = new byte [8192]; Int length; While ((Length = in.read (buffer))! = -1) Signature.Update (buffer, 0, length); In.Close (); IF (Options.indexOf ("s")! = -1) { FileoutPutStream out = new fileoutputstream (signaturefile); BYTE [] RAW = Signature.Sign (); Out.write (RAW); Out.close (); } Else { FileInputStream Sigin = New FileInputStream (SignatureFile); Byte [] raw = new byte [syngin.available ()]; sigin.read (raw); Sigin.close (); IF (Signature.Verify (RAW)) System.out.Println ("The Signature Is Good."); Else System.out.println ("THE SIGNATURE IS BAD."); } } }