RSA加密失败问题 java.security.InvalidK

2019-09-26  本文已影响0人  EnumaElish666

原因: base64编码公钥问题


/**

* RSA最大加密明文大小

*/

private static final int MAX_ENCRYPT_BLOCK =117;

/**

* RSA公钥加密, 实现分段加密

* @param str

*            加密字符串

* @param publicKey

*            公钥

* @return 密文

* @throws Exception

*            加密过程中的异常信息

*/

public static String encrypt( String str, String publicKey ) throws Exception{

//base64编码的公钥

// byte[] decoded = Base64.decodeBase64(publicKey); 错误使用方式

byte[] decoded = (new BASE64Decoder()).decodeBuffer(publicKey); // 正确方式

RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));

//RSA加密

Cipher cipher = Cipher.getInstance("RSA");

cipher.init(Cipher.ENCRYPT_MODE, pubKey);

    byte[] data = str.getBytes();

    int inputLen = data.length;

    ByteArrayOutputStream out =new ByteArrayOutputStream();

    int offSet =0;

    byte[] cache;

    int i =0;

    try {

// 对数据分段加密

        while (inputLen - offSet >0) {

if (inputLen - offSet >MAX_ENCRYPT_BLOCK) {

cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);

            }else {

cache = cipher.doFinal(data, offSet, inputLen - offSet);

            }

out.write(cache, 0, cache.length);

            i++;

            offSet = i *MAX_ENCRYPT_BLOCK;

        }

byte[] encryptedData = out.toByteArray();

        return Base64.encodeBase64String(encryptedData);

    }finally {

if (out!=null) {

out.close();

        }

}


上一篇下一篇

猜你喜欢

热点阅读