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.Key;
10 import java.security.Provider;
11
12 import javax.crypto.Cipher;
13
14 import cn.home1.oss.lib.common.CodecUtils;
15
16
17
18
19 public class RsaDecryptor implements EncodeDecryptor {
20
21 private final Provider provider;
22 @Getter
23 private final RsaKey key;
24
25 public RsaDecryptor(final Provider provider, final KeyExpression keyExpression) {
26 this.provider = provider;
27 this.key = new RsaKey(keyExpression);
28 }
29
30 @Override
31 public String decrypt(final String ciphertext) {
32 return decodeAndDecrypt(this.provider, this.key.getRsaPrivateKey(), ciphertext);
33 }
34
35 @SneakyThrows
36 public static byte[] decryptBytes(final Provider provider, final Key key, final byte[] binary) {
37 final Cipher cipher = Cipher.getInstance(CryptoConstants.RSA_ECB_PKCS1_PADDING, provider);
38 cipher.init(Cipher.DECRYPT_MODE, key);
39 return cipher.doFinal(binary);
40 }
41
42 @SneakyThrows
43 public static String decodeAndDecrypt(final Provider provider, final Key key, final String ciphertext) {
44 checkArgument(key != null, "key must not null");
45
46 final String result;
47 if (ciphertext == null) {
48 result = null;
49 } else if (ciphertext.length() == 0) {
50 result = "";
51 } else {
52 final byte[] binary = CodecUtils.decodeBase64(ciphertext);
53 final byte[] decrypted = decryptBytes(provider, key, binary);
54 result = new String(decrypted, UTF_8);
55 }
56 return result;
57 }
58 }