Java encryption and decryption algorithm __ algorithm

Source: Internet
Author: User
Tags generator sha1
In general, the encryption algorithm used is relatively simple and efficient, key 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

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 transmit 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 check");
}
Else
{
SYSTEM.OUT.PRINTLN ("Abstract not identical");
}
}
catch (Java.security.NoSuchAlgorithmException ex) {
SYSTEM.OUT.PRINTLN ("Illegal Digest Algorithm");
}
}
public string Byte2hex (byte[] b)//two line turn 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.keypairgen Erator.getinstance ("DSA");
     
If a random generator is set to initialize with a phase code
SecureRandom secrand=new securerandom ();
Secrand.setseed ("Tttt". GetBytes ()); Initializes the random generator
Keygen.initialize (512,secrand); Initialize the key builder
otherwise
Keygen.initialize;
Generate key public PubKey and private key Prikey
KeyPair Keys=keygen.generatekeypair ();//Generate key Group
PublicKey Pubkey=keys.getpublic () ;
Privatekey prikey=keys.getprivate (); The
is saved in Myprikey.dat and Mypubkey.dat, so that the next time it is not built
(the time to generate 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 ();
Initializes an signature object and signs the information with the private key
Java.security.Signature signet=java.security.signature.getinstance ("DSA");
Signet.initsign (Myprikey);
Signet.update (Myinfo.getbytes ());
Byte[] Signed=signet.sign ();
Keep 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 is encoded as 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 is encoded as 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 it is already initverify initialized
Parameters: 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.exception {
TESTDSA my=new TESTDSA ();
My.run ();
}
public void Run ()
{
Digital Signature Generation Key
The first step is to generate the key pair, if it has been generated, this process can be skipped, to the user Myprikey.dat to save in the local
and Mypubkey.dat to other users
if ((New Java.io.File ("Myprikey.dat")). Exists () ==false) {
if (GenerateKey () ==false) {
SYSTEM.OUT.PRINTLN ("Generate key pair failure");
Return
};
}
In the second step, this user
Read the private key from the file, sign a string and save it in a file (Myinfo.dat)
and send the Myinfo.dat out again.
In order to facilitate the digital signature also put into 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"; The information to be signed
Generate a digital signature on information with the private key
Java.security.Signature signet=java.security.signature.getinstance ("DSA");
Signet.initsign (Myprikey);
Signet.update (Myinfo.getbytes ());
Byte[] Signed=signet.sign (); Digital signature of information
System.out.println ("Signed (signature content) =" +byte2hex (signed));
Keep 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");
};
Third Step
Other people get this user's public key and files by common means
Others use the user's public key to check the file, if the success statement is the information published by this person.
//
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 ();};
}
Generates a pair of file Myprikey.dat and Mypubkey.dat---Private and public keys.
Public key to the user to send (file, network and other methods) to other users, the private key is stored in the local
public boolean GenerateKey ()
{
try {
Java.security.KeyPairGenerator keygen=java.security.keypairgenerator.getinstance ("DSA");
SecureRandom secrand=new securerandom ();
Secrand.setseed ("Tttt". GetBytes ()); Initializing a random generator
Keygen.initialize (576,secrand); Initialize 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 ();
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.