SHA256withRSA签名验签 & BASE64加解密

本文介绍了一个使用Java实现的SHA256WithRSA签名和验证的方法。其中包括了签名的创建过程以及如何使用公钥来验证签名的真实性。此外还提供了将二进制数据编码为BASE64字符串及解码的方法。
该文章已生成可运行项目,
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import org.apache.commons.codec.binary.Base64;

public class SignUtil {
	
	private static final String ENCODING = "UTF-8";
	private static final String SIGNATURE_ALGORITHM = "SHA256withRSA";
	
	/**
	 * SHA256WithRSA签名
	 * @param data
	 * @param privateKey
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeySpecException
	 * @throws InvalidKeyException
	 * @throws SignatureException
	 * @throws UnsupportedEncodingException
	 */
	public static byte[] sign256(String data, PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, 
	  																		 SignatureException, UnsupportedEncodingException {
	    
		Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
	       
		signature.initSign(privateKey);
	       
		signature.update(data.getBytes(ENCODING));
	         
		return signature.sign();
	}
	
	public static boolean verify256(String data, byte[] sign, PublicKey publicKey){
		if(data == null || sign == null || publicKey == null){
			return false;
		}
		
		try {
			Signature signetcheck = Signature.getInstance(SIGNATURE_ALGORITHM);
			signetcheck.initVerify(publicKey);
			signetcheck.update(data.getBytes("UTF-8"));
			return signetcheck.verify(sign);
		} catch (Exception e) {
			return false;
		}
	}
	
	/**
	 * 二进制数据编码为BASE64字符串 
	 * @param data
	 * @return
	 */
	public static String encodeBase64(byte[] bytes){
		return new String(Base64.encodeBase64(bytes));
	}
	
	/**
	 * BASE64解码
	 * @param bytes
	 * @return
	 */
	public static byte[] decodeBase64(byte[] bytes) { 
		byte[] result = null;
		try {
			result = Base64.decodeBase64(bytes);
		} catch (Exception e) {
			return null;
		}
        return result;  
    }
}

本文章已经生成可运行项目
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值