com.zhbiaocloud.carbon.crypto.CarbonDataChannel Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of carbon-exchange Show documentation
Show all versions of carbon-exchange Show documentation
智保云数据平台开发 SDK。定义数据模型以及数据交互所支持的加解密方法
/*
* Copyright (c) 2018-2023. Chengdu WeiSiFan Technology Co., Ltd.
* Carbon Integration SDK is licensed under Mulan PSL v2.
*
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
package com.zhbiaocloud.carbon.crypto;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhbiaocloud.carbon.CarbonOption;
import com.zhbiaocloud.carbon.SignatureMissMatchException;
import com.zhbiaocloud.carbon.model.MessageType;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
/**
* 信道加密
*
* @author jun
*/
@RequiredArgsConstructor
public class CarbonDataChannel {
private final ObjectMapper mapper;
private final Crypto crypto;
private final CarbonOption option;
@SneakyThrows
public EncryptedRequest encodeRequest(MessageType type, Object request) {
String payload = mapper.writeValueAsString(request);
EncryptedRequest message = new EncryptedRequest();
message.setType(type);
message.setTenant(option.getTenant());
message.setRequestId(UUID.randomUUID());
message.setSign(crypto.digest(payload));
message.setPayload(crypto.encrypt(payload));
return message;
}
@SneakyThrows
public EncryptedResponse encodeResponse(UUID requestId, Object response) {
String payload = mapper.writeValueAsString(response);
EncryptedResponse message = new EncryptedResponse();
message.setRequestId(requestId);
message.setTenant(option.getTenant());
message.setSign(crypto.digest(payload));
message.setPayload(crypto.encrypt(payload));
return message;
}
private void verify(String payload, String actualSign) {
String expectedSign = crypto.digest(payload);
if (!expectedSign.equals(actualSign)) {
throw new SignatureMissMatchException(expectedSign, actualSign);
}
}
@SneakyThrows
public T decodeRequest(EncryptedRequest request, Class clz) {
String payload = crypto.decrypt(request.getPayload());
verify(payload, request.getSign());
return mapper.readValue(payload, clz);
}
@SneakyThrows
public T decodeResponse(EncryptedResponse response, Class clz) {
String payload = crypto.decrypt(response.getPayload());
verify(payload, response.getSign());
return mapper.readValue(payload, clz);
}
}