RSA帮助类
package com.abc.helper; import org.apache.tomcat.util.codec.binary.Base64; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Cipher; import java.io.IOException; import java.io.InputStream; import java.security.*; import java.security.spec.EncodedKeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; /** * Created by xxx. */ public class RsaHelper { private static final String ALGORITHM="RSA"; private PublicKey publicKey = null; private PrivateKey privateKey = null; /* 获取公钥和私钥,0=公钥,1=私钥 */ public String[] getKeys() { String[] keys = new String[2]; try { KeyPair keyPair = getKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); keys[0] = getKeyAsString(publicKey); keys[1] = getKeyAsString(privateKey); } catch (Exception e) { keys[0] = null; keys[1] = null; } return keys; } /* 设置公钥,可以通过getKeys获取公钥和私钥并存储 */ public boolean setPublicKey(String key) { try { this.publicKey = getPublicKeyFromString(key); return true; } catch (Exception e) { return false; } } /* 设置私钥,可以通过getKeys获取公钥和私钥并存储 */ public boolean setPrivateKey(String key) { try { this.privateKey = getPrivateKeyFromString(key); return true; } catch (Exception e) { return false; } } /* 加密,需要先设置公钥 */ public String encrypt(String s) { String key = ""; if (this.publicKey != null) { try { key = encrypt(s, this.publicKey); } catch (Exception e) { //// } } return key; } /* 解密,需要先设置私钥 */ public String decrypt(String key) { String s = ""; if (this.privateKey != null) { try { s = decrpyt(key, this.privateKey); } catch (Exception e) { //// } } return s; } //=============以下静态函数暂不开放对外调用=============// //生成密钥对 static KeyPair getKeyPair() throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(512); //可以理解为:加密后的密文长度,实际原文要小些 越大 加密解密越慢 KeyPair keyPair = keyGen.generateKeyPair(); return keyPair; } /** * 通过公钥文件进行加密数据 * * @return 加密后经过base64处理的字符串 */ static String encrypt(String source, PublicKey publicKey) throws Exception { InputStream fis = null; try { // fis = new FileInputStream(publicKeyFileName); // CertificateFactory cf = CertificateFactory.getInstance("x509"); // Certificate cerCert = cf.generateCertificate(fis); // PublicKey pubKey = cerCert.getPublicKey(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] sbt = source.getBytes(); byte[] epByte = cipher.doFinal(sbt); BASE64Encoder encoder = new BASE64Encoder(); String epStr = encoder.encode(epByte); return epStr; } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 通过私钥文件进行解密数据 * * @return 解密后的明文字符串 */ static String decrpyt(String source, PrivateKey privateKey) throws Exception { BASE64Decoder b64d = new BASE64Decoder(); byte[] keyByte = b64d.decodeBuffer(source); InputStream fis = null; try { // fis = new FileInputStream(privateKeyFileName); // KeyStore keyStore = KeyStore.getInstance("PKCS12"); // char[] pscs = pfxPassword.toCharArray(); // keyStore.load(fis, pscs); // PrivateKey priKey = (PrivateKey) (keyStore.getKey(aliasName, pscs)); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] epByte = cipher.doFinal(keyByte); return new String(epByte, "UTF-8"); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } static String encrypt(String text, Key key) throws Exception { String encryptedText; byte[] cipherText=encrypt(text.getBytes("UTF8"),key); encryptedText=encodeBASE64(cipherText); return encryptedText; } static String decrypt(String text, Key key) throws Exception { String result; byte[] dectyptedText=decrypt(decodeBASE64(text),key); result=new String(dectyptedText,"UTF8"); return result; } static byte[] encrypt(byte[] text, Key key) throws Exception { byte[] cipherText=null; Cipher cipher=Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); cipherText=cipher.doFinal(text); return cipherText; } static byte[] decrypt(byte[] text, Key key) throws Exception { byte[] decryptedText=null; Cipher cipher=Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, key); decryptedText=cipher.doFinal(text); return decryptedText; } //将Key类型转换为String类型 static String getKeyAsString(Key key) { byte[] keyBytes = key.getEncoded(); BASE64Encoder b64 = new BASE64Encoder(); return b64.encode(keyBytes); } //将String类型转换为PrivateKey类型 static PrivateKey getPrivateKeyFromString(String key) throws Exception { KeyFactory keyFactory=KeyFactory.getInstance(ALGORITHM); BASE64Decoder b64=new BASE64Decoder(); EncodedKeySpec privateKeySpec=new PKCS8EncodedKeySpec(b64.decodeBuffer(key)); PrivateKey privateKey=keyFactory.generatePrivate(privateKeySpec); return privateKey; } //将String类型转换为PublicKey类型 static PublicKey getPublicKeyFromString(String key) throws Exception { BASE64Decoder b64=new BASE64Decoder(); KeyFactory keyFactory=KeyFactory.getInstance(ALGORITHM); EncodedKeySpec publicKeySpec=new X509EncodedKeySpec(b64.decodeBuffer(key)); PublicKey publicKey=keyFactory.generatePublic(publicKeySpec); return publicKey; } static String encodeBASE64(byte[] bytes) { BASE64Encoder b64=new BASE64Encoder(); return b64.encode(bytes); } static byte[] decodeBASE64(String text) throws IOException { BASE64Decoder b64=new BASE64Decoder(); return b64.decodeBuffer(text); } static String subSecEncrypt(String pText,Key key) throws Exception{ //分段加密,注意:分段加密的密文长度都是174字节 int pTextLen=pText.length(); int m=pTextLen/117; int n=pTextLen-m*117; String cText=""; //密文 //对117整数倍的子串加密,拼接 for(int i=0;i<m;i++){ String pTextSub=pText.substring(i*117, (i+1)*117); //获取子串 cText=cText+encrypt(pTextSub, key); //分段加密,拼接 } //对剩下的子串加密,拼接 String pTextSub2=pText.substring(pTextLen-n, pTextLen); cText=cText+encrypt(pTextSub2, key); return cText; } static String subSecDecrypt(String cText,Key key) throws Exception{ //分段解密,注意:分段加解密的密文长度都是174字节 int cTextLen=cText.length(); int m=cTextLen/174; //int n=cTextLen-m*174; String pText=""; //明文 for(int i=0;i<m;i++){ String cTextSub=cText.substring(i*174, (i+1)*174); pText=pText+decrypt(cTextSub, key); } return pText; } //用md5生成内容摘要,再用RSA的私钥加密,进而生成数字签名 static String getMd5Sign(String content , PrivateKey privateKey) throws Exception { byte[] contentBytes = content.getBytes("utf-8"); Signature signature = Signature.getInstance("MD5withRSA"); signature.initSign(privateKey); signature.update(contentBytes); byte[] signs = signature.sign(); return Base64.encodeBase64String(signs); } //对用md5和RSA私钥生成的数字签名进行验证 static boolean verifyWhenMd5Sign(String content, String sign, PublicKey publicKey) throws Exception { byte[] contentBytes = content.getBytes("utf-8"); Signature signature = Signature.getInstance("MD5withRSA"); signature.initVerify(publicKey); signature.update(contentBytes); return signature.verify(Base64.decodeBase64(sign)); } //用sha1生成内容摘要,再用RSA的私钥加密,进而生成数字签名 static String getSha1Sign(String content, PrivateKey privateKey) throws Exception { byte[] contentBytes = content.getBytes("utf-8"); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(privateKey); signature.update(contentBytes); byte[] signs = signature.sign(); return Base64.encodeBase64String(signs); } //对用md5和RSA私钥生成的数字签名进行验证 static boolean verifyWhenSha1Sign(String content, String sign, PublicKey publicKey) throws Exception { byte[] contentBytes = content.getBytes("utf-8"); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initVerify(publicKey); signature.update(contentBytes); return signature.verify(Base64.decodeBase64(sign)); } }
有些事情,没经历过不知道原理,没失败过不明白奥妙,没痛苦过不了解真谛。临渊羡鱼,不如退而结网!

浙公网安备 33010602011771号