java对应PHP SHA256 加签 验签工具方法

java 对应 php 的 sha256 加签工具

import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;

/**
 * sha256 rsa验签  对应php sha256 签名验签
 * @author Administrator
 *
 */
public class SHA256withRSAUtils {
	
	public static final String SIGNATURE_ALGORITHM = "SHA256withRSA"; 
	public static final String ENCODE_ALGORITHM = "SHA-256";
	
	/** 
	* 签名 
	* 
	* @param privateKey 
	* 私钥 
	* @param plain_text 
	* 明文 
	* @return 
	*/ 
	public static String sign(PrivateKey privateKey, String plain_text) { 
	MessageDigest messageDigest; 
	byte[] signed = null;
	String signData=null;
	try { 
	messageDigest = MessageDigest.getInstance(ENCODE_ALGORITHM); 
	messageDigest.update(plain_text.getBytes()); 
	byte[] outputDigest_sign = messageDigest.digest(); 
	System.out.println("SHA-256加密后-----》" +bytesToHexStr(outputDigest_sign)); 
	Signature Sign = Signature.getInstance(SIGNATURE_ALGORITHM); 
	Sign.initSign(privateKey); 
	Sign.update(outputDigest_sign); 
	signed = Sign.sign();
	signData = bytesToHexStr(signed);
	System.out.println("SHA256withRSA签名后-----》" +signData); 
	} catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) { 
	e.printStackTrace(); 
	} 
	return signData; 
	} 
	/** 
	* 验签 
	* 
	* @param publicKey 
	* 公钥 
	* @param plain_text 
	* 明文 
	* @param signed 
	* 签名 
	*/ 
	public static boolean verifySign(PublicKey publicKey, String plain_text,String signData) { 
	MessageDigest messageDigest; 
	boolean SignedSuccess=false; 
	try { 
	messageDigest = MessageDigest.getInstance(ENCODE_ALGORITHM); 
	messageDigest.update(plain_text.getBytes()); 
	byte[] outputDigest_verify = messageDigest.digest(); 
	//System.out.println("SHA-256加密后-----》" +bytesToHexString(outputDigest_verify)); 
	Signature verifySign = Signature.getInstance(SIGNATURE_ALGORITHM); 
	verifySign.initVerify(publicKey); 
	verifySign.update(outputDigest_verify);
	byte[] signed = hexStrToBytes(signData);
	SignedSuccess = verifySign.verify(signed); 
	System.out.println("验证成功?---" + SignedSuccess); 

	} catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) { 
	e.printStackTrace(); 
	} 
	return SignedSuccess; 
	} 
	 private static final char[] bcdLookup =  
	        { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };  
	      
	      
	      
	    /** 
	     * 将字节数组转换为16进制字符串的形式. 
	     */  
	    public static final String bytesToHexStr(byte[] bcd){  
	        StringBuffer s = new StringBuffer(bcd.length * 2);  
	  
	        for (int i = 0; i < bcd.length; i++)  
	        {  
	            s.append(bcdLookup[(bcd[i] >>> 4) & 0x0f]);  
	            s.append(bcdLookup[bcd[i] & 0x0f]);  
	        }  
	  
	        return s.toString();  
	    }  
	      
	    /** 
	     * 将16进制字符串还原为字节数组. 
	     */  
	    public static final byte[] hexStrToBytes(String s)  {  
	          
	        byte[] bytes;  
	  
	        bytes = new byte[s.length() / 2];  
	  
	        for (int i = 0; i < bytes.length; i++){  
	            bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2), 16);  
	        }  
	  
	        return bytes;  
	    } 

}

如果需要自己生成公钥私钥请使用如下代码生成即可

import java.security.KeyFactory; 
import java.security.KeyPair; 
import java.security.KeyPairGenerator; 
import java.security.NoSuchAlgorithmException; 
import java.security.PrivateKey; 
import java.security.PublicKey; 
import java.security.interfaces.RSAPrivateKey; 
import java.security.interfaces.RSAPublicKey; 
import java.security.spec.InvalidKeySpecException; 
import java.security.spec.PKCS8EncodedKeySpec; 
import java.security.spec.X509EncodedKeySpec; 
import java.util.HashMap; 
import java.util.Map; 
public class RSA { 
public static final String KEY_ALGORITHM = "RSA"; 
public static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding"; 
public static final String PUBLIC_KEY = "publicKey"; 
public static final String PRIVATE_KEY = "privateKey"; 
public static final int KEY_SIZE = 2048; 
/** 
* 生成密钥对 
* 
* @return 
*/ 
public static Map generateKeyBytes() { 
try { 
KeyPairGenerator keyPairGenerator = KeyPairGenerator 
.getInstance(KEY_ALGORITHM); 
keyPairGenerator.initialize(KEY_SIZE); 
KeyPair keyPair = keyPairGenerator.generateKeyPair(); 
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); 
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); 
Map keyMap = new HashMap (); 
keyMap.put(PUBLIC_KEY, publicKey.getEncoded()); 
keyMap.put(PRIVATE_KEY, privateKey.getEncoded()); 
return keyMap; 
} catch (NoSuchAlgorithmException e) { 
e.printStackTrace(); 
} 
return null; 
} 
/** 
* 还原公钥 
* 
* @param keyBytes 
* @return 
*/ 
public static PublicKey restorePublicKey(byte[] keyBytes) { 
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes); 
try { 
KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM); 
PublicKey publicKey = factory.generatePublic(x509EncodedKeySpec); 
return publicKey; 
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) { 
e.printStackTrace(); 
} 
return null; 
} 
/** 
* 还原私钥 
* 
* @param keyBytes 
* @return 
*/ 
public static PrivateKey restorePrivateKey(byte[] keyBytes) { 
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec( 
keyBytes); 
try { 
KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM); 
PrivateKey privateKey = factory 
.generatePrivate(pkcs8EncodedKeySpec); 
return privateKey; 
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) { 
e.printStackTrace(); 
} 
return null; 
} 

你可能感兴趣的:(java学习)