RSA加密实践

最近做了一个小应用, 需要将发送的报文采用RSA, BASE64, MD5加密。写下这篇文章, 方便自己以后查看,同时也能与各位Java开发的同行交流。

------------------------------------------------------------------

1. RSA加密

import java.security.spec.RSAPublicKeySpec.RSAPublicKeySpec;

import java.security.KeyFactory;

import java.security.Key;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

String encryptByPK(String data, BigInteger modulus, BigInteger exponent) 
throws Exception {


//创建RSAPublicKeySpec 实例,用于取公钥. 

//最开始我采用X509EncodedKeySpec作为keyFactory.generatePublic(pkSepc)的入参,

//结果报错:DerInputStream.getLength(): lengthTag=25, too big.,无法得到公钥。
RSAPublicKeySpec pkSpec = new RSAPublicKeySpec(modulus, exponent);

// 取公钥
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicKey = keyFactory.generatePublic(pkSpec);


// 加密数据
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);

//采用Base64将数据加密成字符串
return Base64.encodeBase64String(cipher.doFinal(data.getBytes()));
}


Tips : 

String.getBytes() : 将字符串转换成字节数组;


2. BASE64加密;

source code : 


//加密

public static String encodeBase64String(byte[] binaryData) {
        return StringUtils.newStringUtf8(encodeBase64(binaryData, false));
    }

//解密

public static byte[] decodeBase64(String base64String) {
        return new Base64().decode(base64String);
    }


3. MD5加密 : MD5可用于生成数字证书(Signature)

import java.security.MessageDigest;


byte[] encryptMD5(byte[] data) throws Exception{
MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
md5.update(data);

return md5.digest();
}

Tips : 在传输密文时, 如果有中文, 记得在加密前对数据进行编码(具体采用的编码根据应用的需要),

否则server收到中文可能乱码,从而导致数字证书不匹配。




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值