Current location - Quotes Website - Signature design - Digital signature based on java language
Digital signature based on java language
Graduation design takes at least 2 months. You just start now, it's too late to copy and paste ~

A quick introduction to Java encryption and digital signature programming

This paper mainly discusses encryption and digital signature in cryptography, and how to use them in java. Partners interested in cryptography are recommended to read Bruce Schneier's book: Applied Cryptography. In the release version of jdk 1.5, the security has been greatly improved, and it also provides direct support for RSA algorithm. Now we use examples to solve the problem (this article is just a brief introduction):

First, the commonly used concepts in cryptography

1) Message summary:

This is a technology used in combination with message authentication code to ensure message integrity. The one-way hash function algorithm is mainly used, and the integrity of the message can be checked through the hash password, and it can be saved directly in the form of text. At present, the widely used algorithms are MD4, MD5, SHA- 1, jdk 1.5, all of which provide support. It is very simple to summarize messages in java, and java.security.MessageDigest provides a simple operation method:

/**

*MessageDigestExample.java

* Copyright 2005-2- 16.

*/

Import java.security.messagedigest;

/**

* Single message digest algorithm, no password. It can be used to hide and save plaintext messages (such as passwords).

*/

Public class messagedigest sample {

The public static void main(String[] args) throws an exception {

if(args.length! = 1){

System.err.println ("usage: Java message digest sample text");

system . exit( 1);

}

Byte[] plaintext =args[0]. getBytes(" UTF8 ");

//getInstance ("algorithm") is used to get the message digest, and the 160 bit algorithm of SHA- 1 is used here.

message digest message digest = message digest . getinstance(" SHA- 1 ");

system . out . println(" \ n "+message digest . get provider()。 getInfo());

//Start using the algorithm

MessageDigest.update (plain text);

system . out . println(" \ n digest:");

//Output the operation result of the algorithm

System.out.println (new string (messageDigest.digest (), "utf8");

}

}

You can also encrypt it with a message authentication code. Javax.crypto.Mac provides a solution. Interested parties can refer to relevant API documents. This article just briefly introduces what is summarization algorithm.

2) private key encryption:

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

This can be well understood by using symmetric algorithm. For example, A encrypts a file with a key, but B needs the same key as A to read the file, and both parties share a private key (in the web environment, the private key is easily intercepted during transmission):

If you use private key encryption, you need a key first. You can use javax.crypto.KeyGenerator to generate a key (java.security.Key), and then pass it to an encryption tool (javax.crypto.Cipher), which uses the corresponding algorithm for encryption. The main symmetric algorithms are: DES (the actual key is only 56 bits). AES (supports three key lengths: 128 and192,256 bits), usually with 128 bits first. Others such as DESede, jdk 1.5 also provide support for symmetric algorithms. The following example uses AES algorithm for encryption:

/**

*PrivateExmaple.java

* Copyright 2005-2- 16.

*/

Import javax.crypto.cipher;

Import javax.crypto.keygenerator;

Import java.security.key;

/**

* Private encryption to ensure the confidentiality of information.

*/

public class PrivateExample{

The public static void main(String[] args) throws an exception {

if(args.length! = 1){

System.err.println ("usage: Java private example < text >;" );

system . exit( 1);

}

Byte[] plaintext =args[0]. getBytes(" UTF8 ");

//A key is formed by a key generator.

System. out.println ("\ nStart generating AES key");

key generator key gen = key generator . getinstance(" AES ");

keygen . init( 128);

key key = key gen . generate key();

System.out.println ("complete generation of DES key");

//Get the private encryption password, where ECB is the encryption method and PKCS5Padding is the padding method.

cipher cipher = cipher . getinstance(" AES/ECB/pkcs 5 padding ");

system . out . println(" \ n "+cipher . get provider()。 getInfo());

//Use private encryption

system . out . println(" \ n start encryption:");

Cipher.init (password. ENCRYPT_MODE,key);

Byte[] ciphertext =cipher.doFinal (plaintext);

System.out.println ("complete encryption:");

System.out.println (new string (ciphertext, "utf8");

System.out.println("\nStart decryption: ");

Cipher.init (password. DECRYPT_MODE,key);

Byte [] newplaintext = cipher.dofinal (ciphertext);

System.out.println ("Decryption completed:");

System.out.println (newPlainText, "utf8");

}

}

3) public key encryption:

As mentioned above, private key encryption requires a * * * shared key, so how to pass the key? In the web environment, direct delivery is easy to be intercepted, but fortunately, public key encryption has emerged. Public key encryption is also called asymmetric encryption. Asymmetric algorithm uses a pair of key pairs, a public key and a private key. Only the private key can unlock the data encrypted by the public key (the public key can be used for encryption). At the same time, data encrypted with private key can only be decrypted (signed) with public key. But the speed is very slow (slower than private key encryption 100 to 1000 times). The main algorithms of public key are RSA, Blowfish, Diffie-Helman and so on. Jdk 1.5 provides support for RSA, which is an 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 example of public encryption. The Cipher class uses public and private encryption generated by the KeyPairGenerator.

*/

Public class publiceexample {

The public static void main(String[] args) throws an exception {

if(args.length! = 1){

System.err.println ("usage: Java public example < text >;" );

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);

key pair key = keygen . generatekeypair();

System.out.println ("RSA key generation completed");

//Get an RSA password class and use public encryption.

cipher cipher = cipher . getinstance(" RSA/ECB/pkcs 1 padding ");

system . out . println(" \ n "+cipher . get provider()。 getInfo());

System. out.println ("\ nStart encryption");

Cipher.init (password. ENCRYPT_MODE,key . getpublic());

Byte[] ciphertext =cipher.doFinal (plaintext);

System.out.println ("complete encryption:");

System.out.println (new string (ciphertext, "utf8");

//Use private encryption to decrypt.

System.out.println("\nStart decryption ");

Cipher.init (password. DECRYPT_MODE,key . get private());

Byte [] newplaintext = cipher.dofinal (ciphertext);

System.out.println ("Decryption completed:");

System.out.println (newPlainText, "utf8");

}

}

4) Digital signature:

Digital signature, which is the first level to determine the identity of the communication party who exchanges messages. Above, A encrypts the data with the public key and sends it to B, and B decrypts it with the private key to get the required data. Here comes the problem. Since they are all encrypted with public keys, how to check the messages sent by A? As mentioned above, the private key is unique, so A can be encrypted with A's own private key, and then B can be decrypted with A's public key. The principle of digital signature is based on this, and usually in order to prove the authenticity of the sent data, the message digest is used to obtain the content of the short message, and then the hash data is encrypted with the private key and sent with the message. Java provides good support for digital signature, 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, using RSA private key to sign the message digest, and then using public key authentication test.

*/

Example of Public Class Digital Signature 2 {

The public static void main(String[] args) throws an exception {

if(args.length! = 1){

System.err.println ("Usage: Java Digital Signature 2example <; Text >; " );

system . exit( 1);

}

Byte[] plaintext =args[0]. getBytes(" UTF8 ");

//form RSA public key pair

System. out.println ("\ nStart generating RSA key");

KeyPairGenerator keyGen = KeyPairGenerator . getinstance(" RSA ");

keygen . initialize( 1024);

key pair key = keygen . generatekeypair();

System.out.println ("RSA key generation completed");

//Use private signature

signature SIG = signature . getinstance(" sha 1 with RSA ");

SIG . init sign(key . get private());

Sig.update (plaintext);

byte[]signature = SIG . sign();

system . out . println(SIG . get provider()。 getInfo());

system . out . println(" \ n signature:");

System.out.println (new string (signature, "utf8");

//Use public authentication

System. out.println ("\ nStart signature verification");

SIG . init verify(key . getpublic());

Sig.update (plaintext);

Try {

if(sig.verify(signature)){

System.out.println ("signature verification");

}else System.out.println ("signature failed");

}catch(SignatureException e){

System.out.println ("signature failed");

}

}

}

5) Digital certificate.

Another problem is the public key problem. A is encrypted with the private key, so after receiving the message, B decrypts it with the public key provided by A; So now there is an annoying C who intercepts the message, encrypts it with his private key, and then sends his public key to B, telling B that this is A's public key. As a result ... at this time, an intermediary agency is needed to speak (I believe in authority, and I am right), and a certification authority (that is, CA) appears. Famous CA institutions include Verisign, etc. At present, the industrial standard of digital authentication is:

Digital certificate: It encapsulates the identity and the public key, and is digitally signed by a third party called a certificate authority (CA).

Keystore: The Java platform provides you with a keystore, which is used as a repository of keys and certificates. In fact, the keystore is a name. By default, it is the keystore (there is an option to make it an encrypted file). Keys and certificates can have names (called aliases) and each alias is protected by a unique password. The keystore itself is also password protected; You can choose to have each alias password match the master keystore password.

Using the tool keytool, let's do a self-certification thing (trust my certification):

1, by default, create a keystoretool-genkey-v-alias feiUserKey-keyalg RSA (the keystore file in the C: \ documents and settings \ directory for Windows system) in your home directory, and create a self-signed certificate with the alias feiuserkey generated by RSA algorithm. If -keystore mm is used, a keystore mm file is created in the current directory to save keys and certificates.

2. View certificates: keytool -list lists all certificates in the keystore.

You can also enter keytool -help in dos to view help.

Second, the signature of the jar.

Now that we have learned how to create our own certificates, we can begin to understand how to sign jar files, which is equivalent to ZIP files in Java. It allows multiple Java class files to be packaged into a file with an extension of. JAR, and then this JAR file can be digitally signed to verify its source and authenticity. The receiver of JAR file can decide whether to trust the code according to the sender's signature, and can be sure that the content has not been tampered with before receiving it. At the same time, in deployment, by placing access control statements in the policy file, access rights to machine resources can be allocated according to the signer's identity. In this way, some small applications can have security check access.

You can use the jarsigner tool to sign jar files:

Now suppose we have a Test.jar file (which can be generated using jar command-line tools):

Jarsigner Test.jar feiUserKey (here we created the certificate with the above alias). Please enter jarsigner for help for details.

Verify its authenticity: jarsigner -verify Test.jar (note, verify whether the jar has been modified, but do not check the reduction. If you add new content, you will also be prompted, but you will not be prompted if you reduce it. )

When using applets:

Thirdly, SSL secure socket layer and TLS transport layer are secure.

Secure Sockets Layer and Transport Layer Security are protocols for establishing secure communication channels between clients and servers. It is also used to authenticate servers for clients and (less commonly) to authenticate clients for servers. This protocol is common in browser applications, and the lock at the bottom of the browser window indicates that SSL/TLS is valid:

1) using SSL/TLS (usually using SSL. SSLServerSocketFactory class), which provides a good factory class of SSLServerSocker, and readers who are familiar with Socket programming can practice it. After writing to the server, enter ssl.keystore = keystore (when creating a certificate, the name should be the host name, such as localhost) and javax.net.ssl.keystorepassword = your password in the browser.