|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +package org.apache.cloudstack.logsws; |
| 19 | + |
| 20 | +import java.security.GeneralSecurityException; |
| 21 | +import java.util.Base64; |
| 22 | + |
| 23 | +import javax.crypto.Cipher; |
| 24 | +import javax.crypto.spec.SecretKeySpec; |
| 25 | + |
| 26 | +import com.cloud.serializer.GsonHelper; |
| 27 | + |
| 28 | +public class LogsWebSessionTokenCryptoUtil { |
| 29 | + private static final String ALGORITHM = "AES"; |
| 30 | + public static final String TRANSFORMATION = "AES"; |
| 31 | + |
| 32 | + public static String encrypt(LogsWebSessionTokenPayload payload, String key) throws GeneralSecurityException { |
| 33 | + String json = GsonHelper.getGson().toJson(payload); |
| 34 | + SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM); |
| 35 | + Cipher cipher = Cipher.getInstance(TRANSFORMATION); |
| 36 | + cipher.init(Cipher.ENCRYPT_MODE, secretKey); |
| 37 | + byte[] encrypted = cipher.doFinal(json.getBytes()); |
| 38 | + return Base64.getEncoder().encodeToString(encrypted); |
| 39 | + } |
| 40 | + |
| 41 | + public static LogsWebSessionTokenPayload decrypt(String token, String key) throws GeneralSecurityException { |
| 42 | + SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM); |
| 43 | + Cipher cipher = Cipher.getInstance(TRANSFORMATION); |
| 44 | + cipher.init(Cipher.DECRYPT_MODE, secretKey); |
| 45 | + byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(token)); |
| 46 | + String json = new String(decrypted); |
| 47 | + return GsonHelper.getGson().fromJson(json, LogsWebSessionTokenPayload.class); |
| 48 | + } |
| 49 | +} |
0 commit comments