View Javadoc
1   package cn.home1.oss.lib.common.crypto;
2   
3   import static com.google.common.base.Charsets.UTF_8;
4   import static com.google.common.base.Preconditions.checkArgument;
5   
6   import lombok.Getter;
7   import lombok.SneakyThrows;
8   
9   import java.security.Provider;
10  import java.security.PublicKey;
11  
12  import javax.crypto.Cipher;
13  
14  import cn.home1.oss.lib.common.CodecUtils;
15  
16  /**
17   * Created by zhanghaolun on 16/10/25.
18   */
19  public class RsaEncryptor implements EncodeEncryptor {
20  
21    private final Provider provider;
22    @Getter
23    private final RsaKey key;
24  
25    public RsaEncryptor(final Provider provider, final KeyExpression keyExpression) {
26      this.provider = provider;
27      this.key = new RsaKey(keyExpression);
28    }
29  
30    @Override
31    public String encrypt(final String plaintext) {
32      return encryptAndEncode(this.provider, this.key.getRsaPublicKey(), plaintext);
33    }
34  
35    @Override
36    public String encrypt(final String plainText, final Integer maxAge) {
37      throw new UnsupportedOperationException();
38    }
39  
40    @SneakyThrows
41    public static byte[] encryptBytes(final Provider provider, final PublicKey publicKey, final byte[] binary) {
42      final Cipher cipher = Cipher.getInstance(CryptoConstants.RSA_ECB_PKCS1_PADDING, provider);
43      cipher.init(Cipher.ENCRYPT_MODE, publicKey);
44      return cipher.doFinal(binary);
45    }
46  
47    public static String encryptAndEncode(final Provider provider, final PublicKey publicKey, final String plaintext) {
48      checkArgument(publicKey != null, "publicKey must not null");
49      final String result;
50      if (plaintext == null) {
51        result = null;
52      } else if (plaintext.length() == 0) {
53        result = "";
54      } else {
55        final byte[] encrypted = encryptBytes(provider, publicKey, plaintext.getBytes(UTF_8));
56        result = CodecUtils.encodeBase64(encrypted);
57      }
58      return result;
59    }
60  }