- public static byte[] encryptByPublicKey(byte[] data, String publicKey)
- throws Exception {
- byte[] keyBytes = Base64.decodeBase64(publicKey);
- X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
- KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
- Key publicK = keyFactory.generatePublic(x509KeySpec);
- // 对数据加密
- Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
- cipher.init(Cipher.ENCRYPT_MODE, publicK);
- int inputLen = data.length;
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- int offSet = 0;
- byte[] cache;
- int i = 0;
- // 对数据分段加密
- 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();
- out.close();
- return encryptedData;
- }
- String str = "${pwd}";
- String result ="";
- try {
- result = Base64.encodeBase64String(encryptByPublicKey(str.getBytes(), RSA_PUB_KEY));
- System.out.println(result);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- print(result);
- vars.put("npsw",result);
- return result;
来源: http://www.bubuko.com/infodetail-2991810.html