java安全4
package com.ngsn.security;import java.security.Key;import java.security.KeyPair;import java.security.KeyPairGenerator;import javax.crypto.Cipher;/** * 非对称加密(公钥加密,私钥解密) * RSA:为非对称加密的算法 * @author John.Yao * */public class SecretKeyTest3 {public static void main(String[] args) throws Exception{//Cipher 此类为加密和解密提供密码功能Cipher cipher = Cipher.getInstance("RSA");//根据RSA的加密算法生成一个密钥对生成工具KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");//得到密钥对对象(包括一个公钥一个私钥)KeyPair keyPair = kpg.generateKeyPair();//得到公钥Key publicKey = keyPair.getPublic();//得到私钥Key privateKey = keyPair.getPrivate();//初始化//Cipher.ENCRYPT_MODE 为加密模式//publicKey 为加密的密钥cipher.init(Cipher.ENCRYPT_MODE,publicKey);//对byte[] 进行加密,返回一个加密后的byte[]byte[] result = cipher.doFinal("新一代".getBytes("UTF-8"));System.out.println("result----->"+new String(result));//解密//初始化//Cipher.DECRYPT_MODE 为解密模式//privateKey 为解密的密钥cipher.init(Cipher.DECRYPT_MODE, privateKey);//对加密后的byte[]进行解密byte[] b = cipher.doFinal(result);System.out.println("b------>"+new String(b,"UTF-8"));}}