Selaa lähdekoodia

删除RSA加密

chenweida 8 vuotta sitten
vanhempi
commit
dbda17b546
1 muutettua tiedostoa jossa 334 lisäystä ja 312 poistoa
  1. 334 312
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/util/RSAUtils.java

+ 334 - 312
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/util/RSAUtils.java

@ -20,8 +20,10 @@ import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.Date;
import javax.annotation.PostConstruct;
import javax.crypto.Cipher;
import com.yihu.wlyy.repository.security.RSADao;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
@ -36,322 +38,342 @@ import org.springframework.stereotype.Component;
/**
 * RSA算法加密/解密工具类。
 * 
 *
 * @author fuchun
 * @version 1.0.0, 2010-05-05
 */
@Component
public class RSAUtils {
	@Autowired
	private CommonUtil CommonUtil;
	private BaseService baseService;
	private static final Logger LOGGER = LoggerFactory.getLogger(RSAUtils.class);
	/** 算法名称 */
	private static final String ALGORITHOM = "RSA";
	/** 密钥大小 */
	private static final int KEY_SIZE = 1024;
	/** 默认的安全服务提供者 */
	private static final Provider DEFAULT_PROVIDER = new BouncyCastleProvider();
	private static KeyPairGenerator keyPairGen = null;
	private static KeyFactory keyFactory = null;
	/** 缓存的密钥对。 */
	private KeyPair oneKeyPair = null;
	private static RSAUtils rsaUtils = null;
	static {
		try {
			keyPairGen = KeyPairGenerator.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
			keyFactory = KeyFactory.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
		} catch (NoSuchAlgorithmException ex) {
			LOGGER.error(ex.getMessage());
		}
	}
	public synchronized static RSAUtils getInstance(BaseService baseService) {
		if (rsaUtils == null) {
			rsaUtils = new RSAUtils();
			rsaUtils.baseService = baseService;
		}
		return rsaUtils;
	}
	public KeyPair getKeyPair() {
		if (oneKeyPair == null) {
			// 从数据库加载
			RSA rsa = baseService.loadRSA();
			if (rsa == null) {
				// 生成密钥
				generateKeyPair();
			} else {
				// 由数据库取出来
				Object obj = CommonUtil.toObject(rsa.getData());
				oneKeyPair = (KeyPair) obj;
			}
		}
		return oneKeyPair;
	}
	/**
	 * 生成并返回RSA密钥对。
	 */
	private synchronized KeyPair generateKeyPair() {
		try {
			keyPairGen.initialize(KEY_SIZE, new SecureRandom(DateFormatUtils.format(new Date(), DateUtil.YYYYMMDD).getBytes()));
			oneKeyPair = keyPairGen.generateKeyPair();
			// 保存到数据库
			baseService.saveRSA(oneKeyPair);
			return oneKeyPair;
		} catch (InvalidParameterException ex) {
			LOGGER.error("KeyPairGenerator does not support a key length of " + KEY_SIZE + ".", ex);
		} catch (NullPointerException ex) {
			LOGGER.error("RSAUtils#KEY_PAIR_GEN is null, can not generate KeyPairGenerator instance.", ex);
		}
		return null;
	}
	/**
	 * 根据给定的系数和专用指数构造一个RSA专用的公钥对象。
	 * 
	 * @param modulus 系数。
	 * @param publicExponent 专用指数。
	 * @return RSA专用公钥对象。
	 */
	public RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) {
		RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent));
		try {
			return (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
		} catch (InvalidKeySpecException ex) {
			LOGGER.error("RSAPublicKeySpec is unavailable.", ex);
		} catch (NullPointerException ex) {
			LOGGER.error("RSAUtils#KEY_FACTORY is null, can not generate KeyFactory instance.", ex);
		}
		return null;
	}
	/**
	 * 根据给定的系数和专用指数构造一个RSA专用的私钥对象。
	 * 
	 * @param modulus 系数。
	 * @param privateExponent 专用指数。
	 * @return RSA专用私钥对象。
	 */
	public RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) {
		RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(new BigInteger(modulus), new BigInteger(privateExponent));
		try {
			return (RSAPrivateKey) keyFactory.generatePrivate(privateKeySpec);
		} catch (InvalidKeySpecException ex) {
			LOGGER.error("RSAPrivateKeySpec is unavailable.", ex);
		} catch (NullPointerException ex) {
			LOGGER.error("RSAUtils#KEY_FACTORY is null, can not generate KeyFactory instance.", ex);
		}
		return null;
	}
	/**
	 * 使用指定的公钥加密数据。
	 * 
	 * @param publicKey 给定的公钥。
	 * @param data 要加密的数据。
	 * @return 加密后的数据。
	 */
	public byte[] encrypt(PublicKey publicKey, byte[] data) throws Exception {
		Cipher ci = Cipher.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
		ci.init(Cipher.ENCRYPT_MODE, publicKey);
		return ci.doFinal(data);
	}
	/**
	 * 使用指定的私钥解密数据。
	 * 
	 * @param privateKey 给定的私钥。
	 * @param data 要解密的数据。
	 * @return 原数据。
	 */
	public byte[] decrypt(PrivateKey privateKey, byte[] data) throws Exception {
		Cipher ci = Cipher.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
		ci.init(Cipher.DECRYPT_MODE, privateKey);
		return ci.doFinal(data);
	}
	/**
	 * 使用给定的公钥加密给定的字符串。
	 * <p />
	 * 若 {@code publicKey} 为 {@code null},或者 {@code plaintext} 为 {@code null} 则返回 {@code
	 * null}。
	 * 
	 * @param publicKey 给定的公钥。
	 * @param plaintext 字符串。
	 * @return 给定字符串的密文。
	 */
	public String encryptString(PublicKey publicKey, String plaintext) {
		if (publicKey == null || plaintext == null) {
			return null;
		}
		byte[] data = plaintext.getBytes();
		try {
			byte[] en_data = encrypt(publicKey, data);
			return new String(Hex.encodeHex(en_data));
		} catch (Exception ex) {
			LOGGER.error(ex.getCause().getMessage());
		}
		return null;
	}
	/**
	 * 使用默认的公钥加密给定的字符串。
	 * <p />
	 * 若{@code plaintext} 为 {@code null} 则返回 {@code null}。
	 * 
	 * @param plaintext 字符串。
	 * @return 给定字符串的密文。
	 */
	public String encryptString(String plaintext) {
		if (plaintext == null) {
			return null;
		}
		byte[] data = plaintext.getBytes();
		try {
			byte[] en_data = encrypt((RSAPublicKey) getKeyPair().getPublic(), data);
			return new String(Hex.encodeHex(en_data));
		} catch (NullPointerException ex) {
			LOGGER.error("keyPair cannot be null.");
		} catch (Exception ex) {
			LOGGER.error(ex.getCause().getMessage());
		}
		return null;
	}
	/**
	 * 使用给定的私钥解密给定的字符串。
	 * <p />
	 * 若私钥为 {@code null},或者 {@code encrypttext} 为 {@code null}或空字符串则返回 {@code null}。
	 * 私钥不匹配时,返回 {@code null}。
	 * 
	 * @param privateKey 给定的私钥。
	 * @param encrypttext 密文。
	 * @return 原文字符串。
	 */
	public String decryptString(PrivateKey privateKey, String encrypttext) {
		if (privateKey == null || StringUtils.isBlank(encrypttext)) {
			return null;
		}
		try {
			byte[] en_data = Hex.decodeHex(encrypttext.toCharArray());
			byte[] data = decrypt(privateKey, en_data);
			return new String(data);
		} catch (Exception ex) {
			LOGGER.error(String.format("\"%s\" Decryption failed. Cause: %s", encrypttext, ex.getCause().getMessage()));
		}
		return null;
	}
	/**
	 * 使用默认的私钥解密给定的字符串。
	 * <p />
	 * 若{@code encrypttext} 为 {@code null}或空字符串则返回 {@code null}。
	 * 私钥不匹配时,返回 {@code null}。
	 * 
	 * @param encrypttext 密文。
	 * @return 原文字符串。
	 */
	public String decryptString(String encrypttext) {
		if (StringUtils.isBlank(encrypttext)) {
			return null;
		}
		try {
			byte[] en_data = Hex.decodeHex(encrypttext.toCharArray());
			byte[] data = decrypt((RSAPrivateKey) getKeyPair().getPrivate(), en_data);
			return new String(data) ;
		} catch (NullPointerException ex) {
			LOGGER.error("keyPair cannot be null.");
		} catch (Exception ex) {
			LOGGER.error(String.format("\"%s\" Decryption failed. Cause: %s", encrypttext, ex.getMessage()));
		}
		return null;
	}
	/**
	 * 使用默认的私钥解密由JS加密(使用此类提供的公钥加密)的字符串。
	 * 
	 * @param encrypttext 密文。
	 * @return {@code encrypttext} 的原文字符串。
	 */
	public String decryptStringByJs(String encrypttext) {
		String text = decryptString(encrypttext);
		if (text == null) {
			return null;
		}
		return StringUtils.reverse(text);
	}
	/** 返回已初始化的默认的公钥。*/
	public RSAPublicKey getDefaultPublicKey() {
		KeyPair keyPair = getKeyPair();
		if (keyPair != null) {
			return (RSAPublicKey) keyPair.getPublic();
		}
		return null;
	}
	/** 返回已初始化的默认的私钥。*/
	public RSAPrivateKey getDefaultPrivateKey() {
		KeyPair keyPair = getKeyPair();
		if (keyPair != null) {
			return (RSAPrivateKey) keyPair.getPrivate();
		}
		return null;
	}
	public String getModulus() {
		return new String(Hex.encodeHex(getDefaultPublicKey().getModulus().toByteArray()));
	}
	public String getExponent() {
		return new String(Hex.encodeHex(getDefaultPublicKey().getPublicExponent().toByteArray()));
	}
	public static byte[] getPublicGovKey2() throws IOException {
		byte[] buffer = null;
		InputStream fis = null;
		ByteArrayOutputStream bos = null;
		try {
			fis = RSAUtils.class.getClassLoader().getResourceAsStream("PublicGov.key");
			bos = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1000];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			buffer = bos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis != null)
				fis.close();
			if (bos != null)
				bos.close();
		}
		return buffer;
	}
	public static byte[] getPublicGovKey() {
		return sehrCrypto.sehrCrypto.ReadFileBytes(RSAUtils.class.getClassLoader().getResource("PublicGov.key").getPath());
	}
	public static void main(String[] args) {
		try {
			byte[] t1 = getPublicGovKey2();
			byte[] t2 = getPublicGovKey();
			System.out.println(t1);
			System.out.println(t2);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
    @Autowired
    private CommonUtil CommonUtil;
    @Autowired
    private RSADao rsaDao;
    private BaseService baseService;
    @PostConstruct
    public void cleanRSA() {
        // 情况缓存表
        rsaDao.deleteAll();
    }
    private static final Logger LOGGER = LoggerFactory.getLogger(RSAUtils.class);
    /**
     * 算法名称
     */
    private static final String ALGORITHOM = "RSA";
    /**
     * 密钥大小
     */
    private static final int KEY_SIZE = 1024;
    /**
     * 默认的安全服务提供者
     */
    private static final Provider DEFAULT_PROVIDER = new BouncyCastleProvider();
    private static KeyPairGenerator keyPairGen = null;
    private static KeyFactory keyFactory = null;
    /**
     * 缓存的密钥对。
     */
    private KeyPair oneKeyPair = null;
    private static RSAUtils rsaUtils = null;
    static {
        try {
            keyPairGen = KeyPairGenerator.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
            keyFactory = KeyFactory.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
        } catch (NoSuchAlgorithmException ex) {
            LOGGER.error(ex.getMessage());
        }
    }
    public synchronized static RSAUtils getInstance(BaseService baseService) {
        if (rsaUtils == null) {
            rsaUtils = new RSAUtils();
            rsaUtils.baseService = baseService;
        }
        return rsaUtils;
    }
    public KeyPair getKeyPair() {
        if (oneKeyPair == null) {
            // 从数据库加载
            RSA rsa = baseService.loadRSA();
            if (rsa == null) {
                // 生成密钥
                generateKeyPair();
            } else {
                // 由数据库取出来
                Object obj = CommonUtil.toObject(rsa.getData());
                oneKeyPair = (KeyPair) obj;
            }
        }
        return oneKeyPair;
    }
    /**
     * 生成并返回RSA密钥对。
     */
    private synchronized KeyPair generateKeyPair() {
        try {
            keyPairGen.initialize(KEY_SIZE, new SecureRandom(DateFormatUtils.format(new Date(), DateUtil.YYYYMMDD).getBytes()));
            oneKeyPair = keyPairGen.generateKeyPair();
            // 保存到数据库
            baseService.saveRSA(oneKeyPair);
            return oneKeyPair;
        } catch (InvalidParameterException ex) {
            LOGGER.error("KeyPairGenerator does not support a key length of " + KEY_SIZE + ".", ex);
        } catch (NullPointerException ex) {
            LOGGER.error("RSAUtils#KEY_PAIR_GEN is null, can not generate KeyPairGenerator instance.", ex);
        }
        return null;
    }
    /**
     * 根据给定的系数和专用指数构造一个RSA专用的公钥对象。
     *
     * @param modulus        系数。
     * @param publicExponent 专用指数。
     * @return RSA专用公钥对象。
     */
    public RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) {
        RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent));
        try {
            return (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
        } catch (InvalidKeySpecException ex) {
            LOGGER.error("RSAPublicKeySpec is unavailable.", ex);
        } catch (NullPointerException ex) {
            LOGGER.error("RSAUtils#KEY_FACTORY is null, can not generate KeyFactory instance.", ex);
        }
        return null;
    }
    /**
     * 根据给定的系数和专用指数构造一个RSA专用的私钥对象。
     *
     * @param modulus         系数。
     * @param privateExponent 专用指数。
     * @return RSA专用私钥对象。
     */
    public RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) {
        RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(new BigInteger(modulus), new BigInteger(privateExponent));
        try {
            return (RSAPrivateKey) keyFactory.generatePrivate(privateKeySpec);
        } catch (InvalidKeySpecException ex) {
            LOGGER.error("RSAPrivateKeySpec is unavailable.", ex);
        } catch (NullPointerException ex) {
            LOGGER.error("RSAUtils#KEY_FACTORY is null, can not generate KeyFactory instance.", ex);
        }
        return null;
    }
    /**
     * 使用指定的公钥加密数据。
     *
     * @param publicKey 给定的公钥。
     * @param data      要加密的数据。
     * @return 加密后的数据。
     */
    public byte[] encrypt(PublicKey publicKey, byte[] data) throws Exception {
        Cipher ci = Cipher.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
        ci.init(Cipher.ENCRYPT_MODE, publicKey);
        return ci.doFinal(data);
    }
    /**
     * 使用指定的私钥解密数据。
     *
     * @param privateKey 给定的私钥。
     * @param data       要解密的数据。
     * @return 原数据。
     */
    public byte[] decrypt(PrivateKey privateKey, byte[] data) throws Exception {
        Cipher ci = Cipher.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
        ci.init(Cipher.DECRYPT_MODE, privateKey);
        return ci.doFinal(data);
    }
    /**
     * 使用给定的公钥加密给定的字符串。
     * <p>
     * 若 {@code publicKey} 为 {@code null},或者 {@code plaintext} 为 {@code null} 则返回 {@code
     * null}。
     *
     * @param publicKey 给定的公钥。
     * @param plaintext 字符串。
     * @return 给定字符串的密文。
     */
    public String encryptString(PublicKey publicKey, String plaintext) {
        if (publicKey == null || plaintext == null) {
            return null;
        }
        byte[] data = plaintext.getBytes();
        try {
            byte[] en_data = encrypt(publicKey, data);
            return new String(Hex.encodeHex(en_data));
        } catch (Exception ex) {
            LOGGER.error(ex.getCause().getMessage());
        }
        return null;
    }
    /**
     * 使用默认的公钥加密给定的字符串。
     * <p>
     * 若{@code plaintext} 为 {@code null} 则返回 {@code null}。
     *
     * @param plaintext 字符串。
     * @return 给定字符串的密文。
     */
    public String encryptString(String plaintext) {
        if (plaintext == null) {
            return null;
        }
        byte[] data = plaintext.getBytes();
        try {
            byte[] en_data = encrypt((RSAPublicKey) getKeyPair().getPublic(), data);
            return new String(Hex.encodeHex(en_data));
        } catch (NullPointerException ex) {
            LOGGER.error("keyPair cannot be null.");
        } catch (Exception ex) {
            LOGGER.error(ex.getCause().getMessage());
        }
        return null;
    }
    /**
     * 使用给定的私钥解密给定的字符串。
     * <p>
     * 若私钥为 {@code null},或者 {@code encrypttext} 为 {@code null}或空字符串则返回 {@code null}。
     * 私钥不匹配时,返回 {@code null}。
     *
     * @param privateKey  给定的私钥。
     * @param encrypttext 密文。
     * @return 原文字符串。
     */
    public String decryptString(PrivateKey privateKey, String encrypttext) {
        if (privateKey == null || StringUtils.isBlank(encrypttext)) {
            return null;
        }
        try {
            byte[] en_data = Hex.decodeHex(encrypttext.toCharArray());
            byte[] data = decrypt(privateKey, en_data);
            return new String(data);
        } catch (Exception ex) {
            LOGGER.error(String.format("\"%s\" Decryption failed. Cause: %s", encrypttext, ex.getCause().getMessage()));
        }
        return null;
    }
    /**
     * 使用默认的私钥解密给定的字符串。
     * <p>
     * 若{@code encrypttext} 为 {@code null}或空字符串则返回 {@code null}。
     * 私钥不匹配时,返回 {@code null}。
     *
     * @param encrypttext 密文。
     * @return 原文字符串。
     */
    public String decryptString(String encrypttext) {
        if (StringUtils.isBlank(encrypttext)) {
            return null;
        }
        try {
            byte[] en_data = Hex.decodeHex(encrypttext.toCharArray());
            byte[] data = decrypt((RSAPrivateKey) getKeyPair().getPrivate(), en_data);
            return new String(data);
        } catch (NullPointerException ex) {
            LOGGER.error("keyPair cannot be null.");
        } catch (Exception ex) {
            LOGGER.error(String.format("\"%s\" Decryption failed. Cause: %s", encrypttext, ex.getMessage()));
        }
        return null;
    }
    /**
     * 使用默认的私钥解密由JS加密(使用此类提供的公钥加密)的字符串。
     *
     * @param encrypttext 密文。
     * @return {@code encrypttext} 的原文字符串。
     */
    public String decryptStringByJs(String encrypttext) {
        String text = decryptString(encrypttext);
        if (text == null) {
            return null;
        }
        return StringUtils.reverse(text);
    }
    /**
     * 返回已初始化的默认的公钥。
     */
    public RSAPublicKey getDefaultPublicKey() {
        KeyPair keyPair = getKeyPair();
        if (keyPair != null) {
            return (RSAPublicKey) keyPair.getPublic();
        }
        return null;
    }
    /**
     * 返回已初始化的默认的私钥。
     */
    public RSAPrivateKey getDefaultPrivateKey() {
        KeyPair keyPair = getKeyPair();
        if (keyPair != null) {
            return (RSAPrivateKey) keyPair.getPrivate();
        }
        return null;
    }
    public String getModulus() {
        return new String(Hex.encodeHex(getDefaultPublicKey().getModulus().toByteArray()));
    }
    public String getExponent() {
        return new String(Hex.encodeHex(getDefaultPublicKey().getPublicExponent().toByteArray()));
    }
    public static byte[] getPublicGovKey2() throws IOException {
        byte[] buffer = null;
        InputStream fis = null;
        ByteArrayOutputStream bos = null;
        try {
            fis = RSAUtils.class.getClassLoader().getResourceAsStream("PublicGov.key");
            bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            buffer = bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null)
                fis.close();
            if (bos != null)
                bos.close();
        }
        return buffer;
    }
    public static byte[] getPublicGovKey() {
        return sehrCrypto.sehrCrypto.ReadFileBytes(RSAUtils.class.getClassLoader().getResource("PublicGov.key").getPath());
    }
    public static void main(String[] args) {
        try {
            byte[] t1 = getPublicGovKey2();
            byte[] t2 = getPublicGovKey();
            System.out.println(t1);
            System.out.println(t2);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}