现在写个简单RSA 加解密实例case
首先利用java的密钥生成器来随机生成密钥:
/** * java 自带公钥私钥生成器 * @throws Exception */ private static void generateKeyPair() throws Exception { SecureRandom sr = new SecureRandom(); KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM); /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */ kpg.initialize(KEYSIZE, sr); /** 生成密匙对 */ KeyPair kp = kpg.generateKeyPair(); Key publicKey = kp.getPublic(); Key privateKey = kp.getPrivate(); /** 用对象流将生成的密钥写入文件 */ ObjectOutputStream oos1 = new ObjectOutputStream(new FileOutputStream(PUBLIC_KEY_FILE)); ObjectOutputStream oos2 = new ObjectOutputStream(new FileOutputStream(PRIVATE_KEY_FILE)); oos1.writeObject(publicKey); oos2.writeObject(privateKey); oos1.close(); oos2.close(); }
然后根据上面生成的公钥来进行加密:
/** * 公钥加密 * @param source * @return * @throws Exception */ public static String encrypt(String source) throws Exception { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE)); Key key = (Key)ois.readObject(); ois.close(); /** 得到Cipher对象来实现对源数据的RSA加密 */ Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] b = source.getBytes(); byte[] b1 = cipher.doFinal(b); return new String(Base64.encodeBase64(b1)); }
最后根据私钥来进行解密:
/** * 私钥解密 * @param target * @return * @throws Exception */ public static String decrypt(String target) throws Exception { @SuppressWarnings("resource") ObjectInputStream ois = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE)); Key key = (Key) ois.readObject(); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, key); byte[] bs = Base64.decodeBase64(target); return new String(cipher.doFinal(bs)); }