记一次 实现 license授权


package com.example.demo;


import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableMap;

import javax.crypto.Cipher;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Map;

/**
* @author yangxj
* @date 2020-04-10 14:17
*/
public class RSADemo {
/**
* 生成一对公(私)钥
* @throws Exception
*/
public static void genPairKey() throws Exception {
//实例化Key
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
//获取一对钥匙
KeyPair keyPair = keyPairGenerator.generateKeyPair();
//获得公钥
Key publicKey = keyPair.getPublic();
//获得私钥
Key privateKey = keyPair.getPrivate();

// 公(私)钥写入 文件
FileOutputStream publicFos = new FileOutputStream("/Users/edz/licensedir/public.key");
FileOutputStream privateFos = new FileOutputStream("/Users/edz/licensedir/private.key");

ObjectOutputStream outputStream = new ObjectOutputStream(publicFos);

ObjectOutputStream outputStream2 = new ObjectOutputStream(privateFos);

outputStream.writeObject(publicKey);

outputStream2.writeObject(privateKey);

outputStream2.close();
outputStream.close();
}

/**
* 解析
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");

// 反序列化 获取 公(私)钥
FileInputStream fis1 = new FileInputStream("/Users/edz/licensedir/public.key");
FileInputStream fis2 = new FileInputStream("/Users/edz/licensedir/private.key");

ObjectInputStream objectStream1 = new ObjectInputStream(fis1);
ObjectInputStream objectStream2 = new ObjectInputStream(fis2);

Key publicKey = (Key)objectStream1.readObject();
Key privateKey = (Key)objectStream2.readObject();

objectStream1.close();
objectStream2.close();

// 要加密的内容
Map authInfo = ImmutableMap.of("授权", "某人", "授权有效期至", "2019-12-01");

//用公(私)钥加密
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte [] encodeResult = cipher.doFinal(JSON.toJSONBytes(authInfo));

//用私(公)钥匙解密
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] bytes = cipher.doFinal(encodeResult);

System.out.println(new String(bytes));


}
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM