· 7 years ago · Apr 15, 2018, 06:58 AM
1package com.alexsomai.blog.crypto;
2
3import com.alexsomai.blog.util.SerializationUtil;
4import org.bouncycastle.crypto.Digest;
5import org.bouncycastle.crypto.InvalidCipherTextException;
6import org.bouncycastle.crypto.digests.SHA256Digest;
7import org.bouncycastle.crypto.engines.AESEngine;
8import org.bouncycastle.crypto.modes.CBCBlockCipher;
9import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
10import org.bouncycastle.crypto.params.KeyParameter;
11import org.bouncycastle.util.encoders.Hex;
12import org.springframework.beans.factory.annotation.Value;
13import org.springframework.stereotype.Component;
14
15import java.nio.charset.StandardCharsets;
16
17@Component
18public class CipherServiceImpl implements CipherService {
19
20 @Value("${cipher.service.secret-key}")
21 private String secretKey;
22
23 ...
24
25 private byte[] applyAlgorithm(byte[] inputBytes, boolean forEncryption) {
26 PaddedBufferedBlockCipher paddedBufferedBlockCipher = initPaddedBufferedBlockCipher(forEncryption);
27
28 byte[] outputBytes = new byte[paddedBufferedBlockCipher.getOutputSize(inputBytes.length)];
29 int outputLength = paddedBufferedBlockCipher.processBytes(inputBytes, 0, inputBytes.length, outputBytes, 0);
30
31 try {
32 paddedBufferedBlockCipher.doFinal(outputBytes, outputLength);
33 } catch (InvalidCipherTextException e) {
34 throw new RuntimeException("Exception occurred while encrypting/decrypting the object");
35 }
36
37 return outputBytes;
38 }
39
40 private PaddedBufferedBlockCipher initPaddedBufferedBlockCipher(boolean forEncryption) {
41 PaddedBufferedBlockCipher bufferedBlockCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
42
43 KeyParameter keyParameter = new KeyParameter(secretKey.getBytes(StandardCharsets.UTF_8));
44 bufferedBlockCipher.init(forEncryption, keyParameter);
45
46 return bufferedBlockCipher;
47 }
48}