From: Http://hi.baidu.com/zhy65991/blog/item/0a663172b039321a8601b0e4.html Usually, the encryption algorithm used is relatively simple and efficient, the key is short, encryption and decryption speed, deciphering extremely difficult. This paper introduces the use of Md5/sha1,dsa,desede/des,diffie-hellman.
1th Chapter Basic Knowledge
1.1. One-Key cipher system
Single-key cryptosystem is a traditional encryption algorithm, which means that the sender and receiver of the information together use the same key to decrypt.
In general, the encryption algorithm used is relatively simple and efficient, key short, encryption and decryption speed, deciphering extremely difficult. But the security of encryption relies on the security of key custody, it is a serious problem to transmit and keep the key securely on the open computer network, and if the security of the key is also a problem in the case of multi-user.
The single-key cryptosystem is represented by the United States des
1.2. Message Digest
A message digest is a digital fingerprint of a block of data. That is, a data block of any length is computed to produce a unique fingerprint (for SHA1 is to produce a binary array of 20 bytes).
The message digest has two basic attributes: two different messages are difficult to generate the same digest it is difficult to generate a message for the specified digest, and the message is extrapolated from the specified summary
Representative: SHA1 of the American Institute of National Standards and technology and Ronald Rivest of MIT MD5
1.3. Diffie-hellman Key Agreement
The key agreement is an idea proposed by the founder of Diffie and Hellman of public key cryptography.
Prerequisites, allowing two users to exchange information on the public media to generate a "consistent", sharable key
Representative: Exponential key agreement (exponential key agreement Protocol)
1.4. Asymmetric algorithms and public key systems
In the 1976, Dittie and Hellman to solve key management problems, in their groundbreaking work "new Direction of cryptography", a key exchange protocol, which allows the exchange of information between the two sides of the communication in the insecure media, securely transmits secret keys. On the basis of this new idea, the asymmetric key cryptosystem, that is, public key cryptosystem, is quickly appearing. In the public key system, the encryption key is different from the decryption key, and the encryption key is publicly available to anyone, and the decryption key is only known to the decrypted person. They are known as public keys and secret keys (private key), respectively.
The RSA system is one of the most famous and most used in all public key cryptography systems to date. The RSA public key cryptography system was proposed by Professor R.rivest, A.shamir and L.adleman in 1977. RSA's name is the first letter from the surname of the three inventors.
1.5. Digital signature
The so-called digital signature is the information sender with its private key to extract from the message of the feature data (or digital fingerprint) to carry out the RSA algorithm operation, in order to ensure that the sender can not deny the message has been sent (that is, non-repudiation), but also to ensure that information messages are signed at the end of tampering (that is, integrity). When the receiver receives the message, it can verify the digital signature with the sender's public key.
The digital fingerprint which plays an important role in digital signature is generated by a kind of special hash function (hash function). The special requirements for these hash functions are: the input message data is not limited to the length, and the output of the fixed length (digital fingerprint) of any input message data can be easily calculated from the message. It is difficult to generate a message for the specified digest, and the specified digest is inferred from the message; Two different messages are difficult to generate the same summary
Representative: DSA
|
Back to the top of the page |
|
The implementation of the 2nd chapter in Java
2.1. Related
The Diffie-hellman key agreement and DES programs require support from the JCE tool Library, which can be downloaded to http://java.sun.com/security/index.html and installed. Simple installation of the jce1.2.1\lib under the copy of all the content under%java_home%\lib\ext, if there is no ext directory set up, and then add Jce1_2_1.jar and Sunjce_provider.jar to the classpath, For more details please see the corresponding user manual
2.2. Message digest use of MD5 and Sha
How to use:
First, the calculation method is determined by generating a messagedigest class.
Java.security.MessageDigest alga=java.security.messagedigest.getinstance ("SHA-1");
Add information to calculate a summary
Alga.update (Myinfo.getbytes ());
Calculate the summary
Byte[] Digesta=alga.digest ();
Send to other people your information and summary
Others initialize with the same method, add information, and finally compare the same summary
Algb.isequal (Digesta,algb.digest ())
Related AIP
Java.security.MessageDigest class
Static getinstance (String algorithm)
Returns a MessageDigest object that implements the specified algorithm
Parameters: algorithm name, such as SHA-1 or MD5
void update (Byte input)
void update (byte[] input)
void update (byte[] input, int offset, int len)
Add information to calculate a summary
Byte[] Digest ()
Completes the calculation, returns the computed summary (for MD5 is 16-bit, SHA is 20-bit)
void Reset ()
Reset
Static Boolean isequal (byte[] digesta, byte[] digestb)
Whether the two summary of the effect is the same
Code:
Import java.security.*;
public class Mydigest {public static void main (string[] args) {mydigest my=new mydigest ();
My.testdigest ();
public void Testdigest () {try {String myinfo= ' my Test information ';
Java.security.MessageDigest alg=java.security.messagedigest.getinstance ("MD5");
Java.security.MessageDigest alga=java.security.messagedigest.getinstance ("SHA-1");
Alga.update (Myinfo.getbytes ());
Byte[] Digesta=alga.digest ();
SYSTEM.OUT.PRINTLN ("This information abstract is:" +byte2hex (Digesta)); Pass a certain way to other people your information (MyInfo) and summary (Digesta) each other can determine whether to change or transfer the normal java.security.MessageDigest algb=
Java.security.MessageDigest.getInstance ("SHA-1");
Algb.update (Myinfo.getbytes ());
if (Algb.isequal (Digesta,algb.digest ())) {System.out.println ("normal information checking");
else {System.out.println ("abstract is not the same");
The catch (Java.security.NoSuchAlgorithmException ex) {System.out.println ("Illegal Digest Algorithm"); }} public String byTe2hex (byte[] b)//Two line spin string {string hs= "";
String stmp= "";
for (int n=0;n<b.length;n++) {stmp= (java.lang.Integer.toHexString (b[n) & 0XFF));
if (Stmp.length () ==1) hs=hs+ "0" +STMP;
else hs=hs+stmp;
if (n<b.length-1) hs=hs+ ":";
return Hs.touppercase (); }
} |
2.3. Digital Signature DSA
For a user to first generate his key pair, and separately save
Generate a Keypairgenerator instance
Java.security.KeyPairGenerator keygen=java.security.keypairgenerator.getinstance ("DSA");
If a random generator is set, the
securerandom secrand=new securerandom () is initialized with the phase code;
Secrand.setseed ("Tttt". GetBytes ()); Initialization of a random generator
keygen.initialize (512,secrand); Initialize the key generator
otherwise
keygen.initialize ();
Generate key Public key PubKey and private key Prikey
KeyPair Keys=keygen.generatekeypair ();//Generate key Group
PublicKey pubkey=keys.getpublic ();
Privatekey prikey=keys.getprivate ();
stored in Myprikey.dat and Mypubkey.dat, respectively, so that the next time it is not generated
(the generation of the key pair is longer
Java.io.ObjectOutputStream out=new Java.io.ObjectOutputStream (New Java.io.FileOutputStream ("Myprikey.dat"));
Out.writeobject (Prikey);
Out.close ();
Out=new Java.io.ObjectOutputStream (New Java.io.FileOutputStream ("Mypubkey.dat"));
Out.writeobject (PubKey);
Out.close (); |
Use his private key (Prikey) to digitally sign the information he confirms (info) to produce a signature array
Read the private key from the file (Prikey)
Java.io.ObjectInputStream in=new Java.io.ObjectInputStream (New Java.io.FileInputStream ("Myprikey.dat"));
Privatekey myprikey= (Privatekey) in.readobject ();
In.close ();
A Signature object is initialized with a private key to sign the information
java.security.Signature signet=java.security.signature.getinstance ("DSA");
Signet.initsign (Myprikey);
Signet.update (Myinfo.getbytes ());
Byte[] Signed=signet.sign ();
Save information and signatures in a file (myinfo.dat)
java.io.ObjectOutputStream out=new Java.io.ObjectOutputStream (new Java.io.FileOutputStream ("Myinfo.dat"));
Out.writeobject (MyInfo);
Out.writeobject (signed);
Out.close ();
Send the information and signature of his public key to other users |
Other users use his public key (PubKey) and signature (signed) and information (info) to verify that the information is signed by him
Read into public key
Java.io.ObjectInputStream in=new Java.io.ObjectInputStream (New Java.io.FileInputStream ("Mypubkey.dat"));
PublicKey pubkey= (PublicKey) in.readobject ();
In.close ();
Read signatures and information
In=new Java.io.ObjectInputStream (New Java.io.FileInputStream ("Myinfo.dat"));
String info= (String) in.readobject ();
Byte[] signed= (byte[]) in.readobject ();
In.close ();
Initializes a signature object and authenticates with the public key and the signature
Java.security.Signature signetcheck=java.security.signature.getinstance ("DSA");
Signetcheck.initverify (PubKey);
Signetcheck.update (Info.getbytes ());
if (Signetcheck.verify (signed)) {System.out.println ("normal signature");}
For the preservation of the key this article is saved and transmitted in the form of an object stream, or it can be saved in an encoded way. Be careful
Import java.security.spec.*
Import java.security.*
With a Hugh note the following public key is encoded with X.509 code as follows:
Byte[] bobencodedpubkey=mypublic.getencoded (); Generate encoding
//Transfer binary encoding
//The following code conversion encoding is the corresponding Key object
x509encodedkeyspec Bobpubkeyspec = new X509encodedkeyspec ( Bobencodedpubkey);
Keyfactory keyfactory = keyfactory.getinstance ("DSA");
PublicKey Bobpubkey = Keyfactory.generatepublic (Bobpubkeyspec); |
For private key is encoded with PKCS#8, the code is as follows:
Byte[] bpkcs=myprikey.getencoded ();
Transfer binary encoding
//The following code conversion encoding for the corresponding Key object
pkcs8encodedkeyspec pripkcs8=new pkcs8encodedkeyspec (BPKCS);
Keyfactory keyf=keyfactory.getinstance ("DSA");
Privatekey otherprikey=keyf.generateprivate (priPKCS8); |
Common APIs
Java.security.KeyPairGenerator Key Generator Class
public static Keypairgenerator getinstance (String algorithm) throws NoSuchAlgorithmException
Returns a Keypairgenerator object with the specified algorithm
Parameters: Algorithm algorithm name. such as: "DSA", "RSA"
public void Initialize (int keysize)
Initializes the Keypairgenerator object at the specified length, if the system is not initialized with a 1024-length default setting
Parameter: keysize algorithm bit length. Its range must be between 512 and 1024 and must be a multiple of 64
public void Initialize (int keysize, SecureRandom random)
Initializes the Keypairgenerator object with the specified length initialization and random generator
Parameter: keysize algorithm bit length. Its range must be between 512 and 1024 and must be a multiple of 64
Random the source of a random bit (for initialize (int keysize) using the default with machine
Public abstract KeyPair Generatekeypair ()
Generate a new key pair
Java.security.KeyPair Key Pair Class
Public Privatekey getprivate ()
Return private key
Public PublicKey getpublic ()
Return public key
Java.security.Signature Signature Class
public static Signature getinstance (String algorithm) throws NoSuchAlgorithmException
Returns a Signature object that specifies the algorithm
parameter algorithm such as: "DSA"
Public final void Initsign (Privatekey privatekey)
Throws InvalidKeyException
Class with the specified private key.
Parameter: The private key used to privatekey the signature
Public final void Update (byte data)
Throws Signatureexception
Public final void Update (byte[] data)
Throws Signatureexception
Public final void Update (byte[] data, int off, int len)
Throws Signatureexception
Add the information to be signed
Public final byte[] sign ()
Throws Signatureexception
Returns an array of signatures, provided that initsign and update
Public final void Initverify (PublicKey publickey)
Throws InvalidKeyException
Class with the specified public key.
Parameters: PublicKey The public key for authentication
Public Final Boolean verify (byte[] signature)
throws Signatureexception
Verify that the signature is valid, if the
parameter is initverify initialized: Signature Signature Array
* * Import java.security.*;
Import java.security.spec.*; public class Testdsa {public static void main (string[] args) throws Java.security.nosuchalgorithmexception,java.lang.ex
ception {TESTDSA my=new testdsa ();
My.run ();
The public void Run () {//digital signature generates keys//The first step generates a key pair, and if it has been generated, the process can be skipped and myprikey.dat to the user to be saved locally//and Mypubkey.dat to the other user if ((New Java.io.File ("Myprikey.dat")). Exists () ==false) {if (GenerateKey () ==false) {System.out.println
("Generate key pair failure");
Return
};
//Step two, this user//from the file read into the private key, signed a string to be saved in a file (Myinfo.dat)//And then send the Myinfo.dat//To facilitate digital signatures are also placed in the Myifno.dat file, of course, can also be sent separately
try {java.io.ObjectInputStream in=new java.io.ObjectInputStream (New Java.io.FileInputStream ("Myprikey.dat"));
Privatekey myprikey= (Privatekey) in.readobject ();
In.close ();
Java.security.spec.X509EncodedKeySpec pubx509=new Java.security.spec.X509EncodedKeySpec (bX509); Java.security.spec.X509EncodedKeySpec pubkeyencode=java.security. Spec. X509encodedkeyspec String myinfo= "This is my message";
Information to be signed//digitally signed with the private key for the information java.security.Signature signet=java.security.signature.getinstance ("DSA");
Signet.initsign (Myprikey);
Signet.update (Myinfo.getbytes ()); Byte[] Signed=signet.sign ();
Digital signature System.out.println of information ("Signed (signature content) =" +byte2hex (signed)); Save information and digital signatures in a file Java.io.ObjectOutputStream out=new java.io.ObjectOutputStream (New Java.io.FileOutputStream ("
Myinfo.dat "));
Out.writeobject (MyInfo);
Out.writeobject (Signed);
Out.close ();
System.out.println ("Signing and generating file success");
catch (Java.lang.Exception e) {e.printstacktrace ();
System.out.println ("Signing and generating file failure");
};
The third step//the other person through public access to the user's public key and file//Other people with the public key to the file to check, if the success of the information published by the users.
try {java.io.ObjectInputStream in=new java.io.ObjectInputStream (New Java.io.FileInputStream ("Mypubkey.dat"));
PublicKey pubkey= (PublicKey) in.readobject ();
In.close ();
System.out.println (Pubkey.getformat ()); In=new Java.io.ObjectInputStream (New JAVA.io.fileinputstream ("Myinfo.dat"));
String info= (String) in.readobject ();
Byte[] signed= (byte[]) in.readobject ();
In.close ();
Java.security.Signature signetcheck=java.security.signature.getinstance ("DSA");
Signetcheck.initverify (PubKey);
Signetcheck.update (Info.getbytes ());
if (Signetcheck.verify (signed)) {System.out.println ("info=" +info);
System.out.println ("signature normal");
else System.out.println ("non-signature normal");
catch (Java.lang.Exception e) {e.printstacktrace ();}; //Generate a pair of files Myprikey.dat and Mypubkey.dat---Private and public key,//public key to send users (file, network, etc.) to other users, the private key is saved in local public boolean generatekey () {T
ry {java.security.KeyPairGenerator keygen=java.security.keypairgenerator.getinstance ("DSA");
SecureRandom secrand=new securerandom (); Secrand.setseed ("Tttt". GetBytes ()); Initialization of a random generator//Keygen.initialize (576,secrand);
Initialize the key generator keygen.initialize (512);
KeyPair Keys=keygen.genkeypair (); KeyPair Keys=keygen.generatekeypair (); Generate Key Group PublicKey pubkey=keys.geTpublic ();
Privatekey prikey=keys.getprivate ();
Java.io.ObjectOutputStream out=new Java.io.ObjectOutputStream (New Java.io.FileOutputStream ("Myprikey.dat"));
Out.writeobject (Prikey);
Out.close ();
System.out.println ("Write Object Prikeys OK");
Out=new Java.io.ObjectOutputStream (New Java.io.FileOutputStream ("Mypubkey.dat"));
Out.writeobject (PubKey);
Out.close ();
System.out.println ("Write Object Pubkeys OK");
SYSTEM.OUT.PRINTLN ("Generate key pair success");
return true;
catch (Java.lang.Exception e) {e.printstacktrace ();
SYSTEM.OUT.PRINTLN ("Generate key pair failed");
return false;
};
public string Byte2hex (byte[] b) {string hs= "";
String stmp= "";
for (int n=0;n<b.length;n++) {stmp= (java.lang.Integer.toHexString (b[n) & 0XFF));
if (Stmp.length () ==1) hs=hs+ "0" +STMP;
else hs=hs+stmp;
if (n<b.length-1) hs=hs+ ":";
return Hs.touppercase (); }
} 2.4. Desede/des symmetric algorithm first generates the key, and saves (here is not the saved code, may refer to the DSA method) Keygenerator keygen = keygenerator.getinstance (algorithm);
Secretkey Deskey = Keygen.generatekey ();
Encrypt plaintext (MyInfo) with key, generate ciphertext (cipherbyte) Cipher C1 = cipher.getinstance (algorithm);
C1.init (Cipher.encrypt_mode,deskey);
Byte[] Cipherbyte=c1.dofinal (Myinfo.getbytes ());
Send ciphertext and key, this article does not have the corresponding code to refer to DSA ...
Using key to decrypt the text C1 = cipher.getinstance (algorithm);
C1.init (Cipher.decrypt_mode,deskey);
Byte[] Clearbyte=c1.dofinal (cipherbyte); Relatively speaking, the use of symmetric keys is very simple, for the JCE Des,desede,blowfish three encryption for the key to save each transmission can use object flow or binary code, the relevant reference code as follows Secretkey Deskey =
Keygen.generatekey ();
Byte[] desencode=deskey.getencoded ();
Javax.crypto.spec.SecretKeySpec destmp=new Javax.crypto.spec.SecretKeySpec (desencode,algorithm);
Secretkey mydeskey=destmp;
The relevant API Keygenerator has been shown in DSA that the following parameters can be DES,DESEDE,BLOWFISH,HMACMD5,HMACSHA1 javax.crypto.Cipher Add/Decrypt after adding JCE instance
public static final Cipher getinstance (java.lang.String transformation) Throws Java.security.NoSuchAlgorithmException, Nosuchpaddingex Ception returns a cipher object parameter for the specified method: Transformation method Name (available des,desede,blowfish) public final void init (int opmode, Java.securit Y.key key) throws Java.security.InvalidKeyException initializes cipher object parameters with the specified key and schema: Opmode (Encrypt_mode, Decrypt_mode, WRAP _mode,unwrap_mode) key key public final byte[] dofinal (byte[] input) throws Java.lang.IllegalStateE Xception, illegalblocksizeexception, badpaddingexception on input Within the string, code processing, return processing binary string, is to return the decryption text or add the text by the Init when the Opmode decided to note: This method before the implementation if there is update, is updat and this input all processing, otherwise it is the content of the inout/* Security Procedures
Desede/des Test * * Import java.security.*;
Import javax.crypto.*;
public class Testdes {public static void main (string[] args) {testdes my=new testdes ();
My.run (); public void Run () {//Add a new security algorithm and add it to the JCE if you use it Security.addprovider (new com.sun.crypto.provideR.sunjce ()); String algorithm= "DES";
Defines an encryption algorithm that can be used des,desede,blowfish String myinfo= "to encrypt information";
try {//generate key Keygenerator keygen = keygenerator.getinstance (algorithm);
Secretkey Deskey = Keygen.generatekey ();
Encrypted System.out.println ("binary string Before encryption:" +byte2hex (Myinfo.getbytes ()));
System.out.println ("Pre-encrypted information:" +myinfo);
Cipher C1 = cipher.getinstance (algorithm);
C1.init (Cipher.encrypt_mode,deskey);
Byte[] Cipherbyte=c1.dofinal (Myinfo.getbytes ());
SYSTEM.OUT.PRINTLN ("Encrypted binary string:" +byte2hex (Cipherbyte));
Decryption C1 = cipher.getinstance (algorithm);
C1.init (Cipher.decrypt_mode,deskey);
Byte[] Clearbyte=c1.dofinal (cipherbyte);
SYSTEM.OUT.PRINTLN ("Decrypted binary string:" +byte2hex (Clearbyte));
SYSTEM.OUT.PRINTLN ("decrypted message:" + (new String (Clearbyte));
catch (Java.security.NoSuchAlgorithmException E1) {e1.printstacktrace ();}
catch (javax.crypto.NoSuchPaddingException E2) {e2.printstacktrace ();} catch (Java.lang.Exception E3) {E3.printstacktracE ();}
public string Byte2hex (byte[] b)//Two line spin string {string hs= "";
String stmp= "";
for (int n=0;n<b.length;n++) {stmp= (java.lang.Integer.toHexString (b[n) & 0XFF));
if (Stmp.length () ==1) hs=hs+ "0" +STMP;
else hs=hs+stmp;
if (n<b.length-1) hs=hs+ ":";
return Hs.touppercase (); } 2.5. Diffie-hellman key Agreement public Key cryptography founder Diffie and Hellman proposed "exponential key agreement" (exponential key agreement Protocol), which does not require |