公钥加密

@param content   待加密内容
@param publicKey 公钥
@param charset   字符集，如UTF-8, GBK, GB2312
@return 密文内容
@throws AlipayApiException
191005
public static String rsaEncrypt(String content, String publicKey,
                                    String charset) throws AlipayApiException {
        try {
            PublicKey pubKey = getPublicKeyFromX509(AlipayConstants.SIGN_TYPE_RSA,
                new ByteArrayInputStream(publicKey.getBytes()));
            Cipher cipher = Cipher.getInstance(AlipayConstants.SIGN_TYPE_RSA);
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            byte[] data = StringUtils.isEmpty(charset) ? content.getBytes()
                : content.getBytes(charset);
            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 = Base64.encodeBase64(out.toByteArray());
            out.close();

            return StringUtils.isEmpty(charset) ? new String(encryptedData)
                : new String(encryptedData, charset);
        } catch (Exception e) {
            throw new AlipayApiException("EncryptContent = " + content + ",charset = " + charset,
                e);
        }
    }
776205
public static byte[] addUtf8Marker(byte[] content) {

        if ((content != null)
            && (content.length >= 3)
            && (content[0] == UTF8_MARKER[0])
            && (content[1] == UTF8_MARKER[1])
            && (content[2] == UTF8_MARKER[2])) {
            return content;
        }

        if (content == null) {
            content = new byte[0];
        }

        byte[] ret = new byte[UTF8_MARKER.length + content.length];

        System.arraycopy(UTF8_MARKER, 0, ret, 0, UTF8_MARKER.length);
        System.arraycopy(content, 0, ret, UTF8_MARKER.length, content.length);

        return ret;
    }
583565
public static String addCharset(String charset, String contentType)
    {
        if (null == contentType)
        {
            return "text/plain;charset=" + charset;
        }
        else
        {
            Matcher matcher = CHARSET_PATT.matcher(contentType);
            if (matcher.find())
            {
                // replace what ever content-type with the charset
                return contentType.substring(0, matcher.start(1)) +
                    charset + contentType.substring(matcher.end(1));
            }
            else
            {
                return contentType + ";charset=" + charset;
            }
        }
    }
130364
public static Content content(String somePlainText) {
		Content c = null;
		try {
			c = new Content("text/plain; charset=UTF-8", somePlainText.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) { /* UTF-8 is never unsupported */
		}
		return c;
	}
592961
@Nullable
  public static String safeDecodeAsString (@Nullable final byte [] aEncodedBytes, @Nonnull final Charset aCharset)
  {
    ValueEnforcer.notNull (aCharset, "Charset");

    return aEncodedBytes == null ? null : safeDecodeAsString (aEncodedBytes, 0, aEncodedBytes.length, aCharset);
  }
758073
public byte[] encrypt(String data, String charset, KeyType keyType) {
		return encrypt(StrUtil.bytes(data, charset), keyType);
	}
514725
private static String aesEncrypt(String content, String aesKey, String charset)
                                                                                   throws AlipayApiException {

        try {
            Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG);

            IvParameterSpec iv = new IvParameterSpec(AES_IV);
            cipher.init(Cipher.ENCRYPT_MODE,
                new SecretKeySpec(Base64.decodeBase64(aesKey.getBytes()), AES_ALG), iv);

            byte[] encryptBytes = cipher.doFinal(content.getBytes(charset));
            return new String(Base64.encodeBase64(encryptBytes));
        } catch (Exception e) {
            throw new AlipayApiException("AES加密失败：Aescontent = " + content + "; charset = "
                                         + charset, e);
        }

    }
272204
public static function loadFromString(string $content): PublicKey {
        $handle = openssl_pkey_get_public($content);
        if(!$handle) {
            throw new RuntimeException(OpenSSL::getLastError());
        }
        return new PublicKey($handle);
    }
1251909
public static void decodeTo(String content, MultiMap<String> map, String charset) {
        decodeTo(content, map, charset == null ? null : Charset.forName(charset));
    }
542871
public String encrypt(String text, PublicKey key) throws MangooEncryptionException {
        Objects.requireNonNull(text, Required.PLAIN_TEXT.toString());
        Objects.requireNonNull(text, Required.PUBLIC_KEY.toString());
        
        String encrypt = null;
        try {
            byte[] cipherText = encrypt(text.getBytes(StandardCharsets.UTF_8), key);
            encrypt = encodeBase64(cipherText);
        } catch (MangooEncryptionException e) {
            throw new MangooEncryptionException("Failed to encrypt clear text with public key", e);
        }
        
        return encrypt;
    }
1060510
public static String urlEncode(String content, Charset charset, TestContext context) {
        return new UrlEncodeFunction().execute(Arrays.asList(content, charset.displayName()), context);
    }
557063
public static void decodeTo(String content, MultiMap map, String charset)
    {
        if (charset==null)
            charset=StringUtil.__ISO_8859_1;

        synchronized(map)
        {
            String key = null;
            String value = null;
            int mark=-1;
            boolean encoded=false;
            for (int i=0;i<content.length();i++)
            {
                char c = content.charAt(i);
                switch (c)
                {
                  case '&':
                      value = encoded
                          ?decodeString(content,mark+1,i-mark-1,charset)
                          :content.substring(mark+1,i);
                      
                      mark=i;
                      encoded=false;
                      if (key != null)
                      {
                          map.add(key,value);
                          key = null;
                      }
                      break;
                  case '=':
                      if (key!=null)
                          break;
                      key = encoded
                          ?decodeString(content,mark+1,i-mark-1,charset)
                          :content.substring(mark+1,i);
                      mark=i;
                      encoded=false;
                      break;
                  case '+':
                      encoded=true;
                      break;
                  case '%':
                      encoded=true;
                      break;
                }                
            }
            
            if (key != null)
            {
                value =  encoded
                    ?decodeString(content,mark+1,content.length()-mark-1,charset)
                    :content.substring(mark+1);
                map.add(key,value);
            }
            else if (mark<content.length())
            {
                key = encoded
                    ?decodeString(content,mark+1,content.length()-mark-1,charset)
                    :content.substring(mark+1);
                map.add(key,"");
            }
        }
    }
474063
private <T extends AlipayResponse> ResponseEncryptItem encryptResponse(AlipayRequest<T> request,
                                                                           Map<String, Object> rt,
                                                                           AlipayParser<T> parser) throws AlipayApiException {

        String responseBody = (String) rt.get("rsp");

        String realBody = null;

        // 解密
        if (request.isNeedEncrypt()) {

            // 解密原始串
            realBody = parser.encryptSourceData(request, responseBody, this.format,
                this.encryptType, this.encryptKey, this.charset);
        } else {

            // 解析原内容串
            realBody = (String) rt.get("rsp");
        }

        return new ResponseEncryptItem(responseBody, realBody);

    }
465734
public static byte[] zlib(String content, String charset, int level) {
		return zlib(StrUtil.bytes(content, charset), level);
	}
223396
private static String decodeFormFields(final String content, final Charset charset) {
        if (content == null) {
            return null;
        }

        return urlDecode(content, (charset != null) ? charset : Charsets.UTF_8, true);
    }
1200372
public static String encryptToBase64(String content) {
        byte[] val = content.getBytes(CHARSET);
        return DatatypeConverter.printBase64Binary(val);
    }
946228
public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception {
		try {
			byte[] buffer = base64.decode(privateKeyStr);
			// X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
			PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此算法");
		} catch (InvalidKeySpecException e) {
			throw new Exception("私钥非法");
		} catch (NullPointerException e) {
			throw new Exception("私钥数据为空");
		}
	}