RSA 簽名、驗證、加密、解密幫助類
import java.io.IOException; import java.security.InvalidKeyException; 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.Signature; import java.security.SignatureException; import java.security.spec.EncodedKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder;
/** * RSA 簽名、驗證、加密、解密幫助類 * * @author sam * */ public class RsaHelper { // 簽名對象 private Signature sign; private static final RsaHelper rsaHelper = new RsaHelper();
private String pubkey; private String prikey;
private RsaHelper() { try { sign = Signature.getInstance } catch (NoSuchAlgorithmException nsa) { System.out.println("" + nsa.getMessage()); } }
public static RsaHelper getInstance() { return rsaHelper; }
private PrivateKey getPrivateKey(String privateKeyStr) { try { byte[] privateKeyBytes = b64decode(privateKeyStr); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); return keyFactory.generatePrivate(privateKeySpec); } catch (InvalidKeySpecException e) { System.out.println("Invalid Key Specs. Not valid Key files." + e.getCause()); return null; } catch (NoSuchAlgorithmException e) { System.out.println("There is no such algorithm. Please check the JDK ver." + e.getCause()); return null; } }
private PublicKey getPublicKey(String publicKeyStr) { try { byte[] publicKeyBytes = b64decode(publicKeyStr); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes); return keyFactory.generatePublic(publicKeySpec); } catch (InvalidKeySpecException e) { System.out.println("Invalid Key Specs. Not valid Key files." + e.getCause()); return null; } catch (NoSuchAlgorithmException e) { System.out.println("There is no such algorithm. Please check the JDK ver." + e.getCause()); return null; } }
/** * RSA 數據簽名 * * @param toBeSigned * (待簽名的原文) * @param priKey * (RSA私鑰) * @return (返回RSA簽名後的數據簽名數據base64編碼) */ public String signData(String toBeSigned, String priKey) {
try { PrivateKey privateKey = getPrivateKey(priKey); byte[] signByte = toBeSigned.getBytes("utf-8"); Signature rsa = Signature.getInstance("SHA1withRSA"); rsa.initSign(privateKey); rsa.update(signByte); return b64encode(rsa.sign()); } catch (NoSuchAlgorithmException ex) { System.out.println(ex); } catch (InvalidKeyException in) { System.out.println("Invalid Key file.Please check the key file path" + in.getCause()); } catch (Exception se) { System.out.println(se); } return null; }
/** * RSA 數據簽名驗證 * * @param signature * (RSA簽名數據(base64編碼) * @param data * (待驗證的數據原文) * @param pubKey * (RSA公鑰數據) * @return 返回驗證結果(TRUE:驗證成功;FALSE:驗證失敗) */ public boolean verifySignature(String signature, String data, String pubKey) { try { byte[] signByte = b64decode(signature); byte[] dataByte = data.getBytes("utf-8"); PublicKey publicKey = getPublicKey(pubKey); sign.initVerify(publicKey); sign.update(dataByte); return sign.verify(signByte); } catch (SignatureException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return false; }
/** * base64編碼 * * @param data * @return */ private String b64encode(byte[] data) { return new BASE64Encoder().encode(data); }
/** * base64解碼 * * @param data * @return */ private byte[] b64decode(String data) { try { return new BASE64Decoder().decodeBuffer(data); } catch (Exception ex) { } return null; }
/** * RSA數據加密 * * @param data * (需要加密的數據) * @param pubKey * (RSA公鑰) * @return 返回加密後的密文(BASE64編碼) */ public String encryptData(String data, String pubKey) { try { byte[] dataByte = data.getBytes("utf-8"); PublicKey publicKey = getPublicKey(pubKey); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return b64encode(cipher.doFinal(dataByte)); } catch (Exception e) { return null; } }
/** * RSA數據解密 * * @param encryptedData * (需要解密的數據base64編碼數據) * @param priKey * (RSA的私鑰) * @return 返回解密後的原始明文 */ public String decryptData(String encryptedData, String priKey) { try { byte[] encryData = b64decode(encryptedData); PrivateKey privateKey = getPrivateKey(priKey); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, privateKey); return new String(cipher.doFinal(encryData), "utf-8"); } catch (Exception e) { return null; } }
/** * 得到私鑰字符串(經過base64編碼) * * @return */ public static String getPriKeyString(PrivateKey key) throws Exception { byte[] keyBytes = key.getEncoded(); String s = (new BASE64Encoder()).encode(keyBytes); return s; }
/** * 得到公鑰字符串(經過base64編碼) * * @return */ public static String getPubKeyString(PublicKey key) throws Exception { byte[] keyBytes = key.getEncoded(); String s = (new BASE64Encoder()).encode(keyBytes); return s; }
/** * 生成密鑰 自動產生RSA1024位密鑰 * * @throws NoSuchAlgorithmException * @throws IOException */ public void getAutoCreateRSA() throws NoSuchAlgorithmException, IOException { try { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024); KeyPair kp = kpg.genKeyPair(); PublicKey puk = kp.getPublic(); PrivateKey prk = kp.getPrivate();
pubkey = getPubKeyString(puk); prikey = getPriKeyString(prk); System.out.print("pubkey==:"+pubkey.replaceAll("\r", "").replaceAll("\n", "")); System.out.print("prikey==:"+prikey.replaceAll("\r", "").replaceAll("\n", "")); } catch (Exception e) { e.printStackTrace(); } }
public String getPubkey() { return pubkey; }
public void setPubkey(String pubkey) { this.pubkey = pubkey; }
public String getPrikey() { return prikey; }
public void setPrikey(String prikey) { this.prikey = prikey; }
}
|
RSA 簽名、驗證、加密、解密幫助類