JAVA加密方法总结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xlyrh/article/details/80021743
	/**
	 * MD5加密,适用于通用的加密规则
	 * @param id
	 * @return
	 */
	public String sign(String content) {
		String contentKey = content + privateKey;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.reset();
			md.update(contentKey.getBytes("UTF-8"));
			byte[] result = md.digest();

			return HttpHelper.bytesToHexString(result);
		} catch (Exception e) {
			System.out.println(Arrays.toString(e.getStackTrace()));
		}
    	return null;
    }
	
    /**
     * MD5withRSA私钥加密
     * @param content
     * @return
     * @throws Exception
     */
    public String MD5withRSASign(String content) throws Exception {
        byte[] contentBytes = content.getBytes("utf-8");
     
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(getPrivateKey(privateKey));
        signature.update(contentBytes);
        byte[] signs = signature.sign();
        
        return Base64.encodeBase64String(signs);
    }
    
    /**
     * SHA1withRSA私钥加密
     * @param content
     * @param privateKey
     * @return
     * @throws Exception
     */
    public String getSha1Sign(String content) throws Exception {
        byte[] contentBytes = content.getBytes("utf-8");
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(getPrivateKey(privateKey));
        signature.update(contentBytes);
        byte[] signs = signature.sign();
        return Base64.encodeBase64String(signs);
    }
    
    /**
     * RSA公钥加密
     * @param content
     * @return
     * @throws Exception
     */
    public String RSASign(String content) throws Exception{  
    	byte[] contentBytes = content.getBytes("utf-8");
    	
        Cipher cipher=Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKey));  
        return Base64.encodeBase64String(cipher.doFinal(contentBytes));  
    }  
      
    
    /**
     * 公钥转换
     * @param key
     * @return
     * @throws Exception
     */
    private static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = (new BASE64Decoder()).decodeBuffer(key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
  }
    /**
     * 私钥转换
     * @param key
     * @return
     * @throws Exception
     */
    private static PrivateKey getPrivateKey(String key) throws Exception {
	    byte[] keyBytes;
	    keyBytes = (new BASE64Decoder()).decodeBuffer(key);
	    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
	    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	    PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
	    return privateKey;
  }

猜你喜欢

转载自blog.csdn.net/xlyrh/article/details/80021743