RSA algorithm (encryption and decryption)

RSA algorithm introduction:

        The RSA algorithm is the RSA encryption algorithm, which is an asymmetric encryption algorithm . RSA is widely used in public key encryption and electronic commerce . RSA 1977 by the Ronald Rivest (Ron Rivest), Adi Shamir (Adi Shamir) and Leonard Adleman (Leonard Adleman) presented together. RSA is made up of the letters of the three of them. In 1973, Clifford Cocks, a mathematician working at the British government ’s communications headquarters , proposed an identical algorithm in an internal document, but his findings were classified as confidential until 1997. Publish. RSA is a very influential public key encryption algorithm now. It can resist most of the known cryptographic attacks. It has been recommended by ISO as a public key data encryption standard. As of 2008, there is no reliable way to attack the RSA algorithm in the world. As long as the length of the key is long enough, the information encrypted with RSA cannot actually be broken. 

speed:

Because all the calculations are large numbers, the fastest RSA situation is several times slower than DES, whether it is implemented in software or hardware. Speed ​​has always been a drawback of RSA. Generally only used for a small amount of data encryption. The speed of RSA is about 1000 times slower than the symmetric cryptographic algorithm corresponding to the same security level.

safety:

The security of RSA depends on the decomposition of large numbers, but whether it is equivalent to the decomposition of large numbers has not been theoretically proven, because there is no proof that the decomposition of RSA requires large number decomposition. Suppose there is an algorithm that does not need to decompose large numbers, then it can certainly be modified into a large number decomposition algorithm. Some variants of RSA have been proven to be equivalent to large number decomposition. In any case, factoring n is the most obvious attack method. People have been able to resolve large prime numbers with multiple decimal places. Therefore, the modulus n must be chosen larger, depending on the specific application.

                                                                                                                                                               ------ The above content is taken from Sogou Encyclopedia

Code:

package com.huadian.encrytionanddecrytion;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Scanner;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class RSA { 
        / ** 
         * encryption 
         * 
         * @param content 
         * content to be encrypted 
         * @param password 
         * encryption password 
         * @return 
         * / 
        public static byte [] encrypt (String content, String password) { 
            try { 
                KeyGenerator kgen = KeyGenerator.getInstance ("AES"); 
                kgen.init (128, new SecureRandom (password.getBytes ())); 
                SecretKey secretKey = kgen.generateKey (); 
                byte [] enCodeFormat = secretKey.getEncoded (); 
                SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
                Cipher cipher = Cipher .getInstance ("AES"); // Create a cipher
                byte[] byteContent = content.getBytes("utf-8");
                cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
                byte[] result = cipher.doFinal(byteContent);
                return result; // 加密
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IllegalBlockSizeException e) {
                e.printStackTrace();
            } catch (BadPaddingException e) {
                e.printStackTrace();
            }
            return null;
        }
/**
 * 解密
 *
 * @param content
 *            待解密内容
 * @param password
 *            解密密钥
 * @return
 */
public static byte[] decrypt(byte[] content, String password) {
    try {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128, new SecureRandom(password.getBytes()));
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES");// 创建密码器
        cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(content);
        return result; // 加密
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    }
    return null;
}
/**
 * 将二进制转换成16进制
 *
 * @param buf
 * @return
 */
public static String parseByte2HexStr(byte buf[]) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < buf.length; i++) {
        String hex = Integer.toHexString(buf[i] & 0xFF);
        if (hex.length() == 1) {
            hex = '0' + hex;
        }
        sb.append(hex.toUpperCase());
    }
    return sb.toString();
}
/**
 * 将16进制转换为二进制
 *
 * @param hexStr
 * @return
 */
public static byte[] parseHexStr2Byte(String hexStr) {
    if (hexStr.length() < 1)
        return null;
    byte[] result = new byte[hexStr.length() / 2];
    for (int i = 0; i < hexStr.length() / 2; i++) {
        int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
        int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
        result[i] = (byte) (high * 16 + low);
    }
    return result;
}
/**
 * 加密
 *
 * @param content
 *            需要加密的内容
 * @param password
 *            加密密码
 * @return
 */
public static byte[] encrypt2(String content, String password) {
    try {
        SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
        byte[] byteContent = content.getBytes("utf-8");
        cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(byteContent);
        return result; // 加密
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    }
    return null;
}
 public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println("请输入要加密的内容和密码");
        System.out.println("请输入要加密的密码");
        Scanner scanner = new Scanner(System.in);
        String content = scanner.next();
        String password = scanner.next();

       // String content = "我是shoneworn";
       // String password = "12345678";
        // 加密
        System.out.println("加密前:" + content);
        byte[] encode = encrypt(content, password);

        //传输过程,不转成16进制的字符串,就等着程序崩溃掉吧
        String code = parseByte2HexStr(encode);
        System.out.println("密文字符串:" + code);
        byte[] decode = parseHexStr2Byte(code);
        // 解密
        byte[] decryptResult = decrypt(decode, password);
        System.out.println("解密后:" + new String(decryptResult, "UTF-8")); //不转码会乱码

    }
}
发布了105 篇原创文章 · 获赞 536 · 访问量 7万+

Guess you like

Origin blog.csdn.net/qq_41934990/article/details/81872715