详细流程看代码注释
import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import javax.crypto.Cipher; import org.apache.commons.codec.binary.Base64; public class ResUtils { public static void main(String[] args) throws Exception { /* * 非对称加密说明: * * 一般公钥是公开的,私钥是不公开的 * 使用公钥加密数据,只能用私钥解密数据 * 使用私钥加密数据,只能用公钥解密数据 * */ KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); // KeyPairGenerator对象用于生成非对称加密的公钥和私钥,选用RSA非对称加密算法 keyGen.initialize(2048); // 密钥初始化为2048位 KeyPair keyPair = keyGen.generateKeyPair(); // 生成密钥对 PublicKey publicKey = keyPair.getPublic(); // 得到公钥对象 PrivateKey privateKey = keyPair.getPrivate(); // 得到私钥对象 String pubKey = Base64.encodeBase64String(publicKey.getEncoded()); // 编码后得到公钥字符串 String priKey = Base64.encodeBase64String(privateKey.getEncoded()); // 编码后得到私钥字符串 System.out.println(pubKey); System.out.println(priKey); // 根据公钥字符串还原成公钥对象 byte[] pubKeyb = Base64.decodeBase64(pubKey); // 编码公钥字符串 X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKeyb); // 根据编码后的公钥字符串创建公钥材料? KeyFactory keyFactory = KeyFactory.getInstance("RSA"); // 密钥工厂使用RSA算法 PublicKey pubKeyr = keyFactory.generatePublic(x509KeySpec); // 密钥工厂使用公钥材料生成公钥对象 // 根据私钥字符串还原成私钥对象 byte[] priKeyb = Base64.decodeBase64(priKey); // 编码私钥字符串 PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKeyb); // 根据编码后的私钥字符串创建私钥材料? PrivateKey priKeyr = keyFactory.generatePrivate(pkcs8KeySpec); // 密钥工厂使用私钥材料生成私钥对象 // 加密数据(使用公钥对象加密) String data = "数据数据数据"; // 待加密的数据 Cipher cipher = Cipher.getInstance("RSA"); // Cipher对象用于加密或解密数据,选用RSA算法加密或解密 cipher.init(Cipher.ENCRYPT_MODE, pubKeyr); // Cipher对象选用ENCRYPT_MODE加密模式,并使用公钥对象加密 byte[] encdata = cipher.doFinal(data.getBytes("UTF8")); // Cipher对象生成加密数据 String encdatas = Base64.encodeBase64String(encdata); // 编码得到加密数据的字符串 System.out.println(encdatas); // 解密数据(使用私钥对象解密) cipher.init(Cipher.PRIVATE_KEY, priKeyr); // Cipher对象选用PRIVATE_KEY解密模式,并使用私钥对象解密 byte[] decdata = cipher.doFinal(Base64.decodeBase64(encdatas)); // 解码加密数据并解密数据 String decdatas = new String(decdata, "UTF8"); // 得到解密后数据的字符串 System.out.println(decdatas); } }
(完)