94021207adde3003a9759d8608b6a261833ec703
[ccsdk/cds.git] /
1 /*
2  * Copyright © 2019-2020 Orange.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.configuration
18
19
20 import org.apache.commons.net.util.Base64
21 import org.springframework.stereotype.Component
22 import org.springframework.stereotype.Service
23 import javax.crypto.Cipher
24 import javax.crypto.spec.IvParameterSpec
25 import javax.crypto.spec.SecretKeySpec
26
27
28 @Component
29 class SecurityEncryptionConfiguration {
30     private val key = "aesEncryptionKey"
31     private val initVector = "encryptionIntVec"
32
33     fun encrypt(value: String): String? {
34         try {
35             val (iv, skeySpec, cipher) = initChiper()
36             cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv)
37             val encrypted = cipher.doFinal(value.toByteArray())
38             return Base64.encodeBase64String(encrypted)
39         } catch (ex: Exception) {
40             ex.printStackTrace()
41         }
42         return String()
43     }
44
45     open fun decrypt(encrypted: String): String? {
46         try {
47             val (iv, skeySpec, cipher) = initChiper()
48             cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv)
49             val original = cipher.doFinal(Base64.decodeBase64(encrypted))
50             return String(original)
51         } catch (ex: Exception) {
52             ex.printStackTrace()
53         }
54         return String()
55     }
56
57     private fun initChiper(): Triple<IvParameterSpec, SecretKeySpec, Cipher> {
58         val iv = IvParameterSpec(initVector.toByteArray(charset("UTF-8")))
59         val secretKeySpec = SecretKeySpec(key.toByteArray(charset("UTF-8")), "AES")
60         val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
61         return Triple(iv, secretKeySpec, cipher)
62     }
63 }