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";p ublic static final string key_md5= "MD5";/** * BASE64 decryption * @param KEY * @return * @throws Exception */public Static byte[] decryptBASE64 (String key) throws exception{return (new Base64decoder ()). Decod Ebuffer (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";//私钥

RSA encryption decryption implementation, need to have a pair of public and private keys, the initialization of public and private keys are as follows:

/** * 初始化密钥 * @return * @throws Exception */public static Map<String,Object> initKey()throws Exception{    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORTHM);    keyPairGenerator.initialize(1024);    KeyPair keyPair = keyPairGenerator.generateKeyPair();    //公钥    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();    //私钥    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

/** * 取得公钥,并转化为String类型 * @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());     }/** * 取得私钥,并转化为String类型 * @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

/** * 用私钥加密 * @param data  加密数据 * @param key   密钥 * @return * @throws Exception */public static byte[] encryptByPrivateKey(byte[] data,String key)throws Exception{    //解密密钥    byte[] keyBytes = decryptBASE64(key);    //取私钥    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);    Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);    //对数据加密    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());    cipher.init(Cipher.ENCRYPT_MODE, privateKey);    return cipher.doFinal(data);}私钥解密

/**

    • 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);//对数据解密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE, privateKey);return cipher.doFinal(data);

      }

Public Key Cryptography

/** * 用公钥加密 * @param data  加密数据 * @param key   密钥 * @return * @throws Exception */public static byte[] encryptByPublicKey(byte[] data,String key)throws Exception{    //对公钥解密    byte[] keyBytes = decryptBASE64(key);    //取公钥    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);    Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec);    //对数据解密    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());    cipher.init(Cipher.ENCRYPT_MODE, publicKey);    return cipher.doFinal(data);}

Private key encryption

 /** * Decrypts with public key * @param data encryption * @param key key * @return * @throws Exception */public static byte[] Decryptb    Ypublickey (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);    Decrypt the data Cipher Cipher = Cipher.getinstance (Keyfactory.getalgorithm ());    Cipher.init (Cipher.decrypt_mode, PublicKey); return cipher.dofinal (data);}  

About 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 the
Digital signature are as follows:
ensure the integrity of the transmission of information, identity authentication of the sender, and prevent repudiation in the transaction. The
Digital signature technique is to encrypt the digest information with the sender's private key and send it to the receiver along with the original. 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. The
digital signature is a cryptographic process, and digital signature verification is a process of decryption. The
Digital Signature algorithm relies on public key cryptography to achieve this. 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 algorithms:
1. Password generation algorithm;
2. Tag algorithm;
3. Validation algorithm.
through the 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

/** *  用私钥对信息生成数字签名 * @param data  //加密数据 * @param privateKey    //私钥 * @return * @throws Exception */public static String sign(byte[] data,String privateKey)throws Exception{    //解密私钥    byte[] keyBytes = decryptBASE64(privateKey);    //构造PKCS8EncodedKeySpec对象    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);    //指定加密算法    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);    //取私钥匙对象    PrivateKey privateKey2 = keyFactory.generatePrivate(pkcs8EncodedKeySpec);    //用私钥对信息生成数字签名    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);    signature.initSign(privateKey2);    signature.update(data);    return encryptBASE64(signature.sign());}

Public key Check

/** * 校验数字签名 * @param data  加密数据 * @param publicKey 公钥 * @param sign  数字签名 * @return * @throws Exception */public static boolean verify(byte[] data,String publicKey,String sign)throws Exception{    //解密公钥    byte[] keyBytes = decryptBASE64(publicKey);    //构造X509EncodedKeySpec对象    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);    //指定加密算法    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);    //取公钥匙对象    PublicKey publicKey2 = keyFactory.generatePublic(x509EncodedKeySpec);    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);    signature.initVerify(publicKey2);    signature.update(data);    //验证签名是否正常    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

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.