/**
* 引进的包都是java自带的jar包
* 秘钥相关包
* base64 编解码
* 这里只用到了编码
*/
import java.security.key;
import java.security.keypair;
import java.security.keypairgenerator;
import java.security.interfaces.rsaprivatekey;
import java.security.interfaces.rsapublickey;
import java.util.hashmap;
import java.util.map;
import sun.misc.base64decoder;
import sun.misc.base64encoder;
public class createsecrtekey {
public class keys {
}
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;
//获得公钥
public static string getpublickey(map keymap) throws exception {
//获得map中的公钥对象 转为key对象
key key = (key) keymap.get(public_key);
//byte[] publickey = key.getencoded();
//编码返回字符串
return encryptbase64(key.getencoded());
}
//获得私钥
public static string getprivatekey(map keymap) throws exception {
//获得map中的私钥对象 转为key对象
key key = (key) keymap.get(private_key);
//byte[] privatekey = key.getencoded();
//编码返回字符串
return encryptbase64(key.getencoded());
}
//解码返回byte
public static byte[] decryptbase64(string key) throws exception {
return (new base64decoder()).decodebuffer(key);
}
//编码返回字符串
public static string encryptbase64(byte[] key) throws exception {
return (new base64encoder()).encodebuffer(key);
}
//map对象中存放公私钥
public static map initkey() throws exception {
//获得对象 keypairgenerator 参数 rsa 1024个字节
keypairgenerator keypairgen = keypairgenerator.getinstance(key_algorithm);
keypairgen.initialize(1024);
//通过对象 keypairgenerator 获取对象keypair
keypair keypair = keypairgen.generatekeypair();
//通过对象 keypair 获取rsa公私钥对象rsapublickey rsaprivatekey
rsapublickey publickey = (rsapublickey) keypair.getpublic();
rsaprivatekey privatekey = (rsaprivatekey) keypair.getprivate();
//公私钥对象存入map中
map keymap = new hashmap(2);
keymap.put(public_key, publickey);
keymap.put(private_key, privatekey);
return keymap;
}
public static void main(string[] args) {
map keymap;
try {
keymap = initkey();
string publickey = getpublickey(keymap);
system.out.println(publickey);
string privatekey = getprivatekey(keymap);
system.out.println(privatekey);
} catch (exception e) {
e.printstacktrace();
}
}