RSA加密

1 篇文章 0 订阅
0 篇文章 0 订阅

public static final String ALGORITHM = "RSA";

public static final int KEYSIZE = 1024*10;//16384;


public static String public_key_file = "public_key.dat";

public static String private_key_file = "private_key.dat";


public static void generateKeyPair() throws NoSuchAlgorithmException, FileNotFoundException, IOException {

SecureRandom sr = new SecureRandom();


KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM);


kpg.initialize(KEYSIZE, sr);

// 生成密钥对

KeyPair keyPair = kpg.generateKeyPair();

// 得到公钥

Key publicKey = keyPair.getPublic();

// 得到私钥

Key privateKey = keyPair.getPrivate();


ObjectOutputStream oosl1 = new ObjectOutputStream(new FileOutputStream(public_key_file));

ObjectOutputStream oosl2 = new ObjectOutputStream(new FileOutputStream(private_key_file));


oosl1.writeObject(publicKey);

oosl2.writeObject(privateKey);


oosl1.close();

oosl2.close();


}


public static String encrypt(String source) throws Exception {

generateKeyPair();


// 取出公钥

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(public_key_file));

Key key = (Key) ois.readObject();

ois.close();

// 开始对公钥加密

Cipher cipher = Cipher.getInstance(ALGORITHM);

cipher.init(Cipher.ENCRYPT_MODE, key);


byte[] b = source.getBytes();

// 使用base64进行编码 字符和byte转换

byte[] doFinal = cipher.doFinal(b);


return new String(Base64.getEncoder().encode(doFinal));

}


public static String decrypt(String cryptText) throws Exception {

// 读文件

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(private_key_file));

Key key = (Key) ois.readObject();

ois.close();

Cipher cipher = Cipher.getInstance(ALGORITHM);

cipher.init(Cipher.DECRYPT_MODE, key);


// byte[] decode = Base64.getDecoder().decode(cryptText);

// byte[] decode = it.sauronsoftware.base64.Base64.encode(cryptText).getBytes();

BASE64Decoder d = new BASE64Decoder();

byte[] decodeBuffer = d.decodeBuffer(cryptText);


byte[] doFinal = cipher.doFinal(decodeBuffer);


return new String(doFinal);

}


public static void main(String[] args) throws Exception {

String name = "ocean";

String text = encrypt(name);

System.out.println(text);


String target = decrypt(text);

System.out.println(target);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值