java非对称加密RSA的工具类及其源代码
java rsa加密解密实例
java rsa加密解密实例这是一个使用Java进行RSA加密和解密的简单示例。
这个示例使用了Java的内置加密库,并且只适用于小数据块的加密和解密。
对于大数据块,你可能需要使用一种称为"混合加密"的技术,将数据分成小块并分别加密。
首先,我们需要导入一些必要的库:```javaimport ;import ;import ;```然后,我们可以生成RSA密钥对:```javaKeyPairGenerator keyGen = ("RSA");(2048);KeyPair pair = ();PrivateKey privateKey = ();PublicKey publicKey = ();```接下来,我们可以使用公钥进行加密,然后使用私钥进行解密。
首先,我们创建一个Cipher对象用于加密:```javaCipher encryptCipher = ("RSA");(_MODE, publicKey);byte[] cipherText = ("Hello, World!".getBytes());String cipherTextBase64 = ().encodeToString(cipherText);```然后,我们创建一个Cipher对象用于解密:```javaCipher decryptCipher = ("RSA");(_MODE, privateKey);byte[] plainText = (().decode(cipherTextBase64));String plainTextStr = new String(plainText);```现在,`plainTextStr`就是解密后的原始文本。
注意,这个例子中的数据是硬编码的,并且只包含英文字符。
如果你的数据包含其他字符(例如中文字符),或者你需要处理的数据量很大,你可能需要使用不同的方法。
RSA 公钥算法Java代码(带界面)
RSA公钥加密算法代码package .rsa.service;public class UnPrimeException extends Exception{public UnPrimeException() {}public UnPrimeException(String message) {super(message);}public UnPrimeException(Throwable cause) {super(cause);}public UnPrimeException(String message, Throwable cause) {super(message, cause);}}------------------------------------------------------------------------------------------------ package .rsa.service;public interface DataInfo {public MyData sendData(long p, long q, long public_key, long deprime)throws UnPrimeException;}-------------------------------------------------------------------------------------------------- package .rsa.service;public class DataDeal implements DataInfo{@Overridepublic MyData sendData(long p, long q, long public_key, long deprime) throws UnPrimeException {MyData data ;if (!this.primeNumber(q)||!this.primeNumber(q)){throw new UnPrimeException("非素数,请重新输入!") ;}else if((deprime >= this.getF(p,q)) ||(this.gcd(this.getF(p, q),deprime)!=1)){throw new UnPrimeException("输入的公钥不符合条件!") ;}else{data = new MyData(p, q,public_key, deprime) ;}return data ;}//判断是否为素数public boolean primeNumber(long t){long k=0;k=(long)Math.sqrt((double)t);boolean flag=true;outer:for(int i=2;i<=k;i++){if((t%i)==0){flag = false;break outer;}}return flag;}private long gcd(long a, long b){//最大公约数long gcd;if(b==0)gcd=a;else gcd=gcd(b,a%b);return gcd;}private long getF(long p, long q){return (p - 1)*(q -1) ;}}---------------------------------------------------------------------------------------------------------package .rsa.service;public class MyData {private long p;private long q;private long public_key ;private long deprime ;public MyData() {super();}public MyData(long p, long q, long public_key, long deprime) {super();this.p = p;this.q = q;this.public_key = public_key;this.deprime = deprime;}public long getP() {return p;}public void setP(long p) {this.p = p;}public long getQ() {return q;}public void setQ(long q) {this.q = q;}public long getDeprime() {return deprime;}public void setDeprime(long deprime) {this.deprime = deprime;}public long getPublic_key() {return public_key;}public void setPublic_key(long public_key) { this.public_key = public_key;}public boolean toPrime(){//判断最大公约数是否为1 if(this.gcd(p, q) != 1)return false ;return true ;}//求最大公约数public long gcd(long a, long b){long gcd;if(b==0)gcd=a;else gcd=gcd(b,a%b);return gcd;}public long getN(){return p*q ;}public long getF(){return (p - 1)*(q -1) ;}public long colum(long y,long n,long key){ //加密/解密long mul;if(key==1)mul=y%n;else mul=y*this.colum(y,n,key-1)%n;return mul;}//计算得到密匙public long getPrivate_key(){long f = this.getF() ;long private_key = 1;long value=1;for(long i=1;;i++){value=i*f+1;if((value%this.public_key==0)&& (value/this.public_key < f)){ private_key=value/this.public_key;break ;}}return private_key ;}//得到密文public long getMyPrime(){return this.colum(this.deprime, this.getN(), this.public_key) ;}public String getStrPrime(){return Long.toString(this.getMyPrime()) ;}//得到解密的文件public long getMyDeprime(){return this.colum(this.getMyPrime(), this.getN(), this.getPrivate_key()) ;}public String getStrDeprime(){return Long.toString(this.getMyDeprime()) ;}}---------------------------------------------------------------------------------------------------------package .rsa.frame;import java.awt.BorderLayout;import ponent;import java.awt.FlowLayout;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JPasswordField;import javax.swing.JTextField;import javax.swing.border.EmptyBorder;public class SenderFrame extends JFrame{/****/private static final long serialVersionUID = 1L;public SenderFrame(){init() ;}public void init(){setTitle("Sender");setSize(300, 220);setContentPane(createContentPane());addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {client.exit(SenderFrame.this) ;}});}private JPanel createContentPane(){JPanel p = new JPanel(new BorderLayout());p.add(BorderLayout.NORTH,new JLabel("发送数据", JLabel.CENTER));p.add(BorderLayout.CENTER, createCenterPane());p.add(BorderLayout.SOUTH, createBtnPane());p.setBorder(new EmptyBorder(6,6,6,6));return p;}private JPanel createCenterPane(){JPanel p= new JPanel(new BorderLayout());p.add(BorderLayout.NORTH, createIdPwdPane());p.setBorder(new EmptyBorder(6,6,6,6));return p;}private JPanel createIdPwdPane() {JPanel p= new JPanel(new GridLayout(2, 2, 0, 6));p.add(createP());p.add(createQ()) ;p.add(createPublic_key()) ;p.add(createPrime());return p;}private JPanel createP(){JPanel p = new JPanel(new BorderLayout(5,0));p.add(BorderLayout.WEST, new JLabel("素数p:"));idP = new JPasswordField();idP.enableInputMethods(true);p.add(BorderLayout.CENTER, idP);return p;}private JPanel createQ(){JPanel p = new JPanel(new BorderLayout(5,0));p.add(BorderLayout.WEST, new JLabel("素数q:"));idQ = new JPasswordField();idQ.enableInputMethods(true);p.add(BorderLayout.CENTER, idQ);return p;}private JPanel createPublic_key() {JPanel p = new JPanel(new BorderLayout(5,0));p.add(BorderLayout.WEST, new JLabel("公钥:"));public_key = new JTextField();p.add(BorderLayout.CENTER, public_key);return p;}private JPanel createPrime() {JPanel p = new JPanel(new BorderLayout(5,0));p.add(BorderLayout.WEST, new JLabel("明文:"));prime = new JTextField();p.add(BorderLayout.CENTER, prime);return p;}private JPanel createBtnPane(){JPanel p= new JPanel(new FlowLayout());JButton login = new JButton("发送");JButton cancel = new JButton("取消");p.add(login);p.add(cancel);getRootPane().setDefaultButton(login);login.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {client.send() ;}});cancel.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) {client.exit(SenderFrame.this) ;}});return p;}private Client client ;public void setClient(Client client){this.client = client ;}private JTextField public_key ;private JTextField prime;private JPasswordField idP;private JPasswordField idQ;public long getP(){char[] str = idP.getPassword();String s = new String(str);return Integer.parseInt(s);}public long getQ(){char[] q = idQ.getPassword();String s = new String(q);return Integer.parseInt(s) ;}public long getPrime(){String str = prime.getText();return Integer.parseInt(str);}public long getPublic_key(){String str = public_key.getText();return Integer.parseInt(str);}}-----------------------------------------------------------------------------------------------------------package .rsa.frame;import java.awt.BorderLayout;import java.awt.FlowLayout;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;public class ReceiverFrame extends JFrame{/****/private static final long serialVersionUID = 1L;public ReceiverFrame(){this.shows() ;}public void shows(){setTitle("Receiver");setSize(300, 180);setContentPane(createContentPane());addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0) ;}});}private JPanel createContentPane(){JPanel p = new JPanel(new BorderLayout());p.add(BorderLayout.NORTH,new JLabel("接收数据", JLabel.CENTER));p.add(BorderLayout.CENTER, createCenterPane());p.add(BorderLayout.SOUTH, createBtnPane());p.setBorder(new EmptyBorder(6,6,6,6));return p;}private JPanel createCenterPane(){JPanel p= new JPanel(new BorderLayout());p.add(BorderLayout.NORTH, createCipPane());p.setBorder(new EmptyBorder(6,6,6,6));return p;}private JPanel createCipPane() {JPanel p= new JPanel(new GridLayout(2, 1, 0, 6));p.add(createIdPane());p.add(createPwdPane());return p;}private JPanel createIdPane(){JPanel p = new JPanel(new BorderLayout(5,0));p.add(BorderLayout.WEST, new JLabel("密文:"));cipField= new JLabel();p.add(BorderLayout.CENTER, cipField);return p;}private JPanel createPwdPane(){JPanel p = new JPanel(new BorderLayout(5,0));p.add(BorderLayout.WEST, new JLabel("解密:"));decipField = new JLabel();p.add(BorderLayout.CENTER, decipField);return p;}private JPanel createBtnPane(){JPanel p= new JPanel(new FlowLayout());JButton button1 = new JButton("解密");JButton button = new JButton("确认");p.add(button1) ;p.add(button);getRootPane().setDefaultButton(button);button1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { client.showPrime(decipField) ;}});button.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { System.exit(0) ;}});return p;}private JLabel cipField ;private JLabel decipField ;public void updata(String pr){cipField.setText(pr) ;}private Client client ;public void setClient(Client client){this.client = client ;}}--------------------------------------------------------------------------------------------------------------package .rsa.frame;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import .rsa.service.DataInfo;import .rsa.service.MyData;import .rsa.service.UnPrimeException;public class Client {private SenderFrame sender ;private ReceiverFrame receiver ;private DataInfo d ;public void setData(DataInfo d){this.d = d ;}public SenderFrame getSender() {return sender;}public void setSender(SenderFrame sender) {this.sender = sender;}public ReceiverFrame getReceiver() {return receiver;}public void setReceiver(ReceiverFrame receiver) {this.receiver = receiver;}public MyData send(){MyData data = null;try{long end = System.currentTimeMillis() ;long idP = sender.getP();long idQ = sender.getQ();long public_key = sender.getPublic_key() ;//公钥long prime = sender.getPrime(); //明文//发送成功data = this.d.sendData(idP, idQ, public_key, prime) ;sender.setVisible(false);long begin = System.currentTimeMillis() ;receiver.updata(data.getStrPrime()) ;System.out.println("运行时间为:" + (end-begin));receiver.setVisible(true);System.out.println("p = " + sender.getP());System.out.println("q = " + sender.getQ());System.out.println("n = " + data.getN());System.out.println("f = " + data.getF());System.out.println("e = " + data.getPublic_key());System.out.println("m = " + sender.getPrime());System.out.println("d = " + data.getPrivate_key());System.out.println("C = " + data.getMyPrime());System.out.println("M = " + data.getMyDeprime());}catch(NumberFormatException e){e.printStackTrace();JOptionPane.showMessageDialog(sender, "输入数字!");}catch(UnPrimeException e){e.printStackTrace() ;JOptionPane.showMessageDialog(sender, e.getMessage());}catch(Exception e){e.printStackTrace();JOptionPane.showMessageDialog(sender, e.getMessage());}return data ;}public void showPrime(JLabel label){MyData d = this.send() ;long begin = System.currentTimeMillis() ;label.setText(d.getStrDeprime()) ;long end = System.currentTimeMillis() ;System.out.println("运行时间为:" + (end-begin));}public void exit(JFrame frame){int val =JOptionPane.showConfirmDialog(frame, "亲,不发送啦?");if(val==JOptionPane.YES_OPTION){frame.setVisible(false);System.exit(0);}}}-------------------------------------------------------------------------------------------------------------package .rsa;import .rsa.frame.Client;import .rsa.frame.ReceiverFrame;import .rsa.frame.SenderFrame;import .rsa.service.DataDeal;import .rsa.service.DataInfo;public class RSAMain {public static void main(String args[]){SenderFrame sf = new SenderFrame() ;Client client = new Client() ;ReceiverFrame rf = new ReceiverFrame() ;DataInfo di = new DataDeal() ;sf.setClient(client) ;rf.setClient(client) ;client.setSender(sf) ;client.setReceiver(rf) ;client.setData(di) ;sf.setVisible(true) ;}}。
Java使用Cipher类实现加密,包括DES,DES3,AES和RSA加密
Java使⽤Cipher类实现加密,包括DES,DES3,AES和RSA加密⼀、先看⼀个简单加密,解密实现1.1 加密/*** content: 加密内容* slatKey: 加密的盐,16位字符串* vectorKey: 加密的向量,16位字符串*/public String encrypt(String content, String slatKey, String vectorKey) throws Exception {Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");SecretKey secretKey = new SecretKeySpec(slatKey.getBytes(), "AES");IvParameterSpec iv = new IvParameterSpec(vectorKey.getBytes());cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);byte[] encrypted = cipher.doFinal(content.getBytes());return Base64.encodeBase64String(encrypted);}1.2 解密/*** content: 解密内容(base64编码格式)* slatKey: 加密时使⽤的盐,16位字符串* vectorKey: 加密时使⽤的向量,16位字符串*/public String decrypt(String base64Content, String slatKey, String vectorKey) throws Exception {Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");SecretKey secretKey = new SecretKeySpec(slatKey.getBytes(), "AES");IvParameterSpec iv = new IvParameterSpec(vectorKey.getBytes());cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);byte[] content = Base64.decodeBase64(base64Content);byte[] encrypted = cipher.doFinal(content);return new String(encrypted);}1.3 代码解释上⾯简单实现了AES("AES/CBC/PKCS5Padding")的加密和解密。
java使用RSA加密方式实现数据加密解密的代码
java使⽤RSA加密⽅式实现数据加密解密的代码RSA的应⽤RSA是⼀种⾮对称加密算法。
现在,很多登陆表单的密码的都采⽤RSA加密,例如京东中的登陆使⽤公钥对密码进⾏加密java使⽤RSA加密⽅式实现数据加密解密,需要⾸先产⽣私钥和公钥测试代码public static void main(String args[]){try {RSADemo rsa=new RSADemo();rsa.generateKey();byte[] data=rsa.encrypt("luanpeng".getBytes());byte[] data1=rsa.decrypt(data);String str=new String(data1);System.out.println(str);} catch (Exception e) {System.out.println(e.toString());}}RSA⼯具类的实现package com.lp.app.safe;import java.security.*;import java.security.interfaces.*;import java.math.*;public class RSADemo {public RSADemo() {}PublicKey pbkey;PrivateKey prkey;public void generateKey() {try {KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");kpg.initialize(1024);KeyPair kp = kpg.genKeyPair();pbkey = kp.getPublic();prkey = kp.getPrivate();} catch (Exception e) {}}//加密,需要公钥public byte[] encrypt(byte[] ptext) throws Exception {// 获取公钥及参数e,nRSAPublicKey pbk = (RSAPublicKey)pbkey;BigInteger e = pbk.getPublicExponent();BigInteger n = pbk.getModulus();// 获取明⽂mBigInteger m = new BigInteger(ptext);// 计算密⽂cBigInteger c = m.modPow(e, n);return c.toByteArray();}//使⽤私钥进⾏解密public byte[] decrypt(byte[] ctext) throws Exception {// 读取密⽂BigInteger c = new BigInteger(ctext);// 读取私钥RSAPrivateKey prk = (RSAPrivateKey)prkey;BigInteger d = prk.getPrivateExponent();// 获取私钥参数及解密BigInteger n = prk.getModulus();BigInteger m = c.modPow(d, n);// 显⽰解密结果byte[] mt = m.toByteArray();return mt;}}总结以上所述是⼩编给⼤家介绍的java使⽤RSA加密⽅式实现数据加密解密的代码,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。
java的非对称性加密服务技术分析
java的非对称性加密服务技术分析鉴于rsa加密的重要性与拖累源代码的匮乏,经过整顿特此贴出。
需要下载bcprov-jdk14-123.jar。
import javax.crypto.Cipher。
import java.security.*。
import java.security.spec.RSAPublicKeySpec。
import java.security.spec.RSAPrivateKeySpec。
import java.security.spec.InvalidKeySpecException。
import java.security.interfaces.RSAPrivateKey。
import java.security.interfaces.RSAPublicKey。
import java.io.*。
import java.math.BigInteger。
/*** RSA 东西类。
供给加密,解密,天生密钥平匀办法。
* 需要到下载bcprov-jdk14-123.jar。
**/public class RSAUtil {/*** 天生密钥对* @return KeyPair* @throws EncryptException*/public static KeyPair generateKeyPair() throws EncryptException {try {KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",new org.bouncycastle.jce.provider.BouncyCastleProvider())。
final int KEY_SIZE = 1024。
//没什么好说的了,这个值相干到块加密的大小,可以变幻,然而不要太大,不然服从会低keyPairGen.initialize(KEY_SIZE, new SecureRandom())。
非对称加密RSA加密文件
⾮对称加密RSA加密⽂件RSA加密⽂件 关于RSA⾮对称加密很多地⽅都有讲解。
下⾯是AES AES 类import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.security.Key;import java.security.SecureRandom;import javax.crypto.Cipher;import javax.crypto.CipherInputStream;import javax.crypto.CipherOutputStream;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;/*** <p>* AES加密解密⼯具包* </p>** @author IceWee* @date 2012-5-18* @version 1.0*/public class AESUtils {private static final String ALGORITHM = "AES";private static final int KEY_SIZE = 256;private static final int CACHE_SIZE = 1024;/*** <p>* ⽣成随机密钥* </p>** @return* @throws Exception*/public static String getSecretKey() throws Exception {return getSecretKey(null);//return "X9qY3q630+wI/kLuKo1cBA==";}/*** <p>* ⽣成密钥* </p>** @param seed 密钥种⼦* @return* @throws Exception*/public static String getSecretKey(String seed) throws Exception {KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);SecureRandom secureRandom;if (seed != null && !"".equals(seed)) {secureRandom = new SecureRandom(seed.getBytes());} else {secureRandom = new SecureRandom();}keyGenerator.init(KEY_SIZE, secureRandom);SecretKey secretKey = keyGenerator.generateKey();System.out.println("密钥种⼦:"+Base64Utils.encode(secretKey.getEncoded()));return Base64Utils.encode(secretKey.getEncoded());}/*** <p>* 加密* </p>** @param data* @param key* @return* @throws Exception*/public static byte[] encrypt(byte[] data, String key) throws Exception {Key k = toKey(Base64Utils.decode(key));byte[] raw = k.getEncoded();SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);Cipher cipher = Cipher.getInstance(ALGORITHM);cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);return cipher.doFinal(data);/*** <p>* ⽂件加密* </p>** @param key* @param sourceFilePath* @param destFilePath* @throws Exception*/public static void encryptFile(String key, String sourceFilePath, String destFilePath) throws Exception { File sourceFile = new File(sourceFilePath);File destFile = new File(destFilePath);if (sourceFile.exists() && sourceFile.isFile()) {if (!destFile.getParentFile().exists()) {destFile.getParentFile().mkdirs();}destFile.createNewFile();InputStream in = new FileInputStream(sourceFile);OutputStream out = new FileOutputStream(destFile);Key k = toKey(Base64Utils.decode(key));byte[] raw = k.getEncoded();SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);Cipher cipher = Cipher.getInstance(ALGORITHM);cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);CipherInputStream cin = new CipherInputStream(in, cipher);byte[] cache = new byte[CACHE_SIZE];int nRead = 0;while ((nRead = cin.read(cache)) != -1) {out.write(cache, 0, nRead);out.flush();}out.close();cin.close();in.close();}}/*** <p>* 解密* </p>** @param data* @param key* @return* @throws Exception*/public static byte[] decrypt(byte[] data, String key) throws Exception {Key k = toKey(Base64Utils.decode(key));byte[] raw = k.getEncoded();SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);Cipher cipher = Cipher.getInstance(ALGORITHM);cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);return cipher.doFinal(data);}/*** <p>* ⽂件解密* </p>** @param key* @param sourceFilePath* @param destFilePath* @throws Exception*/public static void decryptFile(String key, String sourceFilePath, String destFilePath) throws Exception { File sourceFile = new File(sourceFilePath);File destFile = new File(destFilePath);if (sourceFile.exists() && sourceFile.isFile()) {if (!destFile.getParentFile().exists()) {destFile.getParentFile().mkdirs();}destFile.createNewFile();FileInputStream in = new FileInputStream(sourceFile);FileOutputStream out = new FileOutputStream(destFile);Key k = toKey(Base64Utils.decode(key));byte[] raw = k.getEncoded();SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);Cipher cipher = Cipher.getInstance(ALGORITHM);cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);CipherOutputStream cout = new CipherOutputStream(out, cipher);byte[] cache = new byte[CACHE_SIZE];int nRead = 0;while ((nRead = in.read(cache)) != -1) {cout.write(cache, 0, nRead);cout.flush();}cout.close();out.close();in.close();}}* <p>* 转换密钥* </p>** @param key* @return* @throws Exception*/private static Key toKey(byte[] key) throws Exception {SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);return secretKey;}}Base64Utils.javaimport java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;/*** <p>* BASE64编码解码⼯具包* </p>* <p>* 依赖javabase64-1.3.1.jar* </p>** @author IceWee* @date 2012-5-19* @version 1.0*/public class Base64Utils {/*** ⽂件读取缓冲区⼤⼩*/private static final int CACHE_SIZE = 1024;/*** <p>* BASE64字符串解码为⼆进制数据* </p>** @param base64* @return* @throws Exception*/public static byte[] decode(String base64) throws Exception {return Base64.decode(base64);}/*** <p>* ⼆进制数据编码为BASE64字符串* </p>** @param bytes* @return* @throws Exception*/public static String encode(byte[] bytes) throws Exception {return new String(Base64.encode(bytes));}/*** <p>* 将⽂件编码为BASE64字符串* </p>* <p>* ⼤⽂件慎⽤,可能会导致内存溢出* </p>** @param filePath ⽂件绝对路径* @return* @throws Exception*/public static String encodeFile(String filePath) throws Exception {byte[] bytes = fileToByte(filePath);return encode(bytes);}/*** <p>* BASE64字符串转回⽂件* </p>* @param filePath ⽂件绝对路径* @param base64 编码字符串* @throws Exception*/public static void decodeToFile(String filePath, String base64) throws Exception { byte[] bytes = decode(base64);byteArrayToFile(bytes, filePath);}/*** <p>* ⽂件转换为⼆进制数组* </p>** @param filePath ⽂件路径* @return* @throws Exception*/public static byte[] fileToByte(String filePath) throws Exception {byte[] data = new byte[0];File file = new File(filePath);if (file.exists()) {FileInputStream in = new FileInputStream(file);ByteArrayOutputStream out = new ByteArrayOutputStream(2048);byte[] cache = new byte[CACHE_SIZE];int nRead = 0;while ((nRead = in.read(cache)) != -1) {out.write(cache, 0, nRead);out.flush();}out.close();in.close();data = out.toByteArray();}return data;}/*** <p>* ⼆进制数据写⽂件* </p>** @param bytes ⼆进制数据* @param filePath ⽂件⽣成⽬录*/public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception { InputStream in = new ByteArrayInputStream(bytes);File destFile = new File(filePath);if (!destFile.getParentFile().exists()) {destFile.getParentFile().mkdirs();}destFile.createNewFile();OutputStream out = new FileOutputStream(destFile);byte[] cache = new byte[CACHE_SIZE];int nRead = 0;while ((nRead = in.read(cache)) != -1) {out.write(cache, 0, nRead);out.flush();}out.close();in.close();}}下⾯是RSAimport java.util.Collection;import java.util.Map;public abstract class Assert {public Assert() {}public static void isTrue(boolean expression, String message) {if (!expression) {throw new IllegalArgumentException(message);}}public static void isNull(Object object, String message) {if (object != null) {throw new IllegalArgumentException(message);}}public static void notNull(Object object, String message) {if (object == null) {throw new IllegalArgumentException(message);}}public static void hasLength(String text, String message) {if (!hasLength(text)) {throw new IllegalArgumentException(message);}public static void hasText(String text, String message) {if (!hasText(text)) {throw new IllegalArgumentException(message);}}public static void doesNotContain(String textToSearch, String substring, String message) {if (hasLength(textToSearch) && hasLength(substring) && textToSearch.contains(substring)) {throw new IllegalArgumentException(message);}}public static void notEmpty(Object[] array, String message) {if (array == null || array.length == 0) {throw new IllegalArgumentException(message);}}public static void noNullElements(Object[] array, String message) {if (array != null) {Object[] var2 = array;int var3 = array.length;for (int var4 = 0; var4 < var3; ++var4) {Object element = var2[var4];if (element == null) {throw new IllegalArgumentException(message);}}}}public static void notEmpty(Collection<?> collection, String message) {if (isEmpty(collection)) {throw new IllegalArgumentException(message);}}public static void notEmpty(Map<?, ?> map, String message) {if (isEmpty(map)) {throw new IllegalArgumentException(message);}}public static void isInstanceOf(Class<?> type, Object obj, String message) {notNull(type, "Type to check against must not be null");if (!type.isInstance(obj)) {throw new IllegalArgumentException((hasLength(message) ? message + " " : "") + "Object of class [" + (obj != null ? obj.getClass().getName() : "null") + "] must be an instance of " + type); }}public static void isAssignable(Class<?> superType, Class<?> subType, String message) {notNull(superType, "Type to check against must not be null");if (subType == null || !superType.isAssignableFrom(subType)) {throw new IllegalArgumentException(message + subType + " is not assignable to " + superType);}}private static boolean hasLength(CharSequence str) {return str != null && str.length() > 0;}private static boolean hasText(CharSequence str) {if (!hasLength(str)) {return false;} else {int strLen = str.length();for (int i = 0; i < strLen; ++i) {if (!Character.isWhitespace(str.charAt(i))) {return true;}}return false;}}private static boolean isEmpty(Collection<?> collection) {return collection == null || collection.isEmpty();}public static boolean isEmpty(Map<?, ?> map) {return map == null || map.isEmpty();}}import java.nio.charset.Charset;import mons.codec.binary.Base64;public abstract class Base64Code {private static final int CACHE_SIZE = 1024;private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");private static final Base64Delegate delegate = new CommonsCodecBase64Delegate();public Base64Code() {}private static void assertSupported() {Assert.isTrue(delegate != null, "Apache Commons Codec not found - Base64 encoding not supported````````"); }public static byte[] encode(byte[] src) {assertSupported();return delegate.encode(src);}public static String encodeToString(byte[] src) {assertSupported();if (src == null) {return null;} else {return src.length == 0 ? "" : new String(delegate.encode(src), DEFAULT_CHARSET);}}public static byte[] decode(byte[] src) {assertSupported();return delegate.decode(src);}public static byte[] decodeFromString(String src) {assertSupported();if (src == null) {return null;} else {return src.length() == 0 ? new byte[0] : delegate.decode(src.getBytes(DEFAULT_CHARSET));}}private static class CommonsCodecBase64Delegate implements Base64Delegate {private final Base64 base64;private CommonsCodecBase64Delegate() {this.base64 = new Base64();}public byte[] encode(byte[] src) {return this.base64.encode(src);}public byte[] decode(byte[] src) {return this.base64.decode(src);}}private interface Base64Delegate {byte[] encode(byte[] var1);byte[] decode(byte[] var1);}}import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.security.Key;import java.security.KeyFactory;import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.NoSuchAlgorithmException;import java.security.interfaces.RSAPrivateKey;import java.security.interfaces.RSAPublicKey;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.X509EncodedKeySpec;import java.util.HashMap;import java.util.Map;import javax.crypto.Cipher;import javax.crypto.CipherInputStream;import javax.crypto.CipherOutputStream;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;/*** RSA加解密⽅法。
Java非对称加密(三)-代码及说明
} X509EncodedKeySpec keySpec = new X509EncodedKeySpec (publicKeyByte s); return keyFactory.generatePublic (keySpec); } catch (Exception e) { throw new RuntimeException ("load publicKey fail. " + e.getMessage ()); } } /** * 加载公钥(base64) * * @param publicKeyBase64 * 秘钥为BASE64编码 * @param keyAlgorithm * 如:RSA * @param providerName * 可以为空,如:BC * @return */ public static PublicKey loadPublicKey (String publicKeyBase64, String keyA lgorithm, String providerName) { byte [] publicKeyBytes = Encodes.decodeBase64(publicKeyBase64); return loadPublicKey (publicKeyBytes, keyAlgorithm, providerName); } /** * 加载公钥(⽂文件pem) * * @param publicKeyFile * 公钥秘钥⽂文件,内容为BASE64编码 * @param keyAlgorithm * 如:RSA * @param providerName * 可以为空,如:BC * @return */ public static PublicKey loadPublicKey (File publicKeyFile, String keyAlgor ithm, String providerName) { byte [] publicKeyBytes = null; try { publicKeyBytes = Encodes.decodeBase64(FileUtils.readFileToString (publicKeyFile));} catch (Exception e) {throw new RuntimeException ("加载公钥⽂文件内容失败:" + e.getMessage ())23242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768私钥的加载默认同公钥,这⾥里里不不在贴代码,从公钥稍微调整下就OKthrow new RuntimeException ("加载公钥⽂文件内容失败:" + e.getMessage ()); } finally { IOUtils.closeQuietly (in); } } /** * 从keystore 加载公钥 * * @param keystoreUri * @param keystoreType * @param keystorePassword * @return */ public static PublicKey loadPublicKeyFromKeyStore (String keystoreUri, Str ing keystoreType, String keystorePassword) { InputStream in = null; try { KeyStore keyStore = KeyStore.getInstance (keystoreType); Resource resource = new DefaultResourceLoader ().getResource (keyst oreUri); in = resource.getInputStream (); keyStore.load (in, keystorePassword.toCharArray ()); Enumeration <String > enumas = keyStore.aliases (); String keyAlias = null; if (enumas.hasMoreElements ()) { keyAlias = enumas.nextElement (); } return keyStore.getCertificate (keyAlias).getPublicKey ();} catch (Exception e) {throw new RuntimeException ("通过keystore 加载证书公钥失败:" + e.getMe ssage ());} finally {IOUtils.closeQuietly (in);}}4041424344454647484950515253545556575859606162636465666768697071私钥的加载加密和解密while (inputLen - offSet > 0) { if (inputLen - offSet > plainLength) { cache = cipher.doFinal (plainBytes, offSet, plainLength); } else { cache = cipher.doFinal (plainBytes, offSet, inputLen - off Set); } out.write (cache, 0, cache.length); i ++; offSet = i * plainLength; } byte [] encryptedData = out.toByteArray (); return encryptedData; } catch (Exception e) { throw new RuntimeException ("publicKey encrypt fail:" + e.getMessa ge ()); } finally { IOUtils.closeQuietly (out); } } public static String encryptByPublicKeyBase64(String plainText, PublicKey publicKey, String charset) { return Encodes.encodeBase64(encryptByPublicKey (getBytes (plainText, ch arset), publicKey)); } public static String encryptByPublicKeyBase64(String plainText, PublicKey publicKey) { return encryptByPublicKeyBase64(plainText, publicKey, DEFAULT_CHARSET ); }public static String encryptByPublicKeyHex (String plainText, PublicKey pu blicKey, String charset) {return Encodes.encodeHex (encryptByPublicKey (getBytes (plainText, chars et), publicKey));}public static String encryptByPublicKeyHex (String plainText, PublicKey pu blicKey) {return encryptByPublicKeyHex (plainText, publicKey, DEFAULT_CHARSET);}262728293031323334353637383940414243444546474849505152535455565758私钥解密/**1* 私钥解密 * * @param encryptedBytes * 密⽂文数据bytes * @param privateKey * 私钥 * @return 明⽂文数据bytes */ public static byte [] decryptByPrivateKey (byte [] encryptedBytes, PrivateKe y privateKey) { ByteArrayOutputStream out = null; try { Cipher cipher = Cipher.getInstance (privateKey.getAlgorithm ()); cipher.init (Cipher.DECRYPT_MODE, privateKey); int inputLen = encryptedBytes.length; out = new ByteArrayOutputStream (); int offSet = 0; byte [] cache; int i = 0; // 对数据分段解密 int keyLength = ((RSAPrivateKey) privateKey).getModulus ().bitLeng th () / 8; while (inputLen - offSet > 0) { if (inputLen - offSet > keyLength) { cache = cipher.doFinal (encryptedBytes, offSet, keyLength); } else { cache = cipher.doFinal (encryptedBytes, offSet, inputLen - offSet); } out.write (cache, 0, cache.length); i ++; offSet = i * keyLength; } byte [] decryptedData = out.toByteArray (); return decryptedData; } catch (Exception e) { throw new RuntimeException ("privateKey decrypt fail:" + e.getMess age ()); } finally { IOUtils.closeQuietly (out); } } public static String decryptByPrivateKeyBase64(String encryptedBase64, Pr ivateKey privateKey, String charset) { byte [] plainBytes = decryptByPrivateKey (Encodes.decodeBase64(encrypte dBase64), privateKey);2345678910111213141516171819202122232425262728293031323334353637383940414243444546474849签名和验签基本⽆无需考虑性能问题,我在imac 上实际测试⼀一般Signature 的初始化在2ms 左右,除⾮非要求极致性能,否则也不不⽤用做线程缓存。
javaRSAUtils加密工具类操作
javaRSAUtils加密⼯具类操作1.RSA加密算法是⼀种⾮对称加密算法。
在公开密钥加密和电⼦商业中RSA被⼴泛使⽤。
RSA公开密钥密码体制。
所谓的公开密钥密码体制就是使⽤不同的加密密钥与解密密钥,是⼀种“由已知加密密钥推导出解密密钥在计算上是不可⾏的”密码体制。
在公开密钥密码体制中,加密密钥(即公开密钥)PK是公开信息,⽽解密密钥(即秘密密钥)SK是需要保密的。
加密算法E和解密算法D也都是公开的。
虽然解密密钥SK是由公开密钥PK决定的,但却不能根据PK计算出SK。
2.本⼯具类涉及到BASE64编码,所以先展⽰出BASE64Utils:package mon.util;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;import java.security.MessageDigest;/*** BASE64的加解密* @author Neo* @date 2018-4-15 22:21:51**/@SuppressWarnings("restriction")public class Base64Utils {public static final String KEY_SHA = "SHA";public static final String KEY_MD5 = "MD5";/*** BASE64解密** @param key* @return* @throws Exception*/public static byte[] decryptBASE64(String key) throws Exception {return (new BASE64Decoder()).decodeBuffer(key);}/*** BASE64加密** @param key* @return* @throws Exception*/public static String encryptBASE64(byte[] key) throws Exception {return (new BASE64Encoder()).encodeBuffer(key);}/*** MD5加密** @param data* @return* @throws Exception*/public static byte[] encryptMD5(byte[] data) throws Exception {MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);md5.update(data);return md5.digest();}/*** SHA加密** @param data* @return* @throws Exception*/public static byte[] encryptSHA(byte[] data) throws Exception {MessageDigest sha = MessageDigest.getInstance(KEY_SHA);sha.update(data);return sha.digest();}}3.然后我们展⽰RSAUtils:package mon.util;import javax.crypto.Cipher;import java.security.*;import java.security.interfaces.RSAPrivateKey;import java.security.interfaces.RSAPublicKey;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.X509EncodedKeySpec;import java.util.HashMap;import java.util.Map;/*** RSA安全编码组件** @version 1.0* @desc 公钥和私钥存放在properties⽂件的时候每⾏的末尾加上“\r\n\” <br/>* “\r\n” 起到换⾏的作⽤,最后的“\”在properties在⾥表⽰连接** @author Neo* @date 2018-4-15 22:23:19* @since 1.0*/public class RSAUtils extends Base64Utils {public static final String KEY_ALGORITHM = "RSA";public static final String SIGNATURE_ALGORITHM = "MD5withRSA";private static final String PUBLIC_KEY = "RSAPublicKey";private static final String PRIVATE_KEY = "RSAPrivateKey";/*** ⽤私钥对信息⽣成数字签名** @param data 加密数据* @param privateKey 私钥* @return* @throws Exception*/public static String sign(String data, String privateKey) throws Exception {return sign(data.getBytes(), privateKey);}/*** ⽤私钥对信息⽣成数字签名** @param data 加密数据* @param privateKey 私钥* @return* @throws Exception*/public static String sign(byte[] data, String privateKey) throws Exception {// 解密由base64编码的私钥byte[] keyBytes = decryptBASE64(privateKey);// 构造PKCS8EncodedKeySpec对象PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); // KEY_ALGORITHM 指定的加密算法KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);// 取私钥匙对象PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);// ⽤私钥对信息⽣成数字签名Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);signature.initSign(priKey);signature.update(data);return encryptBASE64(signature.sign());/*** 校验数字签名** @param data 加密数据* @param publicKey 公钥* @param sign 数字签名* @return 校验成功返回true 失败返回false* @throws Exception*/public static boolean verify(String data, String publicKey, String sign) throws Exception { return verify(data.getBytes(), publicKey, sign);}/*** 校验数字签名** @param data 加密数据* @param publicKey 公钥* @param sign 数字签名* @return 校验成功返回true 失败返回false* @throws Exception*/public static boolean verify(byte[] data, String publicKey, String sign) throws Exception { // 解密由base64编码的公钥byte[] keyBytes = decryptBASE64(publicKey);// 构造X509EncodedKeySpec对象X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);// KEY_ALGORITHM 指定的加密算法KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);// 取公钥匙对象PublicKey pubKey = keyFactory.generatePublic(keySpec);Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);signature.initVerify(pubKey);signature.update(data);// 验证签名是否正常return signature.verify(decryptBASE64(sign));}/*** 解密<br>* ⽤私钥解密** @param data* @param key* @return* @throws Exception*/public static String decryptByPrivateKey(String data, String key) throws Exception {return new String(decryptByPrivateKey(Base64Utils.decryptBASE64(data), key));}/*** 解密<br>* ⽤私钥解密** @param data* @param key* @return* @throws Exception*/public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception {// 对密钥解密byte[] keyBytes = decryptBASE64(key);// 取得私钥PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);// 对数据解密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE, privateKey);return cipher.doFinal(data);}/*** 解密<br>* ⽤私钥解密** @param data* @param key* @return* @throws Exception*/public static String decryptByPublicKey(String data, String key) throws Exception { return new String(decryptByPublicKey(Base64Utils.decryptBASE64(data), key)); }/*** 解密<br>* ⽤私钥解密** @param data* @param key* @return* @throws Exception*/public static byte[] decryptByPublicKey(byte[] data, String key) throws Exception { // 对密钥解密byte[] keyBytes = decryptBASE64(key);// 取得公钥X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key publicKey = keyFactory.generatePublic(x509KeySpec);// 对数据解密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE, publicKey);return cipher.doFinal(data);}/*** 加密<br>* ⽤公钥加密** @param data* @param key* @return* @throws Exception*/public static String encryptByPublicKey(String data, String key) throws Exception { return Base64Utils.encryptBASE64(encryptByPublicKey(data.getBytes(), key)); }/*** 加密<br>* ⽤公钥加密** @param data* @param key* @return* @throws Exception*/public static byte[] encryptByPublicKey(byte[] data, String key) throws Exception { // 对公钥解密byte[] keyBytes = decryptBASE64(key);// 取得公钥X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key publicKey = keyFactory.generatePublic(x509KeySpec);// 对数据加密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE, publicKey);return cipher.doFinal(data);}/*** 加密<br>* ⽤私钥加密** @param data* @param key* @return* @throws Exception*/public static String encryptByPrivateKey(String data, String key) throws Exception { return Base64Utils.encryptBASE64(encryptByPrivateKey(data.getBytes(), key)); }/*** 加密<br>* ⽤私钥加密** @param data* @param key* @return* @throws Exception*/public static byte[] encryptByPrivateKey(byte[] data, String key) throws Exception { // 对密钥解密byte[] keyBytes = decryptBASE64(key);// 取得私钥PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);// 对数据加密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE, privateKey);return cipher.doFinal(data);}/*** 取得私钥** @param keyMap* @return* @throws Exception*/public static String getPrivateKey(Map<String, Object> keyMap) throws Exception { Key key = (Key) keyMap.get(PRIVATE_KEY);return encryptBASE64(key.getEncoded());}/*** 取得公钥** @param keyMap* @return* @throws Exception*/public static String getPublicKey(Map<String, Object> keyMap) throws Exception {Key key = (Key) keyMap.get(PUBLIC_KEY);return encryptBASE64(key.getEncoded());}/*** 初始化密钥** @return* @throws Exception*/public static Map<String, Object> initKey() throws Exception {KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyPairGen.initialize(1024);KeyPair keyPair = keyPairGen.generateKeyPair();// 公钥RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();// 私钥RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();Map<String, Object> keyMap = new HashMap<String, Object>(2);keyMap.put(PUBLIC_KEY, publicKey);keyMap.put(PRIVATE_KEY, privateKey);return keyMap;}public static void main(String[] args) {try {Map<String, Object> map = RSAUtils.initKey();String publicKey = RSAUtils.getPublicKey(map);String privateKey = RSAUtils.getPrivateKey(map);System.out.println("公钥:" + publicKey);System.out.println("私钥:" + privateKey);String data = "Java是世界上最好的编程语⾔";String encryptData = RSAUtils.encryptByPublicKey(data, publicKey);System.out.println("加密后:" + encryptData);String decryptData = RSAUtils.decryptByPrivateKey(encryptData, privateKey);System.out.println("解密后:" + decryptData);} catch (Exception e) {e.printStackTrace();}}}4.最后展⽰测试结果:补充知识:java使⽤RSA⽣成公钥和私钥,并进⾏加解密废话不多说,上代码:import javax.crypto.Cipher;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;import java.security.KeyFactory;import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.SecureRandom;import java.security.interfaces.RSAPrivateKey;import java.security.interfaces.RSAPublicKey;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.X509EncodedKeySpec;import java.util.HashMap;import java.util.Map;/*** Java RSA 加密⼯具类*/public class RSAUtils {/*** 密钥长度于原⽂长度对应以及越长速度越慢*/private final static int KEY_SIZE = 1024;/*** ⽤于封装随机产⽣的公钥与私钥*/private static Map<Integer, String> keyMap = new HashMap<Integer, String>();/*** 随机⽣成密钥对* @throws Exception*/public static void genKeyPair() throws Exception {// KeyPairGenerator类⽤于⽣成公钥和私钥对,基于RSA算法⽣成对象KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");// 初始化密钥对⽣成器keyPairGen.initialize(KEY_SIZE, new SecureRandom());// ⽣成⼀个密钥对,保存在keyPair中KeyPair keyPair = keyPairGen.generateKeyPair();// 得到私钥RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();// 得到公钥RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();String publicKeyString = encryptBASE64(publicKey.getEncoded());// 得到私钥字符串String privateKeyString = encryptBASE64(privateKey.getEncoded());// 将公钥和私钥保存到Map//0表⽰公钥keyMap.put(0, publicKeyString);//1表⽰私钥keyMap.put(1, privateKeyString);}//编码返回字符串public static String encryptBASE64(byte[] key) throws Exception {return (new BASE64Encoder()).encodeBuffer(key);}//解码返回bytepublic static byte[] decryptBASE64(String key) throws Exception {return (new BASE64Decoder()).decodeBuffer(key);}/*** RSA公钥加密** @param str 加密字符串* @param publicKey 公钥* @return 密⽂* @throws Exception 加密过程中的异常信息*/public static String encrypt(String str, String publicKey) throws Exception {//base64编码的公钥byte[] decoded = decryptBASE64(publicKey);RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded)); //RSA加密Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, pubKey);String outStr = encryptBASE64(cipher.doFinal(str.getBytes("UTF-8")));return outStr;}/*** RSA私钥解密** @param str 加密字符串* @param privateKey 私钥* @return 明⽂* @throws Exception 解密过程中的异常信息*/public static String decrypt(String str, String privateKey) throws Exception {//64位解码加密后的字符串byte[] inputByte = decryptBASE64(str);//base64编码的私钥byte[] decoded = decryptBASE64(privateKey);RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));//RSA解密Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.DECRYPT_MODE, priKey);String outStr = new String(cipher.doFinal(inputByte));return outStr;}public static void main(String[] args) throws Exception {long temp = System.currentTimeMillis();//⽣成公钥和私钥genKeyPair();//加密字符串System.out.println("公钥:" + keyMap.get(0));System.out.println("私钥:" + keyMap.get(1));System.out.println("⽣成密钥消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");String message = "RSA测试aaa";System.out.println("原⽂:" + message);temp = System.currentTimeMillis();String messageEn = encrypt(message, keyMap.get(0));System.out.println("密⽂:" + messageEn);System.out.println("加密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");temp = System.currentTimeMillis();String messageDe = decrypt(messageEn, keyMap.get(1));System.out.println("解密:" + messageDe);System.out.println("解密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");}}以上这篇java RSAUtils 加密⼯具类操作就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
非对称加密解密算法RSA的C实现
非对称加密解密算法RSA的C实现RSA加密算法是一种非对称加密算法,常用于数据加密和数字签名。
其安全性基于大数分解的困难性,即质因数分解。
RSA加密算法的全称为Rivest-Shamir-Adleman加密算法,是由Ron Rivest、Adi Shamir和Leonard Adleman于1977年共同提出的。
RSA算法的加密过程如下:1.选择两个不同的质数p和q,计算它们的乘积n=p*q。
2.选择一个整数e,满足1<e<φ(n),且e和φ(n)互质,其中φ(n)=(p-1)*(q-1)。
3. 计算e关于φ(n)的模反元素d,即满足(e*d)mod φ(n) = 14.公钥为(n,e),私钥为(n,d)。
5. 对于要加密的明文m,使用公钥(n, e)进行加密,得到密文c,公式为c = (m^e)mod n。
6. 对于要解密的密文c,使用私钥(n, d)进行解密,得到明文m,公式为m = (c^d)mod n。
以下是使用C语言实现RSA加密和解密的代码:```c#include <stdio.h>#include <stdlib.h>#include <math.h>//求最大公约数int gcd(int a, int b)if (b == 0)return a;return gcd(b, a % b);//求模反元素int mod_inverse(int e, int phi) int d;for (d = 1; d <= phi; d++)if ((e * d) % phi == 1)return d;}return -1; // 模反元素不存在//加密函数int encrypt(int m, int e, int n) int c = fmod(pow(m, e), n); return c;//解密函数int decrypt(int c, int d, int n)int m = fmod(pow(c, d), n);return m;//主函数int maiint p, q, n, phi, e, d, m, c;printf("请输入两个质数p和q: ");scanf("%d%d", &p, &q);n=p*q;phi = (p - 1) * (q - 1);printf("请输入一个整数e(1 < e < %d且与%d互质): ", phi, phi);scanf("%d", &e);// 检查e和phi是否互质if (gcd(e, phi) != 1)printf("输入的e不符合要求,请重新输入!\n");return 0;}d = mod_inverse(e, phi);if (d == -1)printf("模反元素不存在,解密失败!\n");return 0;}printf("请输入要加密的明文m: ");scanf("%d", &m);c = encrypt(m, e, n);printf("加密后的密文c为: %d\n", c);m = decrypt(c, d, n);printf("解密后的明文m为: %d\n", m);return 0;```以上代码中,首先通过输入两个质数p和q,计算得到公共模数n和欧拉函数φ(n),然后要求输入一个符合条件的整数e,通过计算求得模反元素d。
Java使用数字证书加密文件(含代码)
JA V A 使用数字证书加密解密文件总结目录1.编写目的 (3)2.JA V A生产数字证书 (4)2.1.1 keystore(JKS) 的生成 (4)2.1.2 导出公钥 (5)3.使用JKS私钥加密文件 (5)4.转换为PFX格式私钥 (6)5.使用PFX加密文件 (7)6 源代码 (8)6.1 用到的JAR包 (8)6.2 示例代码 (8)6.2.1 Test.java (8)6.2.2 RsaUtil.java (10)6.2.3 Base64.java (19)7.结束语 (26)1.编写目的学习RSA算法,读取数字证书中的私钥对文件进行加密,使用数字证书的公钥解密,这种方式就是RSA算法.自己对RSA算法的理解:⏹私钥加密公钥解密:如果用私钥对文件加密,发给别人,别人用我公布的公钥进行解密,实现这个文件就是我本人制作的,不是别人做的.⏹公钥加密私钥解密:如果别人用我的公钥加密文件,那么只能我一个人看,只有使用我的私钥进行解密,私钥一定是不能告诉其他人的.本文讲解如何用JKS私钥对文件进行加密,用对于CRT公钥进行解密,将JKS私钥转换为PFX格式私钥,并用PFX私钥对文件进行加密解密Jks:是JA V A的keytools证书工具支持的证书私钥格式pfx:是微软支持的私钥格式⏹2.JAVA生产数字证书为了实现数字证书加密文件,我们首先要制作几个数字证书,如果你已经有了pfx格式的数字证书并且知道其密码,以及对应crt或者cer格式的公钥证书则跳过本章.2.1 keytool 创建数字证书Keytool是一个Java数据证书的管理工具,Keytool将密钥(key)和证书(certificates)存在一个称为keystore的文件中在keystore里,包含两种数据:⏹密钥实体(Key entity):密钥(secret key)又或者是私钥⏹配对公钥(采用非对称加密):可信任的证书实体(trusted certificate entries),只包含公钥2.1.1 keystore(JKS) 的生成●分阶段生成:命令格式:keytool -genkey -alias yushan(别名) -keypass yushan(别名密码) -keyalg RSA(算法) -keysize 1024(密钥长度) -validity 365(有效期,天单位) -keystore e:\yushan.keystore(指定生成证书的位置和证书名称) -storepass 123456(获取keystore信息的密码);示例:1)cmd下进入java/bin2)输入命令keytool -genkey -alias myalias-keypass 123456-keyalg RSA-keysize 1024 -validity 365 -keystore d: \myalias.keystore -storepass 123456●一次性生成:keytool -genkey -alias yushan -keypass yushan -keyalg RSA -keysize 1024 -validity 365 -keystore e:\yushan.keystore -storepass 123456 -dname "CN=(名字与姓氏), OU=(组织单位名称), O=(组织名称), L=(城市或区域名称), ST=(州或省份名称), C=(单位的两字母国家代码)";(中英文即可)无例图2.1.2 导出公钥命令:keytool -export -alias myalias -keystore d:\myalias.keystore -file d:\myalias.crt -storepass 123456创建结果:3.使用JKS私钥加密文件//工具类RSAUtil rsa = new RSAUtil();//从jks私钥中获取私钥加密串PrivateKey priKeyFromKs = rsa.getPriKeyFromKS("d:\\myalias.keystore","123456", "myalias", "123456");//从jks私钥中获取公钥解密串PublicKey pubKeyFromKS = rsa.getPubKeyFromKS("d:\\myalias.keystore", "123456", "myalias");//从crt公钥中获取公钥解密串PublicKey pubKeyFromCrt = rsa.getPubKeyFromCRT("d:\\myalias.crt");//用私钥串加密rsa.encryptWithPrv("d:\\file.xml",priKeyFromKs,"d:\\file_encWithKSPri.xml", true);//用jks公钥串解密rsa.decryptWithPub("d:\\file_encWithKSPri.xml", pubKeyFromKS, true,"d:\\file_encWithKSPri_decKs.xml");//用crt公钥串解密rsa.decryptWithPub("d:\\file_encWithKSPri.xml", pubKeyFromCrt, true, "d:\\file_encWithKSPri_decCrt.xml");4.转换为PFX格式私钥如果你已经有了pfx格式的数字证书并且知道其密码,以及对应crt或者cer格式的公钥证书则跳过本章.4.1 转换工具转换工具我使用的是kestore-export下载kestore-export.rar 请百度搜索,我也会往CSDN上上传,请直接搜索kestore-export.rar。
RSA加密解密实现(JAVA)
RSA加密解密实现(JAVA)1.关于RSA算法的原理解析参考:2.RSA密钥长度、明⽂长度和密⽂长度参考:3.以下⽰例代码可以将密钥Base64转码之后保存到⽂本⽂件内,也可以从⽂本⽂件中读取密钥。
public class RSAGenerator {/*** 算法*/private String ALGORITHM_RSA = "RSA";private String DEFAULT_ENCODING = "UTF-8";public static final String KEY_TYPE_PUBLIC = "PUBLIC";public static final String KEY_TYPE_PRIVATE = "PRIVATE";/*** 公钥*/private RSAPublicKey publicKey;private String publicKeyStr;/*** 私钥*/private RSAPrivateKey privateKey;private String privateKeyStr;/*** ⽤于加解密*/private Cipher cipher;/*** 明⽂块的长度它必须⼩于密⽂块的长度 - 11*/private int originLength = 128;/*** 密⽂块的长度*/private int encrytLength = 256;/*** ⽣成密钥对* @return*/public RSAGenerator generateKeyPair() {try {// RSA加密算法KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM_RSA);// 创建密钥对,长度采⽤2048keyPairGenerator.initialize(2048);KeyPair keyPair = keyPairGenerator.generateKeyPair();// 分别得到公钥和私钥publicKey = (RSAPublicKey) keyPair.getPublic();privateKey = (RSAPrivateKey) keyPair.getPrivate();// 使⽤ Base64编码publicKeyStr = Base64Util.encode(publicKey.getEncoded());privateKeyStr = Base64Util.encode(privateKey.getEncoded());//将BASE64编码的结果保存到⽂件内String classPath = this.getClass().getClassLoader().getResource("").toString();String prefix = classPath.substring(classPath.indexOf(":") + 1);String publicFilePath = prefix+"public.txt";File publicFile= new File(publicFilePath);saveBase64KeyToFile(publicFile, publicKeyStr);String privateFilePath = prefix+"private.txt";File privateFile= new File(privateFilePath);saveBase64KeyToFile(privateFile, privateKeyStr);} catch (NoSuchAlgorithmException e) {e.printStackTrace();}return this;}/*** ⽤公钥加密* @param content* @return 加密后的16进制字符串*/public String encryptByPublic(String content) {String encode = "";try {cipher = Cipher.getInstance(ALGORITHM_RSA);cipher.init(Cipher.ENCRYPT_MODE, publicKey);// 该密钥能够加密的最⼤字节长度int splitLength = publicKey.getModulus().bitLength() / 8 - 11; byte[][] arrays = splitBytes(content.getBytes(), splitLength); // 加密StringBuffer buffer = new StringBuffer();for (byte[] array : arrays) {buffer.append(bytesToHexString(cipher.doFinal(array)));}encode = buffer.toString();} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();}return encode;}/*** ⽤私钥加密** @param content* @return 加密后的16进制字符串*/public String encryptByPrivate(String content) {try {Cipher cipher = Cipher.getInstance(ALGORITHM_RSA);cipher.init(Cipher.ENCRYPT_MODE, privateKey);// 该密钥能够加密的最⼤字节长度int splitLength = ((RSAPrivateKey) privateKey).getModulus() .bitLength() / 8 - 11;byte[][] arrays = splitBytes(content.getBytes(), splitLength); StringBuffer stringBuffer = new StringBuffer();for (byte[] array : arrays) {stringBuffer.append(bytesToHexString(cipher.doFinal(array))); }return stringBuffer.toString();} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();}return null;}/*** ⽤私钥解密* @param content* @return 解密后的原⽂*/public String decryptByPrivate(String content) {String decode = "";try {cipher = Cipher.getInstance(ALGORITHM_RSA);cipher.init(Cipher.DECRYPT_MODE, privateKey);// 该密钥能够加密的最⼤字节长度int splitLength = privateKey.getModulus().bitLength() / 8;byte[] contentBytes = hexStringToBytes(content);byte[][] arrays = splitBytes(contentBytes, splitLength);StringBuffer stringBuffer = new StringBuffer();for (byte[] array : arrays) {stringBuffer.append(new String(cipher.doFinal(array)));}decode = stringBuffer.toString();} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();}return decode;}/*** ⽤私钥解密** @param content* @return 解密后的原⽂*/public String decryptByPublic(String content) {String decode = "";try {cipher = Cipher.getInstance(ALGORITHM_RSA);cipher.init(Cipher.DECRYPT_MODE, publicKey);// 该密钥能够加密的最⼤字节长度int splitLength = publicKey.getModulus().bitLength() / 8;byte[] contentBytes = hexStringToBytes(content);byte[][] arrays = splitBytes(contentBytes, splitLength);StringBuffer stringBuffer = new StringBuffer();for (byte[] array : arrays) {stringBuffer.append(new String(cipher.doFinal(array)));}decode = stringBuffer.toString();} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();}return decode;}/*** 根据限定的每组字节长度,将字节数组分组* @param bytes 等待分组的字节组* @param splitLength 每组长度* @return 分组后的字节组*/public static byte[][] splitBytes(byte[] bytes, int splitLength) {// bytes与splitLength的余数int remainder = bytes.length % splitLength;// 数据拆分后的组数,余数不为0时加1int quotient = remainder > 0 ? bytes.length / splitLength + 1: bytes.length / splitLength;byte[][] arrays = new byte[quotient][];byte[] array = null;for (int i = 0; i < quotient; i++) {// 如果是最后⼀组(quotient-1),同时余数不等于0,就将最后⼀组设置为remainder的长度 if (i == quotient - 1 && remainder != 0) {array = new byte[remainder];System.arraycopy(bytes, i * splitLength, array, 0, remainder);} else {array = new byte[splitLength];System.arraycopy(bytes, i * splitLength, array, 0, splitLength);}arrays[i] = array;}return arrays;}/*** 将字节数组转换成16进制字符串* @param bytes 即将转换的数据* @return 16进制字符串*/public static String bytesToHexString(byte[] bytes) {StringBuffer sb = new StringBuffer(bytes.length);String temp = null;for (int i = 0; i < bytes.length; i++) {temp = Integer.toHexString(0xFF & bytes[i]);if (temp.length() < 2) {sb.append(0);}sb.append(temp);}return sb.toString();}/*** 将16进制字符串转换成字节数组** @param hex* 16进制字符串* @return byte[]*/public static byte[] hexStringToBytes(String hex) {int len = (hex.length() / 2);hex = hex.toUpperCase();byte[] result = new byte[len];char[] chars = hex.toCharArray();for (int i = 0; i < len; i++) {int pos = i * 2;result[i] = (byte) (toByte(chars[pos]) << 4 | toByte(chars[pos + 1])); }return result;}/*** 将char转换为byte** @param c* char* @return byte*/private static byte toByte(char c) {return (byte) "0123456789ABCDEF".indexOf(c);}/*** 保存公钥到⽂件** @param file* @return*/public boolean savePublicKey(File file) {return saveKeyToFile(publicKey, file);}/*** 保存私钥到⽂件** @param file* @return*/public boolean savePrivateKey(File file) {return saveKeyToFile(privateKey, file);}/*** 保存密钥到⽂件* @param key 密钥* @param file ⽂件* @return*/private boolean saveKeyToFile(Key key, File file) {boolean result = false;FileOutputStream fos = null;try {fos = new FileOutputStream(file);ObjectOutputStream oos = new ObjectOutputStream(fos);// 公钥默认使⽤的是X.509编码,私钥默认采⽤的是PKCS #8编码byte[] encode = key.getEncoded();// 注意,此处采⽤writeObject⽅法,读取时也要采⽤readObject⽅法oos.writeObject(encode);oos.close();result = true;} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {fos.close();} catch (IOException e) {e.printStackTrace();}}return result;}private boolean saveBase64KeyToFile(File file, String key) {boolean result = false;FileOutputStream fos = null;try {fos = new FileOutputStream(file);fos.write(key.getBytes());fos.close();result = true;} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {fos.close();} catch (IOException e) {e.printStackTrace();}}return result;}/*** 从BASE64⽂件中读取KEY值* @param fileName* @param keyType*/public void getKeyFromBase64File(String fileName,String keyType) {try {InputStream inputStream = this.getClass().getClassLoader().getResource(fileName).openStream(); ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] subByte = new byte[1024];int len = 0;while((len=inputStream.read(subByte))>0) {outStream.write(subByte,0,len);}inputStream.close();outStream.close();String base64Key = new String(outStream.toByteArray(), DEFAULT_ENCODING);byte[] keybyte = Base64Util.decode(base64Key);// 默认编码KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);if (KEY_TYPE_PUBLIC.equals(keyType)) {X509EncodedKeySpec x509eks = new X509EncodedKeySpec(keybyte);publicKey = (RSAPublicKey) keyFactory.generatePublic(x509eks);System.out.println(publicKey.getAlgorithm());} else {PKCS8EncodedKeySpec pkcs8eks = new PKCS8EncodedKeySpec(keybyte);privateKey = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8eks);}} catch (IOException e) {e.printStackTrace();} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (InvalidKeySpecException e) {e.printStackTrace();}/*** 从⽂件中得到公钥** @param file*/public void getPublicKey(File file) {getKey(file, KEY_TYPE_PUBLIC);}/*** 从⽂件中得到私钥** @param file*/public void getPrivateKey(File file) {getKey(file, KEY_TYPE_PRIVATE);}/*** 从⽂件中得到密钥** @param file* @param keyType*/private void getKey(File file, String keyType) {FileInputStream fis = null;try {fis = new FileInputStream(file);ObjectInputStream ois = new ObjectInputStream(fis);byte[] keybyte = (byte[]) ois.readObject();// 关闭资源ois.close();// 默认编码KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);if (KEY_TYPE_PUBLIC.equals(keyType)) {X509EncodedKeySpec x509eks = new X509EncodedKeySpec(keybyte);publicKey = (RSAPublicKey) keyFactory.generatePublic(x509eks);System.out.println(publicKey.getAlgorithm());} else {PKCS8EncodedKeySpec pkcs8eks = new PKCS8EncodedKeySpec(keybyte);privateKey = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8eks);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (InvalidKeySpecException e) {e.printStackTrace();} finally {try {fis.close();} catch (IOException e) {e.printStackTrace();}}}} 代码中涉及到的Base64Util如下:public class Base64Util{private static final char S_BASE64CHAR[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b','c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p','q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3','4', '5', '6', '7', '8', '9', '+', '/' };private static final byte S_DECODETABLE[];static{S_DECODETABLE = new byte[128];for (int i = 0; i < S_DECODETABLE.length; i++)S_DECODETABLE[i] = 127;for (int i = 0; i < S_BASE64CHAR.length; i++)S_DECODETABLE[S_BASE64CHAR[i]] = (byte) i;}/**** @param ibuf* @param obuf* @param wp* @return*/private static int decode0(char ibuf[], byte obuf[], int wp){int outlen = 3;if (ibuf[3] == '=')outlen = 2;if (ibuf[2] == '=')outlen = 1;int b0 = S_DECODETABLE[ibuf[0]];int b1 = S_DECODETABLE[ibuf[1]];int b2 = S_DECODETABLE[ibuf[2]];int b3 = S_DECODETABLE[ibuf[3]];switch (outlen){case 1: // '\001'obuf[wp] = (byte) (b0 << 2 & 252 | b1 >> 4 & 3);return 1;case 2: // '\002'obuf[wp++] = (byte) (b0 << 2 & 252 | b1 >> 4 & 3);obuf[wp] = (byte) (b1 << 4 & 240 | b2 >> 2 & 15);return 2;case 3: // '\003'obuf[wp++] = (byte) (b0 << 2 & 252 | b1 >> 4 & 3);obuf[wp++] = (byte) (b1 << 4 & 240 | b2 >> 2 & 15);obuf[wp] = (byte) (b2 << 6 & 192 | b3 & 63);return 3;}throw new RuntimeException("Internal error");}/**** @param data* @param off* @param len* @return*/public static byte[] decode(char data[], int off, int len){char ibuf[] = new char[4];int ibufcount = 0;byte obuf[] = new byte[(len / 4) * 3 + 3];int obufcount = 0;for (int i = off; i < off + len; i++){char ch = data[i];if (ch != '=' && (ch >= S_DECODETABLE.length || S_DECODETABLE[ch] == 127)) continue;ibuf[ibufcount++] = ch;if (ibufcount == ibuf.length){ibufcount = 0;obufcount += decode0(ibuf, obuf, obufcount);}}if (obufcount == obuf.length){return obuf;}else{byte ret[] = new byte[obufcount];System.arraycopy(obuf, 0, ret, 0, obufcount);return ret;}}/**** @param data* @return*/public static byte[] decode(String data){char ibuf[] = new char[4];int ibufcount = 0;byte obuf[] = new byte[(data.length() / 4) * 3 + 3];int obufcount = 0;for (int i = 0; i < data.length(); i++){char ch = data.charAt(i);if (ch != '=' && (ch >= S_DECODETABLE.length || S_DECODETABLE[ch] == 127))continue;ibuf[ibufcount++] = ch;if (ibufcount == ibuf.length){ibufcount = 0;obufcount += decode0(ibuf, obuf, obufcount);}}if (obufcount == obuf.length){return obuf;}else{byte ret[] = new byte[obufcount];System.arraycopy(obuf, 0, ret, 0, obufcount);return ret;}}/**** @param data* @param off* @param len* @param ostream* @throws IOException*/public static void decode(char data[], int off, int len, OutputStream ostream) throws IOException {char ibuf[] = new char[4];int ibufcount = 0;byte obuf[] = new byte[3];for (int i = off; i < off + len; i++){char ch = data[i];if (ch != '=' && (ch >= S_DECODETABLE.length || S_DECODETABLE[ch] == 127))continue;ibuf[ibufcount++] = ch;if (ibufcount == ibuf.length){ibufcount = 0;int obufcount = decode0(ibuf, obuf, 0);ostream.write(obuf, 0, obufcount);}}}/**** @param data* @param ostream* @throws IOException*/public static void decode(String data, OutputStream ostream) throws IOException{char ibuf[] = new char[4];int ibufcount = 0;byte obuf[] = new byte[3];for (int i = 0; i < data.length(); i++){char ch = data.charAt(i);if (ch != '=' && (ch >= S_DECODETABLE.length || S_DECODETABLE[ch] == 127))continue;ibuf[ibufcount++] = ch;if (ibufcount == ibuf.length){ibufcount = 0;int obufcount = decode0(ibuf, obuf, 0);ostream.write(obuf, 0, obufcount);}}}/**** @param data* @return*/public static String encode(byte data[]){return encode(data, 0, data.length);}/**** @param data* @param off* @param len* @return*/public static String encode(byte data[], int off, int len){if (len <= 0)return "";char out[] = new char[(len / 3) * 4 + 4];int rindex = off;int windex = 0;int rest;for (rest = len - off; rest >= 3; rest -= 3){int i = ((data[rindex] & 255) << 16) + ((data[rindex + 1] & 255) << 8) + (data[rindex + 2] & 255); out[windex++] = S_BASE64CHAR[i >> 18];out[windex++] = S_BASE64CHAR[i >> 12 & 63];out[windex++] = S_BASE64CHAR[i >> 6 & 63];out[windex++] = S_BASE64CHAR[i & 63];rindex += 3;}if (rest == 1){int i = data[rindex] & 255;out[windex++] = S_BASE64CHAR[i >> 2];out[windex++] = S_BASE64CHAR[i << 4 & 63];out[windex++] = '=';out[windex++] = '=';}else if (rest == 2){int i = ((data[rindex] & 255) << 8) + (data[rindex + 1] & 255);out[windex++] = S_BASE64CHAR[i >> 10];out[windex++] = S_BASE64CHAR[i >> 4 & 63];out[windex++] = S_BASE64CHAR[i << 2 & 63];out[windex++] = '=';}return new String(out, 0, windex);}/**** @param data* @param off* @param len* @param ostream* @throws IOException*/public static void encode(byte data[], int off, int len, OutputStream ostream) throws IOException{if (len <= 0)return;byte out[] = new byte[4];int rindex = off;int rest;for (rest = len - off; rest >= 3; rest -= 3){int i = ((data[rindex] & 255) << 16) + ((data[rindex + 1] & 255) << 8) + (data[rindex + 2] & 255); out[0] = (byte) S_BASE64CHAR[i >> 18];out[1] = (byte) S_BASE64CHAR[i >> 12 & 63];out[2] = (byte) S_BASE64CHAR[i >> 6 & 63];out[3] = (byte) S_BASE64CHAR[i & 63];ostream.write(out, 0, 4);rindex += 3;}if (rest == 1){int i = data[rindex] & 255;out[0] = (byte) S_BASE64CHAR[i >> 2];out[1] = (byte) S_BASE64CHAR[i << 4 & 63];out[2] = 61;out[3] = 61;ostream.write(out, 0, 4);}else if (rest == 2){int i = ((data[rindex] & 255) << 8) + (data[rindex + 1] & 255);out[0] = (byte) S_BASE64CHAR[i >> 10];out[1] = (byte) S_BASE64CHAR[i >> 4 & 63];out[2] = (byte) S_BASE64CHAR[i << 2 & 63];out[3] = 61;ostream.write(out, 0, 4);}}/**** @param data* @param off* @param len* @param writer* @throws IOException*/public static void encode(byte data[], int off, int len, Writer writer) throws IOException{if (len <= 0)return;char out[] = new char[4];int rindex = off;int rest = len - off;int output = 0;do{if (rest < 3)break;int i = ((data[rindex] & 255) << 16) + ((data[rindex + 1] & 255) << 8) + (data[rindex + 2] & 255); out[0] = S_BASE64CHAR[i >> 18];out[1] = S_BASE64CHAR[i >> 12 & 63];out[2] = S_BASE64CHAR[i >> 6 & 63];out[3] = S_BASE64CHAR[i & 63];writer.write(out, 0, 4);rindex += 3;rest -= 3;if ((output += 4) % 76 == 0)writer.write("\n");}while (true);if (rest == 1){int i = data[rindex] & 255;out[0] = S_BASE64CHAR[i >> 2];out[1] = S_BASE64CHAR[i << 4 & 63];out[2] = '=';out[3] = '=';writer.write(out, 0, 4);}else if (rest == 2){int i = ((data[rindex] & 255) << 8) + (data[rindex + 1] & 255);out[0] = S_BASE64CHAR[i >> 10];out[1] = S_BASE64CHAR[i >> 4 & 63];out[2] = S_BASE64CHAR[i << 2 & 63];out[3] = '=';writer.write(out, 0, 4);}}}测试类:public class RSATest {@Testpublic void test() {RSAGenerator rsaGenerator = new RSAGenerator().generateKeyPair();String str="数表的质数⼜称素数。
教你用Java实现RSA非对称加密算法
教你⽤Java实现RSA⾮对称加密算法⽬录⼀、⾮对称加密⼆、RSA算法三、RSA算法Java语⾔实现⼀、⾮对称加密⾮对称加密算法是⼀种密钥的保密⽅法。
⾮对称加密算法需要两个密钥:公开密钥(publickey:简称公钥)和私有密钥(privatekey:简称私钥)。
公钥与私钥是⼀对,如果⽤公钥对数据进⾏加密,只有⽤对应的私钥才能解密。
因为加密和解密使⽤的是两个不同的密钥,所以这种算法叫作⾮对称加密算法。
⾮对称加密算法实现机密信息交换的基本过程是:甲⽅⽣成⼀对密钥并将公钥公开,需要向甲⽅发送信息的其他⾓⾊(⼄⽅)使⽤该密钥(甲⽅的公钥)对机密信息进⾏加密后再发送给甲⽅;甲⽅再⽤⾃⼰私钥对加密后的信息进⾏解密。
甲⽅想要回复⼄⽅时正好相反,使⽤⼄⽅的公钥对数据进⾏加密,同理,⼄⽅使⽤⾃⼰的私钥来进⾏解密。
另⼀⽅⾯,甲⽅可以使⽤⾃⼰的私钥对机密信息进⾏签名后再发送给⼄⽅;⼄⽅再⽤甲⽅的公钥对甲⽅发送回来的数据进⾏验签。
甲⽅只能⽤其私钥解密由其公钥加密后的任何信息。
⾮对称加密算法的保密性⽐较好,它消除了最终⽤户交换密钥的需要。
⾮对称密码体质的特点:算法强度复杂、安全性依赖于算法与密钥但是由于其算法复杂,⽽使得加密解密速度没有对称加密解密的速度快。
对称密码体制中只有⼀种密钥,并且是⾮公开的,如果要解密就得让对⽅知道密钥。
所以保证其安全性就是保证密钥的安全,⽽⾮对称密钥体制有两种密钥,其中⼀个是公开的,这样就可以不需要像对称密码那样传输对⽅的密钥了。
这样安全性就⼤了很多。
⼆、RSA算法简介:RSA公开密钥密码体质是⼀种使⽤不同的加密密钥与解密密钥,“由已知加密密钥推导出解密密钥在计算上是不可⾏的”密码体制。
在公开密钥密码体制中,加密密钥(即公开密钥)PK是公开信息,⽽解密密钥(即秘密密钥)SK是需要保密的。
加密算法E和解密算法D也都是公开的。
虽然解密密钥SK是由公开密钥PK决定的,但却不能根据PK计算出SK 。
RSA加密算法java代码:
1.RSA加密算法java代码:import java.math.BigInteger;public class RSA {private long p,q,e,d,n;public RSA(){int pIndex = (int)(Math.random()*10);int qIndex;int eIndex;do{qIndex = (int)(Math.random()*10);}while(qIndex==pIndex);do{eIndex = (int)(Math.random()*10);}while(eIndex==pIndex||eIndex==pIndex); p = 1033;q = 2017;e = 29437;n = p*q;d = calculateD();}private long calculateD(){long t0 = 0,t1 = 1,t2 = -1;long r0 = (p-1)*(q-1), m = r0,r1 = e ,r2 = -1; do{long q = r0/r1;r2 = r0-r1*q;if(r2==0)break;t2 = t0 - t1*q;while(t2<0){t2+=m;}if(t2>=m){t2 %= m;}r0 = r1;r1 = r2;t0 = t1;t1 = t2;}while(r2!=0);if(r1!=1){return 0;}else{return t2;}}public long getE() {return e;}public long getN() {return n;}public long getD() {return d;}public BigInteger encode(BigInteger data){ return pow(data,d).mod(new BigInteger(n+"")); }public BigInteger decode(BigInteger code){ return pow(code,e).mod(new BigInteger(n+"")); }public BigInteger pow(BigInteger data,long p){ data = data.pow((int)p);return data;}public static void main(String args[]){RSA rsa = new RSA();BigInteger data = new BigInteger("222222");long oldtime = System.currentTimeMillis();BigInteger code = rsa.encode(data);long newtime = System.currentTimeMillis();double codetime = ((double)(newtime-oldtime))/1000; oldtime = System.currentTimeMillis();BigInteger decode = rsa.decode(code);newtime = System.currentTimeMillis();double decodetime = ((double)(newtime-oldtime))/1000; System.out.println("privateKey:"+rsa.d);System.out.println("publickKey:"+rsa.e);System.out.println("N:"+rsa.n);System.out.println("data:"+data);System.out.println("code:"+code+" time:"+codetime); System.out.println("decode:"+decode+" time:"+decodetime);}}2.运行结果截图:。
Java非对称加密RSA工具类v1.1
byte[] newResult = new byte[len];
System.arraycopy(result, 0, newResult, 0, len);
//还原字符串
return new String(newResult);
}
return null;
}
/**将二进制转换成16进制*/
public static String parseByte2HexStr(byte buf[]) {
} catch (Exception e) {
e.printStackTrace();
}
return me;
}
private RSAPublicKey publicKey;
private RSAPrivateCrtKey privateKey;
/**获取公钥*/
public String getPublicKey(){
byte[] keyBytes = parseHexStr2Byte(key);
//先分段
String[] rs = res.split("\\"+split);
//分段解密
if(rs!=null){
int len = 0;
//组合byte[]
byte[] result = new byte[rs.length*max];
private static RSA me;
private RSA(){}//单例
public static RSA create(){
if (me==null) {
me = new RSA();
}
//生成公钥、私钥
try {
java使用RSA与AES加密解密
java使⽤RSA与AES加密解密⾸先了解下,什么是堆成加密,什么是⾮对称加密? 对称加密:加密与解密的密钥是相同的,加解密速度很快,⽐如AES ⾮对称加密:加密与解密的秘钥是不同的,速度较慢,⽐如RSA先看代码(先会⽤在研究) 相关依赖: <dependency><groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk15on</artifactId><version>1.58</version></dependency>1,RSA⼯具类:package cn.wangtao.utils;import org.bouncycastle.jce.provider.BouncyCastleProvider;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import javax.crypto.Cipher;import java.io.ByteArrayOutputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectOutputStream;import java.security.*;import java.security.interfaces.RSAPrivateKey;import java.security.interfaces.RSAPublicKey;/*** @ClassName RSAUtils* @Auth 桃⼦* @Date 2019-6-25 15:15* @Version 1.0* @Description**/public class RSAUtils {private static final String RSA = "RSA"; // 加密⽅式private static final Logger logger= LoggerFactory.getLogger(RSAUtils.class);//获取密钥public static KeyPair getKey() throws Exception {try {KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA, new BouncyCastleProvider()); keyPairGenerator.initialize(2048); // 初始化密钥长度KeyPair keyPair = keyPairGenerator.generateKeyPair();// ⽣成密钥对return keyPair;} catch (Exception e) {logger.error("获取RSA秘钥对异常",e);throw new Exception("获取RSA秘钥对异常",e);}}//利⽤公钥进⾏加密public static String encryptStr(RSAPublicKey publicKey, String str) throws Exception {Cipher cipher = Cipher.getInstance(RSA, new BouncyCastleProvider());cipher.init(Cipher.ENCRYPT_MODE, publicKey);//加密byte[] bytes = getBytes(str.getBytes(), cipher);//2进⾏转换成16进制String result = CommonUtils.parseByte2HexStr(bytes);return result;} catch (Exception e) {logger.error("使⽤RSA公钥进⾏加密异常",e);throw new Exception("使⽤RSA公钥进⾏加密异常",e);}}//利⽤私钥进⾏解密public static String decryptStr(RSAPrivateKey privateKey, String str) throws Exception {try {Cipher cipher = Cipher.getInstance(RSA, new BouncyCastleProvider());cipher.init(Cipher.DECRYPT_MODE, privateKey); // ⽤密钥初始化此Cipher对象//16进制转换成2进制byte[] bytes = CommonUtils.parseHexStr2Byte(str);//解密byte[] bs = getBytes(bytes, cipher);String content=new String(bs,"utf-8");return content;} catch (Exception e) {logger.error("使⽤RSA私钥进⾏解密异常",e);throw new Exception("使⽤RSA私钥进⾏解密异常",e);}}//通过cipher获取字节数组public static byte[] getBytes(byte[] bytes,Cipher cipher) throws Exception {int blockSize = cipher.getBlockSize(); // 返回块的⼤⼩int j = 0;ByteArrayOutputStream baos = new ByteArrayOutputStream();while (bytes.length - j * blockSize > 0) { // 将⼆进制数据分块写⼊ByteArrayOutputStream中 if(bytes.length-j*blockSize>blockSize){baos.write(cipher.doFinal(bytes, j * blockSize, blockSize));}else{baos.write(cipher.doFinal(bytes, j * blockSize,bytes.length-j*blockSize));}j++;}baos.close();byte[] byteArray = baos.toByteArray();return byteArray;}//保存秘钥对到⽂件public void saveRSAKey(String fileName) throws Exception {FileOutputStream fos=null;ObjectOutputStream oos=null;try {KeyPair keyPair = getKey();fos=new FileOutputStream(fileName);oos=new ObjectOutputStream(fos); //对象序列号oos.writeObject(keyPair);} catch (Exception e) {logger.error("RSA秘钥对保存到⽂件异常[{}]",fileName,e);throw new Exception("RSA秘钥对保存到⽂件异常",e);}finally {if(oos!=null){try {oos.close();} catch (IOException e1) {e1.printStackTrace();}if(fos!=null){try {fos.close();} catch (IOException e1) {e1.printStackTrace();}}}}}/*** @ClassName RSAUtils* @Version 1.0* @Description RSA⼯具类**/public class RSAUtils {private static final String RSA = "RSA";public static final String MD5WITHRSA="MD5withRSA";public static final String SHA1WITHRSA="SHA1withRSA";private static Logger logger= LoggerFactory.getLogger(RSAUtils.class);/*** @desc 读取秘钥⽂本内容* @createTime 2019年7⽉2⽇下午5:20:38* @param keyFile 秘钥⽂件* @return 秘钥⽂本内容* @throws Exception*/private static String initKeyByFile(File keyFile) throws Exception {if(keyFile.exists() && keyFile.isFile()) {BufferedReader bufferedReader = null;try {bufferedReader = new BufferedReader(new FileReader(keyFile));StringBuilder stringBuilder = new StringBuilder();String line = null;while ((line = bufferedReader.readLine()) != null) {if (line.length() == 0 || line.charAt(0) == '-') {continue;}stringBuilder.append(line).append(System.getProperty("line.separator")); }return stringBuilder.toString();}catch (Exception e) {logger.error("读取秘钥⽂本内容异常",e);throw new Exception("读取秘钥⽂本内容异常",e);}finally {CommonUtils.closeReaderandWriter(bufferedReader, null);}}return null;}/*** @desc 获取公钥* @author Liuweian* @createTime 2019年7⽉2⽇下午5:19:34* @param pubKeyFileName 公钥⽂件地址* @return PublicKey* @throws Exception*/public static PublicKey getPublicKeyByFile(File pubKeyFile) throws Exception {String keyContent = initKeyByFile(pubKeyFile);byte[] keyByte = Base64.decode(keyContent);KeyFactory kf = KeyFactory.getInstance(RSA);X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyByte);return kf.generatePublic(keySpec);}* @desc 获取私钥* @createTime 2019年7⽉2⽇下午5:19:16* @param priKeyFileName 私钥⽂件地址* @return PrivateKey* @throws Exception*/public static PrivateKey getPrivateKeyByFile(File priKeyFile) throws Exception {String keyContent = initKeyByFile(priKeyFile);byte[] keyByte = Base64.decode(keyContent);KeyFactory kf = KeyFactory.getInstance(RSA);PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyByte);return kf.generatePrivate(keySpec);}/*** @desc 使⽤RSA中的私钥对数据签名* @createTime 2019年7⽉2⽇下午5:24:30* @param privateKey 秘钥对中的私钥* @param data 待加签字节数组* @param signType 加签类型* @return 加签后的签名* @throws Exception*/public static String sign(byte[] data, PrivateKey privateKey, String signType) throws Exception {Signature signature = Signature.getInstance(signType);signature.initSign(privateKey);signature.update(data);byte[] signByte = signature.sign();//Base64加密return new String(Base64.encode(signByte));}/*** @desc 使⽤RSA中的公钥对签名验签* @createTime 2019年7⽉2⽇下午5:24:30* @param data 待验签字节数组* @param sign 签名* @param publicKey 秘钥对中的公钥* @param signType 加签类型* @return 验签是否成功* @throws Exception*/public static boolean verify(byte[] data, byte[] sign, PublicKey publicKey, String signType) {try {Signature signature = Signature.getInstance(signType);signature.initVerify(publicKey);signature.update(data);//Base64解密byte[] keyByte = Base64.decode(sign);return signature.verify(keyByte);} catch (Exception e) {logger.error("验签出现异常", e);return false;}}/*** @desc 使⽤RSA中的私钥对数据签名加签⽅式 MD5withRSA* @createTime 2019年7⽉2⽇下午5:24:30* @param privateKey 秘钥对中的私钥* @param data 待加签字节数组* @return 加签后的签名* @throws Exception*/public static String signMD5withRSA(byte[] data, PrivateKey privateKey) throws Exception {return sign(data, privateKey, MD5WITHRSA);}/*** @desc 使⽤RSA中的公钥对签名验签验签⽅式 MD5withRSA* @createTime 2019年7⽉2⽇下午5:24:30* @param sign 签名* @param publicKey 秘钥对中的公钥* @param signType 加签类型* @return 验签是否成功,失败则异常抛出* @throws Exception*/public static void verifyMD5withRSA(byte[] data, byte[] sign, PublicKey publicKey) throws Exception { if(!verify(data, sign, publicKey, MD5WITHRSA)) {throw new Exception("验签失败");}}/*** @desc 通过cipher获取字节数组分块* @createTime 2019年7⽉2⽇下午5:21:33* @param data 待加密的字节数组* @param cipher* @return* @throws Exception*/public static byte[] getBytes(byte[] data, Cipher cipher) throws Exception {int blockSize = cipher.getBlockSize(); // 返回块的⼤⼩int j = 0;ByteArrayOutputStream baos = new ByteArrayOutputStream();while (data.length - j * blockSize > 0) { // 将⼆进制数据分块写⼊ByteArrayOutputStream中 if(data.length - j * blockSize > blockSize) {baos.write(cipher.doFinal(data, j * blockSize, blockSize));}else{baos.write(cipher.doFinal(data, j * blockSize, data.length - j * blockSize));}j++;}baos.close();byte[] byteArray = baos.toByteArray();return byteArray;}/*** @desc 利⽤公钥进⾏加密* @createTime 2019年7⽉2⽇下午5:24:30* @param key 密钥对的⼀个* @param data 待加密字节数组* @return 密⽂* @throws Exception*/public static String encrypt(Key key, byte[] data) throws Exception {try {Cipher cipher = Cipher.getInstance(RSA, new BouncyCastleProvider());cipher.init(Cipher.ENCRYPT_MODE, key);//加密byte[] bytes = getBytes(data, cipher);//2进⾏转换成16进制String result = CommonUtils.parseByte2HexStr(bytes);return new String(Base64.encode(result.getBytes(CommonUtils.CODE_TYPE)));} catch (Exception e) {logger.error("使⽤RSA公钥进⾏加密异常",e);throw new Exception("使⽤RSA公钥进⾏加密异常",e);}}/*** @desc 利⽤私钥进⾏解密* @createTime 2019年7⽉2⽇下午5:23:10* @param key 密钥对的⼀个* @param data 待解密的字节数组* @return 明⽂* @throws Exception*/public static String decrypt(Key key, byte[] data) throws Exception {try {Cipher cipher = Cipher.getInstance(RSA, new BouncyCastleProvider());cipher.init(Cipher.DECRYPT_MODE, key); // ⽤密钥初始化此Cipher对象//16进制转换成2进制byte[] bytes = CommonUtils.parseHexStr2Byte(Base64.decode(data));//解密byte[] bs = getBytes(bytes, cipher);String content=new String(bs,CommonUtils.CODE_TYPE);return content;} catch (Exception e) {logger.error("使⽤RSA私钥进⾏解密异常",e);throw new Exception("使⽤RSA私钥进⾏解密异常",e);}}} 2,CommonUtils通⽤⼯具类:package cn.wangtao.utils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.IOException;import java.io.Reader;import java.io.Writer;/*** @ClassName CommonUtils* @Auth 桃⼦* @Date 2019-6-27 12:51* @Version 1.0* @Description**/public class CommonUtils {private static final Logger logger= LoggerFactory.getLogger(CommonUtils.class);//编码⽅式public static final String CODE_TYPE = "UTF-8";//字符补全private static final String[] consult = new String[]{"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G"}; //关流public static void closeReaderandWriter(Reader reader, Writer writer){if(writer!=null){try {writer.close();} catch (IOException e) {logger.error("关闭输出流失败",e);}}if(reader!=null){try {reader.close();} catch (IOException e) {logger.error("关闭输出流失败",e);}}}//将16进制转换为⼆进制public static byte[] parseHexStr2Byte(String hexStr) {if (hexStr.length() < 1)return null;byte[] result = new byte[hexStr.length()/2];for (int i = 0;i< hexStr.length()/2; i++) {int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);result[i] = (byte) (high * 16 + low);}return result;}//将⼆进制转换成16进制public static String parseByte2HexStr(byte buf[]) {StringBuffer sb = new StringBuffer();for (int i = 0; i < buf.length; i++) {String hex = Integer.toHexString(buf[i] & 0xFF);if (hex.length() == 1) {hex = '0' + hex;}sb.append(hex.toUpperCase());}return sb.toString();}//补全字符public static String completionCodeFor16Bytes(String str) throws Exception {try{int num = str.getBytes(CODE_TYPE).length;int index = num%16;//进⾏加密内容补全操作, 加密内容应该为 16字节的倍数, 当不⾜16*n字节是进⾏补全, 差⼀位时补全16+1位 //补全字符以 $ 开始,$后⼀位代表$后补全字符位数,之后全部以0进⾏补全;if(index != 0){StringBuffer sbBuffer = new StringBuffer(str);if(16-index == 1){sbBuffer.append("$" + consult[16-1] + addStr(16-1-1));}else{sbBuffer.append("$" + consult[16-index-1] + addStr(16-index-1-1));}str = sbBuffer.toString();}return str;}catch (Exception e){logger.error("使⽤AES加密前补全字符异常",e);throw new Exception("使⽤AES加密前补全字符异常",e);}}//追加字符public static String addStr(int num){StringBuffer sbBuffer = new StringBuffer("");for (int i = 0; i < num; i++) {sbBuffer.append("0");}return sbBuffer.toString();}//还原字符(进⾏字符判断)public static String resumeCodeOf16Bytes(String str) throws Exception{int indexOf = stIndexOf("$");if(indexOf == -1){return str;}String trim = str.substring(indexOf+1,indexOf+2).trim();int num = 0;for (int i = 0; i < consult.length; i++) {if(trim.equals(consult[i])){num = i;}}if(num == 0){return str;}return str.substring(0,indexOf).trim();}}3,AESUtils通⽤⼯具类:package cn.wangtao.utils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import javax.crypto.Cipher;import javax.crypto.spec.SecretKeySpec;import java.io.*;import java.security.interfaces.RSAPrivateKey;import java.util.Map;/*** @ClassName AESUtils* @Auth 桃⼦* @Date 2019-6-27 12:05* @Version 1.0* @Description**/public class AESUtils {private static final Logger logger= LoggerFactory.getLogger(AESUtils.class);//填充类型public static final String AES_TYPE = "AES/ECB/PKCS5Padding";private static final String AES = "AES"; // 加密⽅式public static final String DES_TYPE = "DES/ECB/PKCS5Padding";private static final String DES = "DES"; // 加密⽅式private final String defaultDesKey="11112222";//8位//对字符串加密public static String encryptStr(String content,String aesKey) throws Exception {try {SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(),AES );Cipher cipher = Cipher.getInstance(AES_TYPE);cipher.init(Cipher.ENCRYPT_MODE, key);//字符补全String content16Str = pletionCodeFor16Bytes(content);byte[] encryptedData = cipher.doFinal(content16Str.getBytes(CommonUtils.CODE_TYPE));//2进制转换成16进制String hexStr = CommonUtils.parseByte2HexStr(encryptedData);return hexStr;} catch (Exception e) {logger.error("使⽤AES对字符串加密异常",e);throw new Exception("使⽤AES对字符串加密异常",e);}}//对字符串解密public static String decryptStr(String content,String aesKey) throws Exception {try {//16进制转换成2进制byte[] bytes = CommonUtils.parseHexStr2Byte(content);SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(), AES);Cipher cipher = Cipher.getInstance(AES_TYPE);cipher.init(Cipher.DECRYPT_MODE, key);byte[] decryptedData = cipher.doFinal(bytes);String result=new String(decryptedData, CommonUtils.CODE_TYPE);//还原字符String orgResult = CommonUtils.resumeCodeOf16Bytes(result);return orgResult;} catch (Exception e) {logger.error("使⽤AES对字符串解密异常",e);throw new Exception("使⽤AES对字符串解密异常",e);}}//对⽂件加密public static File encryptFile(File orgFile, File encryptFile, Map<String,Object> context) throws Exception {("使⽤AES对⽂件加密开始,源⽂件地址[{}]加密后⽂件地址[{}]",orgFile.getPath(),encryptFile.getPath()); BufferedReader br=null;BufferedWriter bw=null;try{//获取AESKEY ,如果没有为默认String aesKey = (String) context.get(Dirt.AES_KEY);br=new BufferedReader(new FileReader(orgFile));bw=(BufferedWriter)context.get(Dirt.BUFFEREDWRITER);if(null==bw){bw=new BufferedWriter(new FileWriter(encryptFile));}String len=null;while (null!=(len=br.readLine())){String encrypt= encryptStr(len,aesKey);bw.write(encrypt);bw.newLine();bw.flush();}("使⽤AES对⽂件加密结束,源⽂件地址[{}]加密后⽂件地址[{}]",orgFile.getPath(),encryptFile.getPath());return encryptFile;}catch (Exception e){logger.error("使⽤AES对⽂件加密异常,源⽂件地址[{}]加密后⽂件地址[{}]",orgFile.getPath(),encryptFile.getPath(),e);throw new Exception("使⽤AES对⽂件加密异常",e);}finally {CommonUtils.closeReaderandWriter(br,bw);}}//对⽂本解密,返回解密⽂件后的⽂件public static File decryptFile(File decryptfile, File encryptFile,Map<String,Object> context) throws Exception {("使⽤AES对⽂件解密开始,源加密⽂件地址[{}]解密后⽂件地址[{}]",encryptFile.getPath(),decryptfile.getPath());BufferedReader br=null;BufferedWriter bw=null;try{if(decryptfile.exists()){decryptfile.delete();}//边读边加密边写br=new BufferedReader(new FileReader(encryptFile));bw=new BufferedWriter(new FileWriter(decryptfile));String len=null;String aesKey=null;//判断是否加密RSAPrivateKey privateKey= (RSAPrivateKey) context.get(Dirt.RSAPRIVATEKEY);if(null!=privateKey){StringBuffer sb=new StringBuffer();while ((len=br.readLine())!=null){sb.append(len);if(len.equals("\n")||len.equals("")||len.equals("\r\n")||len.equals("\r")){aesKey=RSAUtils.decryptStr(privateKey,sb.toString());break;}}}if(null==aesKey){aesKey=(String) context.get(Dirt.AES_KEY);}("aesKey[{}]",aesKey);if(aesKey!=null){while ((len=br.readLine())!=null){String decrypt= decryptStr(len,aesKey);bw.write(decrypt);bw.flush();bw.newLine();}}("使⽤AES对⽂件解密结束,源加密⽂件地址[{}]解密后⽂件地址[{}]",encryptFile.getPath(),decryptfile.getPath()); return decryptfile;}catch (Exception e){logger.error("使⽤AES对⽂件解密异常,源加密⽂件地址[{}]解密后⽂件地址[{}]",encryptFile.getPath(),decryptfile.getPath(),e); throw new Exception("使⽤AES对⽂件解密异常",e);}finally {CommonUtils.closeReaderandWriter(br,bw);}}}/*** @ClassName AESUtils* @Version 1.0* @Description AES⼯具类**/public class AESUtils {private static final Logger logger = LoggerFactory.getLogger(AESUtils.class);/** 加密⽅式 */public static final String AES = "AES";public static final String AES_Type = "AES/ECB/PKCS5Padding";/*** @desc 随机⽣成AES加密秘钥* @createTime 2019年7⽉2⽇下午5:36:00* @return 随机的AES的秘钥串 16位* @throws Exception*/public static String getAesKey() {Random random = new Random();String result = "";for(int i = 0; i< 16; i++){String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";// 输出字母还是数字if( "char".equalsIgnoreCase(charOrNum) ) {// 输出是⼤写字母还是⼩写字母// int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;result += (char)(random.nextInt(26) + 65);} else {result += String.valueOf(random.nextInt(10));}}return result;}/*** @desc AES加密操作* @createTime 2019年7⽉2⽇下午5:30:33* @param data 待加密字节数组* @param aesKey 秘钥串* @return 密⽂* @throws Exception*/public static String encrypt(byte[] data, String aesKey) throws Exception {try {SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(CommonUtils.CODE_TYPE), AES); Cipher cipher = Cipher.getInstance(AES);cipher.init(Cipher.ENCRYPT_MODE, key);byte[] encryptedData = cipher.doFinal(data);//2进制转换成16进制并返回密⽂String result = CommonUtils.parseByte2HexStr(encryptedData);return new String(Base64.encode(result.getBytes(CommonUtils.CODE_TYPE)));} catch (Exception e) {logger.error("使⽤AES对字符串加密异常", e);throw new Exception("使⽤AES对字符串加密异常", e);}}/*** @desc AES解密操作* @createTime 2019年7⽉2⽇下午5:31:37* @param data 待解密字节数组* @param aesKey 秘钥串* @return 明⽂* @throws Exception*/public static String decrypt(byte[] data, String aesKey) throws Exception {try {// 16进制转换成2进制byte[] bytes = CommonUtils.parseHexStr2Byte(Base64.decode(data));SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(CommonUtils.CODE_TYPE), AES); Cipher cipher = Cipher.getInstance(AES);cipher.init(Cipher.DECRYPT_MODE, key);//执⾏解密byte[] decryptedData = cipher.doFinal(bytes);//还原字符并返回return new String(decryptedData, CommonUtils.CODE_TYPE);} catch (Exception e) {logger.error("使⽤AES对字符串解密异常", e);throw new Exception("使⽤AES对字符串解密异常", e);}}} 4,Dirt常量package cn.wangtao.utils;import java.security.interfaces.RSAPublicKey;/*** @ClassName Dirt* @Auth 桃⼦* @Date 2019-6-27 14:20* @Version 1.0* @Description**/public class Dirt {public static final String UPLOADFILEURL="uploadFileUrl";public static final String AES_KEY="aesKey";public static final String RSAPUBLICKEY="rsaPublicKey";public static final String RSAPRIVATEKEY="rsaPrivateKey";public final static String RETURNCODE="returnCode";public final static String RETURNMSG="returnMsg";public final static String FILENAME="fileName";public final static String ORGFILENAME="orgFileName";public final static String ENCRYPTFILE="encryptFile";public static final String BUFFEREDWRITER="bufferedWriter"; //是为了在原始⽂件中进⾏补充加密 //返回码public final static String SUCCESSCODE="000000";public final static String FAILEDCODE="999999";//加密⽂件所放的⽬录public final static String BASELOCALDIR="XXX"; //基本⽬录路径public final static String ENCRYPTLOCALDIR="encrypt"; //加密⽂件⽬录}AES的介绍RSA的介绍。
java 非对称算法 pem 案例
Java中使用非对称算法和PEM格式密钥的案例详解一、概述本文档将详细介绍如何在Java中使用非对称算法,以及如何管理和使用PEM格式的密钥。
非对称算法是一种加密算法,它使用一对密钥,即公钥和私钥。
公钥用于加密数据,私钥用于解密数据。
PEM格式是一种常见的密钥存储格式,它可以方便地在不同的系统和应用程序之间传输和存储密钥。
二、非对称算法1. 非对称算法的原理非对称算法基于数学难题,如大数分解和离散对数等。
它的工作原理是使用一对密钥,即公钥和私钥。
公钥用于加密数据,私钥用于解密数据。
这种算法的优点是可以保证数据的安全性,即使公钥被泄露,也无法解密数据,除非获取到私钥。
2. 常见的非对称算法常见的非对称算法有RSA、DSA、ECC等。
其中,RSA算法是目前最常用的非对称算法,它可以用于加密、签名和验证等场景。
三、PEM格式密钥1. PEM格式介绍PEM格式是一种常见的密钥存储格式,它可以方便地在不同的系统和应用程序之间传输和存储密钥。
PEM格式的文件通常以".pem"为扩展名,其内容是以Base64编码的二进制数据。
2. 生成PEM格式密钥可以使用OpenSSL工具生成PEM格式的密钥。
以下是生成RSA密钥的示例命令:openssl genrsa -out private_key.pem 2048openssl rsa -in private_key.pem -pubout -out public_key.pem四、Java中使用非对称算法和PEM格式密钥的案例1. 导入依赖首先,需要在项目中导入BouncyCastle库,以支持PEM格式密钥的解析和使用。
在Maven项目的pom.xml文件中添加以下依赖:<dependency><groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk15on</artifactId><version>1.68</version></dependency>2. 读取PEM格式密钥使用BouncyCastle库提供的PEMParser类,可以方便地读取PEM格式的密钥。
hutool-all 密码加密方法
hutool-all 密码加密方法在之前的文章中,我们了解了如何使用hutool工具包进行密码加密。
本文将详细介绍hutool-all中的其他加密方法,包括对称加密、非对称加密和哈希算法等。
一、对称加密对称加密是一种加密和解密过程使用相同密钥的加密方式。
在hutool-all 中,我们可以使用AES(Advanced Encryption Standard)进行对称加密。
以下是一个简单的示例:```javaimport cn.hutool.core.codec.Aes;public class SymmetricEncryptionExample {public static void main(String[] args) throws Exception { //原始数据String plainText = "Hello, World!";//生成随机密钥byte[] key = Aes.generateKey(128);//加密byte[] encrypted = Aes.encrypt(plainText.getBytes(), key);//解密String decrypted = new String(Aes.decrypt(encrypted, key));System.out.println("原始数据: " + plainText);System.out.println("解密后的数据: " + decrypted);}}```二、非对称加密非对称加密是一种加密和解密过程使用不同密钥的加密方式。
在hutool-all中,我们可以使用RSA(Rivest-Shamir-Adleman)进行非对称加密。
以下是一个简单的示例:```javaimport cn.hutool.core.codec.Rsa;public class AsymmetricEncryptionExample {public static void main(String[] args) throws Exception { //生成RSA密钥对Rsa rsa = Rsa.generateKeyPair();byte[] publicKey = rsa.getPublicKey().getEncoded();byte[] privateKey = rsa.getPrivateKey().getEncoded();//发送公钥和原始数据给接收方String plainText = "Hello, World!";byte[] encrypted = Rsa.encrypt(plainText.getBytes(), publicKey);//接收方使用公钥解密byte[] decrypted = Rsa.decrypt(encrypted, privateKey);System.out.println("解密后的数据: " + new String(decrypted));}}```三、哈希算法哈希算法是一种将任意长度的数据映射到固定长度的数据的加密方式。
js前台和java后台非对称加密交互
js前台和java后台⾮对称加密交互前⼏天有个需求,两个管理平台可以互相⼀键登录,所以需要⽤RSA来进⾏⽤户名和密码的传递。
1.RSA⼯具类1package com.dp.plat.util;23import java.security.Key;4import java.security.KeyFactory;5import java.security.KeyPair;6import java.security.KeyPairGenerator;7import java.security.PrivateKey;8import java.security.PublicKey;9import java.security.interfaces.RSAPrivateKey;10import java.security.interfaces.RSAPublicKey;11import java.security.spec.PKCS8EncodedKeySpec;12import java.security.spec.X509EncodedKeySpec;13import java.util.HashMap;1415import javax.crypto.Cipher;1617import mons.codec.binary.Base64;181920/**21 * RSA⾮对称加密22 *23*/24public class RSAEncryptor25 {26//⾮对称密钥算法27private static final String KEY = "RSA";2829//密钥长度(64的倍数512-65536之间)30private static final Integer KEY_SIZE = 512;3132//公钥33private static final String PUBLIC_KEY = "PIBLIC";3435//私钥36private static final String PRIVATE_KEY = "PRIVATE";3738public static HashMap<String,Object> initKeyMap() throws Exception39 {40//实例化密钥⽣成器41 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY);42//初始化密钥⽣成器43 keyPairGenerator.initialize(KEY_SIZE);44//⽣成密钥对45 KeyPair keyPair = keyPairGenerator.generateKeyPair();46//公钥47 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();48//私钥49 RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();5051//将密钥存储在map中52 HashMap<String,Object> keyMap = new HashMap<String, Object>();53 keyMap.put(PUBLIC_KEY, publicKey);54 keyMap.put(PRIVATE_KEY, privateKey);5556return keyMap;57 }5859/**60 * 私钥加密61 * @param data 待加密数据62 * @param key 密钥63 * @return byte[] 加密数据64 * @throws Exception65*/66public static byte[] encryptByPrivateKey(byte[] data,byte[] key) throws Exception67 {68//私钥材料转换69 PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(key);70//实例化⼯⼚71 KeyFactory keyFactory = KeyFactory.getInstance(KEY);72//⽣成私钥73 PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);74//数据加密75 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());76 cipher.init(Cipher.ENCRYPT_MODE, privateKey);7778return cipher.doFinal(data);79 }8081/**82 * 公钥加密83 * @param data 待加密数据84 * @param key 密钥85 * @return byte[] 加密数据86 * @throws Exception87*/88public static byte[] encryptByPublicKey(byte[] data,byte[] key) throws Exception89 {90//公钥材料转换91 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(key);92 KeyFactory keyFactory = KeyFactory.getInstance(KEY);93//⽣成公钥94 PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);95//数据加密96 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());97 cipher.init(Cipher.ENCRYPT_MODE, publicKey);9899return cipher.doFinal(data);100 }101102/**103 * 私钥解密104 * @param data 待加密数据105 * @param key 密钥106 * @return byte[] 解密数据107 * @throws Exception108*/109public static byte[] decryptByPrivateKey(byte[] data,byte[] key) throws Exception110 {111//私钥材料转换112 PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(key); 113//实例化⼯⼚114 KeyFactory keyFactory = KeyFactory.getInstance(KEY);115//⽣成私钥116 PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);117//数据加密118 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());119 cipher.init(Cipher.DECRYPT_MODE, privateKey);120121return cipher.doFinal(data);122 }123124/**125 * 公钥解密126 * @param data 待加密数据127 * @param key 密钥128 * @return byte[] 解密数据129 * @throws Exception130*/131public static byte[] decryptByPublicKey(byte[] data,byte[] key) throws Exception132 {133//公钥材料转换134 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(key);135 KeyFactory keyFactory = KeyFactory.getInstance(KEY);136//⽣成公钥137 PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);138//数据加密139 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());140 cipher.init(Cipher.DECRYPT_MODE, publicKey);141142return cipher.doFinal(data);143 }144145/**146 * 获取私钥147 * @param keyMap148 * @return149 * @throws Exception150*/151public static byte[] getPrivateKey(HashMap<String, Object> keyMap) throws Exception 152 {153 Key key = (Key) keyMap.get(PRIVATE_KEY);154return key.getEncoded();155 }156public static String getPrivateKeyStr(HashMap<String, Object> keyMap) throws Exception 157 {158 Key key = (Key) keyMap.get(PRIVATE_KEY);159return new String(Base64.encodeBase64(key.getEncoded()));160 }161162/**163 * 获取密钥164 * @param keyMap165 * @return166 * @throws Exception167*/168public static byte[] getPublicKey(HashMap<String, Object> keyMap) throws Exception169 {170 Key key = (Key) keyMap.get(PUBLIC_KEY);171return key.getEncoded();172 }173174public static String getPublicKeyStr(HashMap<String, Object> keyMap) throws Exception175 {176 Key key = (Key) keyMap.get(PUBLIC_KEY);177return new String(Base64.encodeBase64(key.getEncoded()));178 }179 }RSA⼯具类2.获取key的⽅法1 HashMap<String,Object> keyMap = new HashMap<String,Object>();2public void getPrivateKey() throws Exception3 {4 keyMap = RSAEncryptor.initKeyMap();5 String publicKey = RSAEncryptor.getPublicKeyStr(keyMap);6 ServletActionContext.getResponse().setCharacterEncoding("utf-8");7 ServletActionContext.getResponse().getWriter().print("{\"key\":\""+publicKey+"\"}");8 }获取KEY值3.Action接收1 DESEncryptor dese = new DESEncryptor();2 q = q.replaceAll("%2B", "+");3 w = w.replaceAll("%2B", "+");4byte[] privateKey = RSAEncryptor.getPrivateKey(keyMap);5 q = new String(RSAEncryptor.decryptByPrivateKey(Base64.decodeBase64(q.getBytes()), privateKey));6 w = new String(RSAEncryptor.decryptByPrivateKey(Base64.decodeBase64(w.getBytes()), privateKey)); Action接受4.jsp测试页⾯获取key的URL:accessKey.action登录URL:access.action?q=&w=1function login()2 {3 $.ajax({4 url:"accessKey.action",5 dataType:"json",6 type:"POST",7 success:function(data)8 {9//获取publiuc key10var key = data.key;11var encrypt = new JSEncrypt();12 encrypt.setPublicKey(key);13//加密⽤户名和密码14var encryptUser = encrypt.encrypt('test');15var encryptPassword = encrypt.encrypt('12345678');16//转义空格17 encryptUser = encodeURI(encryptUser).replace(/\+/g,"%2B");18 encryptPassword = encodeURI(encryptPassword).replace(/\+/g,"%2B");19//跳转20 top.window.location="access.action?q="+encryptUser+"&w="+encryptPassword;21 }22 })23 }测试JS5.引⼊的js:jsencrypt.min.js6.备注:开始弄这个的时候,主要的问题是js和action的交互上,主要有两个问题:第⼀个是URL传输的时候加号(+)会变成空格( ),导致解析的时候长度出错。
RSA加解密Java
RSA加解密Javaimport cn.hutool.crypto.asymmetric.KeyType;import cn.hutool.crypto.asymmetric.RSA;/*** RAS⾮对称加密*/public class RsaUtil {private static final String publicKey;private static final String privateKey;private static final RSA rsa;private static final String SALT = "123";static {publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC2xhZ9YP2GhO1jxb8a1aPP7i6ZjfjD6kTS++9/HfFb9KhUGt1zr3m5H7WQ" +"/8oNUaJqaDHpjmKQ5hFUpHYVGQWjBlM+P1Ut2Y8EzKu6Kjra1tRC1r3YhoI7erLhRuv+8TZd+yswmn0ZnCskK6bUaFKlzXRaiZGzQKYQdDPJ12hubwIDAQAB";privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALbGFn1g/YaE7WPFvxrVo8/uLpmN+MPqRNL7738d8Vv0qFQa3XOvebkftZD/yg1RompoMemOYpDmEVSkdhUZBaMGUz4/VS3ZjwTMq7oqOtrW1ELWvdiGg rsa = new RSA(privateKey, publicKey);}/*** 公钥加密* @param data 加密前数据* @return返回加密后数据, base64格式*/public static String encrypt(String data) {return rsa.encryptBase64(data + SALT, KeyType.PublicKey);}/*** 私钥解密* @param encryptStr 加密后的字符串* @return*/public static String decrypt(String encryptStr) {return rsa.decryptStr(encryptStr, KeyType.PrivateKey);}public static void main(String[] args) {System.out.println("公钥:" + publicKey);System.out.println("私钥:" + privateKey);String encryptStr = encrypt("test");String decryptStr = decrypt(encryptStr);System.out.println("加密后:" + encryptStr);System.out.println("解密后:" + decryptStr);}}依赖<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId></dependency>。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
CSDN | 社区 | 技术中心 | BLOG首页 | 我的首页 | 我的文章 | 个人档案 | 联系作者 | 聚合 |
| 搜索 | 登录 5篇原创: 0篇翻译: 0篇转载: 2469次点击: 24个评论: 0个Trackbacks
* @throws EncryptException
*/
public static RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[]
privateExponent) throws EncryptException {
} catch (NoSuchAlgorithmException ex) {
throw new EncryptException(ex.getMessage());
}
RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new
int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 :
data.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
publicExponent) throws EncryptException {
KeyFactory keyFac = null;
try {
keyFac = KeyFactory.getInstance("RSA", new
org.bouncycastle.jce.provider.BouncyCastleProvider());
org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, key);
int blockSize =
cipher.getBlockSize();//获得加密块大小,如:加密前数据为128个byte,而key_size=1024 加密块大小为127
throw new EncryptException(ex.getMessage());
}
}
/**
* 加密
* @param key 加密的密钥
* @param data 待加密的明文数据
* @return 加密后的数据
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",
new org.bouncycastle.jce.provider.BouncyCastleProvider());
* @since 2004-5-20
*
*/
public class RSAUtil {
/**
* 生成密钥对
* @return KeyPair
* @throws EncryptException
*/
public static KeyPair generateKeyPair() throws EncryptException {
outputSize);
else
cipher.doFinal(data, i * blockSize, data.length - i *
blockSize, raw, i * outputSize);
//这里面doUpdate方法不可用,查看源代码后发现每次doUpdate后并没有什么实际动作除了把byte[]放到ByteArrayOutputStream中,而最后doFinal的时候才将所有的byte[]进行加密,可是到了此时加密块大小很可能已经超出了OutputSize所以只好用dofinal方法。
int i = 0;
while (data.length - i * blockSize > 0) {
if (data.length - i * blockSize > blockSize)
cipher.doFinal(data, i * blockSize, blockSize, raw, i *
Csdn Blog User的个人信息
作者首页
文章
安全(RSS)
收藏
相册
存档
2004年06月(4)
2004年05月(1)
最近评论
jcl123:RSA算法可不可以用在文件加密上呢???
谢谢``
xuhuan_today@
* 需要到下载bcprov-jdk14-123.jar。
* @author xiaoyusong
* mail: xiaoyusong@
* msn:xiao_yu_song@
BigInteger(modulus), new BigInteger(privateExponent));
try {
return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);
} catch (InvalidKeySpecException ex) {
* @throws EncryptException
*/
public static byte[] encrypt(Key key, byte[] data) throws EncryptException {
try {
Cipher cipher = Cipher.getInstance("RSA", new
KeyFactory keyFac = null;
try {
keyFac = KeyFactory.getInstance("RSA", new
org.bouncycastle.jce.provider.BouncyCastleProvider());
* @param modulus
* @param publicExponent
* @return RSAPublicKey
* @throws EncryptException
*/
public static RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[]
return keyPair;
} catch (Exception e) {
throw new EncryptException(e.getMessage());
}
}
/**
* 生成公钥
316225467
作者tag:安全 CSDN 推荐tag:加密 rsa 源代码 解密
上一篇: java中传值和传址及其引伸深度克隆的思考 | 下一篇: java中传值和传址及其引伸深度克隆的思考
java非对称加密RSA的工具类及其源代码
鉴于rsa加密的重要性和相关源代码的匮乏,经过整理特此贴出。需要到下载bcprov-jdk14-123.jar。
byte,加密后为128个byte;因此共有2个加密块,第一个127 byte第二个为1个byte
int outputSize = cipher.getOutputSize(data.length);//获得加密块加密后块大小
int leavedSize = data.length % blockSize;
BigInteger(modulus), new BigInteger(publicExponent));
try {
return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
} catch (InvalidKeySpecException ex) {
} catch (NoSuchAlgorithmException ex) {
throw new EncryptException(ex.getMessage());
}
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new
final int KEY_SIZE = 1024;//没什么好说的了,这个值关系到块加密的大小,可以更改,但是不要太大,否则效率会低
keyPairGen.initialize(KEY_SIZE, new SecureRandom());
KeyPair keyPair = keyPairGen.genKeyPair();
java非对称加密RSA的工具类及其源代码 - xiaoyusong的专栏 - CSDNBlogսԚ???ĺ?ć뇳...
MzForm
StatusBar
xiaoyusong的专栏
throw new EncryptException(ex.getMessage());
}
}
/**
* 生成私钥
* @param modulus
* @param privateExponent
* @return RSAPrivateKey
import javax.crypto.Cipher;
imrt java.security.spec.RSAPublicKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.InvalidKeySpecException;