· 6 years ago · Jun 27, 2019, 08:46 PM
1package com.ni.apps.cartencryptutil;
2
3import java.io.UnsupportedEncodingException;
4import java.security.InvalidKeyException;
5import java.security.KeyPair;
6import java.security.KeyPairGenerator;
7import java.security.NoSuchAlgorithmException;
8import java.security.PrivateKey;
9import java.security.PublicKey;
10import java.security.SecureRandom;
11
12import javax.crypto.BadPaddingException;
13import javax.crypto.Cipher;
14import javax.crypto.IllegalBlockSizeException;
15import javax.crypto.NoSuchPaddingException;
16import javax.crypto.SecretKey;
17import javax.crypto.spec.IvParameterSpec;
18import javax.xml.bind.DatatypeConverter;
19
20import org.apache.commons.lang3.StringUtils;
21import org.apache.log4j.Logger;
22
23/**
24 * Security class for encrypting and decrypting Strings (that also works in WC ver 7 and above)
25 *
26 * @author
27 *
28 */
29public class SecurityTools {
30 private static final Logger logger = Logger.getLogger(SecurityTools.class);
31
32 private Cipher cipher;
33 private IvParameterSpec initVector;
34 private SecretKey secretKey;
35 PrivateKey privateKeyParam;
36 PublicKey publicKeyParam;
37 private static SecureRandom secureRandom = new SecureRandom();
38
39 private static final String TRANSFORMATION = "RSA/ECB/OAEPWithSHA-1AndMGF1Padding";
40 private static final String ALGORITHM_SHORT = "RSA";
41 private static final String RNG_ALGORITHM = "SHA1PRNG";
42 private static final String ALGORITHM = "PBKDF2WithHmacSHA256";
43 private static final String UTF8 = "UTF-8";
44
45 // exceptions
46 private static final String _ERR_ILLEGAL_BLOCK_SIZE = "illegal block size exception.";
47 private static final String _ERR_BAD_PADDING = "bad padding exception.";
48 private static final String _ERR_INVALIDKEY = "invalidkey exception.";
49 private static final String _ERR_PADDING = "padding exception.";
50 private static final String _ERR_NO_SUCH_ALGORITHM = "no such algorithm exception.";
51 private static final String _ERR_PASSPHRASE_IS_NULL = "passphrase is null.";
52 private static final String _ERR_INVALID_ALGORITHM = "invalid algorithm exception.";
53 private static final String _ERR_UNSUPPORTED_ENCODING = "encoding not supported.";
54 private static final String _ERR_INVALID_KEY_SPEC = "invalid key spec exception.";
55
56 /**
57 * Constructor
58 *
59 * @throws EncryptionException
60 */
61 public SecurityTools() throws EncryptionException {
62 if (logger.isDebugEnabled()) {
63 logger.debug("entering Constructor");
64 }
65 try {
66 cipher = Cipher.getInstance(ALGORITHM_SHORT);
67 generateIV();
68 generateKeys();
69 } catch (NoSuchAlgorithmException iae) {
70 logger.error(_ERR_NO_SUCH_ALGORITHM, iae);
71 throw new EncryptionException(_ERR_NO_SUCH_ALGORITHM, iae);
72 } catch (NoSuchPaddingException nspe) {
73 logger.error(_ERR_PADDING, nspe);
74 throw new EncryptionException(_ERR_PADDING, nspe);
75 }
76 if (logger.isDebugEnabled()) {
77 logger.debug("exiting Constructor");
78 }
79 }
80
81 /**
82 * Encrypts a given plain text String, and returns the encrypted String
83 *
84 * @param plainText
85 * @return
86 * @throws EncryptionException
87 */
88 public String encrypt(String plainText, PublicKey publicKey) throws EncryptionException {
89 if (logger.isDebugEnabled()) {
90 logger.debug("entering encrypt");
91 }
92
93 String encryptedKey = null;
94 try {
95 byte[] byteToEncrypt = plainText.getBytes(UTF8);
96 cipher.init(Cipher.ENCRYPT_MODE, publicKey);
97 byte[] encryptedBytes = cipher.doFinal(byteToEncrypt);
98 encryptedKey = DatatypeConverter.printBase64Binary(encryptedBytes);
99 } catch (IllegalArgumentException iae) {
100 logger.error(_ERR_PASSPHRASE_IS_NULL, iae);
101 throw new EncryptionException(_ERR_PASSPHRASE_IS_NULL, iae);
102 } catch (InvalidKeyException ike) {
103 logger.error(_ERR_INVALIDKEY, ike);
104 throw new EncryptionException(_ERR_INVALIDKEY, ike);
105 } catch (BadPaddingException bpe) {
106 logger.error(_ERR_BAD_PADDING, bpe);
107 throw new EncryptionException(_ERR_BAD_PADDING, bpe);
108 } catch (IllegalBlockSizeException bpe) {
109 logger.error(_ERR_ILLEGAL_BLOCK_SIZE, bpe);
110 throw new EncryptionException(_ERR_ILLEGAL_BLOCK_SIZE, bpe);
111 } catch (UnsupportedEncodingException uee) {
112 logger.error(_ERR_UNSUPPORTED_ENCODING, uee);
113 throw new EncryptionException(_ERR_UNSUPPORTED_ENCODING, uee);
114 } /*-catch (InvalidAlgorithmParameterException iape) {
115 logger.error(_ERR_INVALID_ALGORITHM, iape);
116 throw new EncryptionException(_ERR_INVALID_ALGORITHM, iape);
117 }*/
118
119 if (logger.isDebugEnabled()) {
120 logger.debug("exiting encrypt");
121 }
122
123 return encryptedKey;
124 }
125
126 /**
127 * Decrypts a given encrypted String, and returns the plain text String
128 *
129 * @param cipherTextStr
130 * @return
131 * @throws EncryptionException
132 */
133 public String decrypt(String cipherTextStr, PrivateKey privateKey) throws EncryptionException {
134 if (logger.isDebugEnabled()) {
135 logger.debug("entering decrypt");
136 }
137
138 String cleartext = null;
139 try {
140 cipher.init(Cipher.DECRYPT_MODE, privateKey);
141 byte[] plainByte = cipher.doFinal(DatatypeConverter.parseBase64Binary(cipherTextStr));
142 cleartext = new String(plainByte);
143 } /*-catch (InvalidAlgorithmParameterException iape) {
144 logger.error(_ERR_INVALID_ALGORITHM, iape);
145 throw new EncryptionException(_ERR_INVALID_ALGORITHM, iape);
146 } */catch (IllegalArgumentException iae) {
147 logger.error(_ERR_PASSPHRASE_IS_NULL, iae);
148 throw new EncryptionException(_ERR_PASSPHRASE_IS_NULL, iae);
149 } catch (InvalidKeyException ike) {
150 logger.error(_ERR_INVALIDKEY, ike);
151 throw new EncryptionException(_ERR_INVALIDKEY, ike);
152 } catch (BadPaddingException bpe) {
153 logger.error(_ERR_BAD_PADDING, bpe);
154 throw new EncryptionException(_ERR_BAD_PADDING, bpe);
155 } catch (IllegalBlockSizeException bpe) {
156 logger.error(_ERR_ILLEGAL_BLOCK_SIZE, bpe);
157 throw new EncryptionException(_ERR_ILLEGAL_BLOCK_SIZE, bpe);
158 }
159
160 if (logger.isDebugEnabled()) {
161 logger.debug("exiting decrypt");
162 }
163
164 return cleartext;
165 }
166
167 /**
168 * Creates the IV using Secure Random Number Generator and an empty 16byte array
169 *
170 * @return
171 */
172 private void generateIV() {
173 if (logger.isDebugEnabled()) {
174 logger.debug("entering generateIV");
175 }
176
177 byte[] newSeed = secureRandom.generateSeed(16);
178 secureRandom.setSeed(newSeed);
179 byte[] byteIV = new byte[16];
180 secureRandom.nextBytes(byteIV);
181 initVector = new IvParameterSpec(byteIV);
182
183 if (logger.isDebugEnabled()) {
184 logger.debug("exiting generateIV");
185 }
186 }
187
188 /**
189 * Generates the Key used for decryption and encryption
190 *
191 * @throws EncryptionException
192 */
193 private void generateKeys() throws EncryptionException {
194
195 try {
196 String saltStr = "salty";// rbConfig.getString("salt");
197 String passPhraseStr = "passy";// rbConfig.getString("passphrase");
198 if (StringUtils.isEmpty(saltStr) || StringUtils.isEmpty(passPhraseStr)) {
199 throw new EncryptionException(_ERR_PASSPHRASE_IS_NULL);
200 }
201
202 KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
203 keyGen.initialize(512); // key size specified here.
204 KeyPair pair = keyGen.generateKeyPair();
205 privateKeyParam = pair.getPrivate();
206 publicKeyParam = pair.getPublic();
207
208 /*-byte[] salt = saltStr.getBytes();
209 int iterations = 10000;
210 int keyLength = 128;
211
212 SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
213 SecretKey tmp = factory.generateSecret(new PBEKeySpec(passPhraseStr.toCharArray(), salt, iterations, keyLength));
214 secretKey = new SecretKeySpec(tmp.getEncoded(), ALGORITHM_SHORT);*/
215 } catch (NoSuchAlgorithmException iae) {
216 logger.error(_ERR_NO_SUCH_ALGORITHM, iae);
217 throw new EncryptionException(_ERR_NO_SUCH_ALGORITHM, iae);
218 } /*-catch (InvalidKeySpecException e) {
219 logger.error(_ERR_INVALID_KEY_SPEC, e);
220 throw new EncryptionException(_ERR_INVALID_KEY_SPEC, e);
221 }*/
222
223 }
224
225 /**
226 * Test method
227 *
228 * @param args
229 */
230 public static void main(String[] args) {
231 String[] message = { "mktest", "9248547896548752345", "okok234234234okok467467",
232 "12" };
233 String result = null;
234 try {
235 SecurityTools secTool = new SecurityTools();
236 PrivateKey priv = secTool.getPrivateKeyParam();
237 PublicKey publ = secTool.getPublicKeyParam();
238 String temp = "N5B1zgbvts3Vwrt6qyL/TBzt62HTFz0ISySx5HFu02oVq1YEhFLbrgdCndROX4/5hMpxCHGM8UJBSyZUfjD/DA==";
239 // System.out.println("ASYMMETRIC TEST" + secTool.decrypt(temp, priv));
240
241 for (String mess : message) {
242 result = secTool.encrypt(mess, publ);
243 System.out.println(result);
244 result = secTool.decrypt(result, priv);
245 System.out.println(result);
246 }
247 } catch (Exception e) {
248 System.out.println(e.getMessage());
249 e.printStackTrace();
250
251 }
252 }
253
254 /**
255 * @return the privateKeyParam
256 */
257 public PrivateKey getPrivateKeyParam() {
258 return privateKeyParam;
259 }
260
261 /**
262 * @return the publicKeyParam
263 */
264 public PublicKey getPublicKeyParam() {
265 return publicKeyParam;
266 }
267
268 class EncryptionException extends Exception {
269
270 private static final long serialVersionUID = 1L;
271
272 public EncryptionException() {}
273
274 public EncryptionException(String message, Throwable cause) {
275 super(message, cause);
276 }
277
278 public EncryptionException(String message) {
279 super(message);
280 }
281
282 public EncryptionException(Throwable cause) {
283 super(cause);
284 }
285 }
286}
287
288com.ni.apps.cartencryptutil.SecurityTools$EncryptionException: bad padding exception.
289 at com.ni.apps.cartencryptutil.SecurityTools.decrypt(SecurityTools.java:154)
290 at com.ni.apps.cartencryptutil.SecurityTools.main(SecurityTools.java:239)
291Caused by: javax.crypto.BadPaddingException: Decryption error
292 at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380)
293 at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291)
294 at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:363)
295 at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
296 at javax.crypto.Cipher.doFinal(Cipher.java:2165)
297 at com.ni.apps.cartencryptutil.SecurityTools.decrypt(SecurityTools.java:141)
298 ... 1 more