非对称加密RAS

非对称加密主要特点是一次性生成有2把钥匙,公钥加密私钥解密,反过来一样私钥加密公钥解密.

public static final String RSA = "RSA";
public static void main(String[] args) throws Exception{
String input = "非对称加密";
encrypt(input,RSA);
}
private static void encrypt(String input, String rsa) throws Exception {
//生成密匙对
KeyPair pair = KeyPairGenerator.getInstance(rsa).generateKeyPair();
//公钥
PublicKey publicKey = pair.getPublic();
//私钥
PrivateKey privateKey = pair.getPrivate();

Cipher cipher = Cipher.getInstance(rsa);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
//不能处理大数据,会报错
//byte[] doFinal = cipher.doFinal(input.getBytes());
//加密一次性不能超过117
byte[] doFinal = doFinalWrite(cipher,input.getBytes(),117);

//测试下加密结果
System.out.println(new String(doFinal));

cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] bs = doFinalWrite(cipher, doFinal, 128);
//测试下解密结果
System.out.println(new String(bs));
}
/**
* 把字符串分批添加到数组中 
* 需要调用cipher.doFinal(input, inputOffset, inputLen)
* @param cipher
* @param bytes
* @param i
* @return
* @throws Exception
*/
private static byte[] doFinalWrite(Cipher cipher, byte[] bytes, int i) throws Exception {

int offset=0;
byte[] temp;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while(bytes.length-offset>0){
if(bytes.length-offset>=i){
temp = cipher.doFinal(bytes,offset,i);
offset=offset+i;
}else{
temp = cipher.doFinal(bytes, offset,bytes.length-offset);
offset = offset+(bytes.length-offset);
}
bos.write(temp);
}
bos.close();
return bos.toByteArray();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值