RSA encryption and decryption and digital signature Java implementation

Source: Internet
Author: User
Tags base64 decrypt md5 encryption asymmetric encryption


The RSA public Key cryptography algorithm was introduced in 1977 by Ronald Leevist (Ron rivest), Adi Samor (Adi Shamir) and Lennard Adman (Leonard Adleman). At the time, all three of them worked at MIT. RSA is the first letter of their three surnames made together.
RSA is the most influential public key encryption algorithm, which can resist most of the cryptographic attacks known so far, and has been recommended by ISO as a public key data encryption algorithm.
RSA algorithm is an asymmetric cryptographic algorithm, so-called asymmetric, means that the algorithm needs a pair of keys, using one of the encryption, you need to use another to decrypt.
About the principle of the RSA algorithm, here is no longer detailed introduction, a lot of resources on the Internet. The implementation of the RSA cryptographic decryption Java class is introduced below.
Import Java.security.MessageDigest;

Import Sun.misc.BASE64Decoder;
Import Sun.misc.BASE64Encoder;

public class Coder {

public static final String key_sha= "SHA";
public static final String key_md5= "MD5";

/**
* BASE64 Decryption
* @param key
* @return
* @throws Exception
*/
public static byte[] decryptBASE64 (String key) throws exception{
Return (new Base64decoder ()). Decodebuffer (key);
}

/**
* BASE64 Encryption
* @param key
* @return
* @throws Exception
*/
public static String encryptBASE64 (byte[] key) throws exception{
Return (new Base64encoder ()). Encodebuffer (key);
}

/**
* MD5 Encryption
* @param data
* @return
* @throws Exception
*/
public static byte[] EncryptMD5 (byte[] data) throws exception{
MessageDigest MD5 = messagedigest.getinstance (KEY_MD5);
Md5.update (data);
return Md5.digest ();
}

/**
* SHA Encryption
* @param data
* @return
* @throws Exception
*/
public static byte[] Encryptsha (byte[] data) throws exception{
MessageDigest sha = Messagedigest.getinstance (Key_sha);
Sha.update (data);
return Sha.digest ();
}
}
The coder encoding class is provided first, which encapsulates the basic Base64, MD5, and SHA encryption decryption algorithms. Java provides a good API encapsulation for the implementation of these algorithms, so developers can easily and conveniently encrypt and decrypt data simply by invoking these APIs.
The following provides the RSA cryptographic decryption class, which is the coder class subclass, because the RSA public-private key is saved with a layer of Base64 encryption.
RSA cryptographic decryption Class static constants
public static final String key_algorthm= "RSA";//
public static final String signature_algorithm= "Md5withrsa";

public static final String Public_key = "Rsapublickey";//
public static final String Private_key = "Rsaprivatekey";//Private key


RSA encryption decryption implementation, need to have a pair of public and private keys, the initialization of public and private keys are as follows:
/**
* Initialize key
* @return
* @throws Exception
*/
public static map<string,object> Initkey () throws exception{
Keypairgenerator keypairgenerator = keypairgenerator.getinstance (key_algorthm);
Keypairgenerator.initialize (1024);
KeyPair KeyPair = Keypairgenerator.generatekeypair ();

Public
Rsapublickey PublicKey = (rsapublickey) keypair.getpublic ();
Private
Rsaprivatekey Privatekey = (rsaprivatekey) keypair.getprivate ();

map<string,object> KeyMap = new hashmap<string, object> (2);
Keymap.put (Public_key, PublicKey);
Keymap.put (Private_key, Privatekey);

return KEYMAP;
}
It can be seen from the code that the initialization length of the key is 1024 bits, the longer the key length, the better the security, but the more time it takes to encrypt and decrypt. The length of a ciphertext that can be encrypted at a time is also proportional to the length of the key. The length of ciphertext that can be encrypted at a time is: the length of the key/8-11. So the 1024bit length of the key can be encrypted at a time cipher 1024/8-11=117bit. Therefore, asymmetric encryption is generally used to encrypt the key of the symmetric encryption algorithm, instead of encrypting the content directly. RSA encryption is available for small files, but the encryption process may still use segmented encryption.
Get the public key, private key from map
/**
* Get the public key and convert to string type
* @param keyMap
* @return
* @throws Exception
*/
public static String Getpublickey (map<string, object> keyMap) throws exception{
Key key = (key) keymap.get (Public_key);
Return encryptBASE64 (key.getencoded ());
}

/**
* Get the private key and convert to string type
* @param keyMap
* @return
* @throws Exception
*/
public static String Getprivatekey (map<string, object> keyMap) throws exception{
Key key = (key) keymap.get (Private_key);
Return encryptBASE64 (key.getencoded ());
}

For the public and private keys generated by RSA, we can encrypt and decrypt information in two ways. Private key encryption-public key decryption and public key cryptography-private key decryption.

Private key encryption
/**
* Encrypt with private key
* @param data encryption
* @param key key
* @return
* @throws Exception
*/
public static byte[] Encryptbyprivatekey (byte[] data,string key) throws exception{
Decryption key
byte[] keybytes = decryptBASE64 (key);
Take private key
Pkcs8encodedkeyspec Pkcs8encodedkeyspec = new Pkcs8encodedkeyspec (keybytes);
Keyfactory keyfactory = keyfactory.getinstance (key_algorthm);
Key Privatekey = keyfactory.generateprivate (Pkcs8encodedkeyspec);

Encrypt the data
Cipher Cipher = cipher.getinstance (Keyfactory.getalgorithm ());
Cipher.init (Cipher.encrypt_mode, Privatekey);

return cipher.dofinal (data);
}
Private key decryption
/**
* Decryption with private key * @param data encryption
* @param key key
* @return
* @throws Exception
*/
public static byte[] Decryptbyprivatekey (byte[] data,string key) throws exception{
Decrypt the private key
byte[] keybytes = decryptBASE64 (key);

Pkcs8encodedkeyspec Pkcs8encodedkeyspec = new Pkcs8encodedkeyspec (keybytes);
Keyfactory keyfactory = keyfactory.getinstance (key_algorthm);
Key Privatekey = keyfactory.generateprivate (Pkcs8encodedkeyspec);
Decryption of data
Cipher Cipher = cipher.getinstance (Keyfactory.getalgorithm ());
Cipher.init (Cipher.decrypt_mode, Privatekey);

return cipher.dofinal (data);
}
Public Key Cryptography
/**
* Encrypted with Public key
* @param data encryption
* @param key key
* @return
* @throws Exception
*/
public static byte[] Encryptbypublickey (byte[] data,string key) throws exception{
Decrypting the public key
byte[] keybytes = decryptBASE64 (key);
Take public key
X509encodedkeyspec X509encodedkeyspec = new X509encodedkeyspec (keybytes);
Keyfactory keyfactory = keyfactory.getinstance (key_algorthm);
Key PublicKey = Keyfactory.generatepublic (X509encodedkeyspec);

Decryption of data
Cipher Cipher = cipher.getinstance (Keyfactory.getalgorithm ());
Cipher.init (Cipher.encrypt_mode, PublicKey);

return cipher.dofinal (data);
}
Private key encryption
/**
* Decryption with Public key
* @param data encryption
* @param key key
* @return
* @throws Exception
*/
public static byte[] Decryptbypublickey (byte[] data,string key) throws exception{
Decrypt the private key
byte[] keybytes = decryptBASE64 (key);
X509encodedkeyspec X509encodedkeyspec = new X509encodedkeyspec (keybytes);
Keyfactory keyfactory = keyfactory.getinstance (key_algorthm);
Key PublicKey = Keyfactory.generatepublic (X509encodedkeyspec);

Decryption of data
Cipher Cipher = cipher.getinstance (Keyfactory.getalgorithm ());
Cipher.init (Cipher.decrypt_mode, PublicKey);

return cipher.dofinal (data);
}
For digital signatures, first understand what digital signatures are. Digital signature, is only the sender of information can be produced by others can not forge a string of numbers, this string is also the sender of information to send information authenticity of a valid proof. Digital signature is the application of asymmetric key encryption technology and digital Digest technology. Simply put, the so-called digital signature is attached to the data unit of some data, or to the data unit of the password transformation. This data or transformation allows the receiver of the data unit to confirm the source and data unit integrity of the data unit and to protect the data from forgery by the person (for example, the recipient).
The main functions of digital signatures are as follows:

Ensure the integrity of the transmission of information, the identity of the sender of authentication, to prevent the occurrence of repudiation in the transaction.
The technology of digital signature is to encrypt the digest information with the sender's private key and send it to the receiver with the original text. The recipient only uses the sender's public key to decrypt the encrypted digest information, and then generates a summary of the received text, which is compared to the decrypted digest information. If the same, the information received is complete, not modified during transmission, otherwise the information is modified so that the digital signature verifies the integrity of the information.
Digital signature is a process of encryption, and digital signature verification is a process of decryption.
The digital Signature algorithm relies on the public key cryptography technology to realize. In public key cryptography, each user has a pair of keys: a public key and a private key. The public key is free to publish, but the private key is kept secret, and one requirement is that it is impossible to derive the private key from the public key.
The common digital Signature algorithm consists of three kinds of algorithms:
1. Password generation algorithm;
2. Marking algorithm;
3. Verify the algorithm.
With RSA encryption and decryption algorithm, we can realize the function of digital signature. We can use the private key to generate digital signatures, and then use the public key to verify the digital signature, of course, the public key signature, the private key check.
Private key Signature

/**
* Generate digital signatures for information with the private key
* @param data//Encrypted data
* @param privatekey//private key
* @return
* @throws Exception
*/
public static String sign (byte[] data,string privatekey) throws exception{
Decrypting the private key
byte[] keybytes = decryptBASE64 (Privatekey);
Constructing Pkcs8encodedkeyspec objects
Pkcs8encodedkeyspec Pkcs8encodedkeyspec = new Pkcs8encodedkeyspec (keybytes);
Specifying the encryption algorithm
Keyfactory keyfactory = keyfactory.getinstance (key_algorthm);
Take private Key Object
Privatekey PrivateKey2 = keyfactory.generateprivate (Pkcs8encodedkeyspec);
Generating digital signatures for information with the private key
Signature Signature = signature.getinstance (signature_algorithm);
Signature.initsign (PrivateKey2);
Signature.update (data);

Return encryptBASE64 (Signature.sign ());
}
Public key Check

/**
* Verify Digital signature
* @param data encryption
* @param publickey Public key
* @param sign Digital signature
* @return
* @throws Exception
*/
public static Boolean verify (byte[] data,string publickey,string sign) throws exception{
Decrypting the public key
byte[] keybytes = decryptBASE64 (PublicKey);
Constructing X509encodedkeyspec objects
X509encodedkeyspec X509encodedkeyspec = new X509encodedkeyspec (keybytes);
Specifying the encryption algorithm
Keyfactory keyfactory = keyfactory.getinstance (key_algorthm);
Take the public key object
PublicKey PublicKey2 = Keyfactory.generatepublic (X509encodedkeyspec);

Signature Signature = signature.getinstance (signature_algorithm);
Signature.initverify (PublicKey2);
Signature.update (data);
Verifying that the signature is healthy
Return signature.verify (decryptBASE64 (sign));

}
For RSA How to encrypt files, pictures and other information, how to save the encrypted information, how to save the decrypted information, as well as the operation of the errors encountered in the process, will be introduced in the following article to everyone.


Share a spring cloud video
Follow the public number reply Springcloud get

https://my.oschina.net/jiangli0502/blog/171263

RSA encryption and decryption and digital signature Java implementation

Related Article

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.