Formatting Code base with ktlint
[ccsdk/cds.git] / ms / blueprintsprocessor / modules / inbounds / health-api-common / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / healthapi / configuration / SecurityEncryptionConfiguration.kt
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 import org.apache.commons.net.util.Base64
20 import org.springframework.stereotype.Component
21 import javax.crypto.Cipher
22 import javax.crypto.spec.IvParameterSpec
23 import javax.crypto.spec.SecretKeySpec
24
25 @Component
26 class SecurityEncryptionConfiguration {
27
28     private val key = "aesEncryptionKey"
29     private val initVector = "encryptionIntVec"
30
31     fun encrypt(value: String): String? {
32         try {
33             val (iv, skeySpec, cipher) = initChiper()
34             cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv)
35             val encrypted = cipher.doFinal(value.toByteArray())
36             return Base64.encodeBase64String(encrypted)
37         } catch (ex: Exception) {
38             ex.printStackTrace()
39         }
40         return String()
41     }
42
43     open fun decrypt(encrypted: String): String? {
44         try {
45             val (iv, skeySpec, cipher) = initChiper()
46             cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv)
47             val original = cipher.doFinal(Base64.decodeBase64(encrypted))
48             return String(original)
49         } catch (ex: Exception) {
50             ex.printStackTrace()
51         }
52         return String()
53     }
54
55     private fun initChiper(): Triple<IvParameterSpec, SecretKeySpec, Cipher> {
56         val iv = IvParameterSpec(initVector.toByteArray(charset("UTF-8")))
57         val secretKeySpec = SecretKeySpec(key.toByteArray(charset("UTF-8")), "AES")
58         val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
59         return Triple(iv, secretKeySpec, cipher)
60     }
61 }