更新时间:2025-08-12 gmt 08:00
构建程序-j9九游会登录
本例提供了为文件加/解密的程序包,使用空白模板创建函数,用户可以使用示例代码学习使用。
创建程序包
本例使用java8语言实现加/解密的功能,有关函数开发的过程请参考java函数开发。本例不再介绍业务功能实现的代码,样例代码目录如图1所示。
图1 样例代码目录
其中fileencryptanddecrypt为函数执行的入口类,fileencryptanddecrypt类中入口函数的代码如下:
package com.huawei.kms;
import com.huawei.services.runtime.context;
import com.huawei.services.runtime.entity.s3obs.s3obstriggerevent;
import com.huaweicloud.sdk.core.auth.basiccredentials;
import com.huaweicloud.sdk.kms.v1.kmsclient;
import com.huaweicloud.sdk.kms.v1.model.*;
import com.obs.services.obsclient;
import com.obs.services.exception.obsexception;
import com.obs.services.model.obsobject;
import javax.crypto.cipher;
import javax.crypto.spec.gcmparameterspec;
import javax.crypto.spec.secretkeyspec;
import java.io.*;
import java.nio.file.files;
import java.security.securerandom;
public class fileencryptanddecrypt {
private string objectkey;
private string inputpath;
private string outputpath;
public string encrypt(s3obstriggerevent event, context context){
objectkey = event.getobjectkey();
inputpath = "/tmp/" objectkey;
outputpath = "/tmp/" objectkey ".encrypt";
// 初始化obs类
obsclienthandler client = new obsclienthandler();
client.init(context);
client.setobjectinfo(objectkey, inputpath, outputpath);
// 下载obs桶里面的文件
client.downloadfile();
// 初始化kms类
kmsclienthandler kms = new kmsclienthandler();
kms.init(context);
kms.setpath(inputpath, outputpath);
// 加密文件
kms.encryptfile();
// 上传
client.uploadfile();
return "ok";
}
public string decrypt(s3obstriggerevent event, context context){
objectkey = event.getobjectkey();
inputpath = "/tmp/" objectkey;
outputpath = "/tmp/" objectkey ".decrypt";
// 初始化obs类
obsclienthandler client = new obsclienthandler();
client.init(context);
client.setobjectinfo(objectkey, inputpath, outputpath);
// 下载obs桶里面的文件
client.downloadfile();
// 初始化kms类
kmsclienthandler kms = new kmsclienthandler();
kms.init(context);
kms.setpath(inputpath, outputpath);
// 加密文件
kms.decryptfile();
// 上传
client.uploadfile();
return "ok";
}
static class kmsclienthandler {
// dew服务接口版本信息,当前固定为v1.0
private static final string kms_interface_version = "v1.0";
private static final string aes_key_bit_length = "256";
private static final string aes_key_byte_length = "32";
private static final string aes_alg = "aes/gcm/pkcs5padding";
private static final string aes_flag = "aes";
private static final int gcm_tag_length = 16;
private static final int gcm_iv_length = 12;
private string access_key;
private string secret_access_key;
private string security_token;
private string project_id;
private string kms_endpoint;
private string keyid;
private string ciphertext;
private string inputpath;
private string outputpath;
private context context;
private kmsclient kmsclient = null;
void init(context context) {
this.context = context;
}
void initkmsclient() {
if (kmsclient == null) {
access_key = context.getsecurityaccesskey();
secret_access_key = context.securitygetsecretkey();
security_token = context.getsecuritytoken();
project_id = context.getprojectid();
kms_endpoint = context.getuserdata("kms_endpoint");
keyid = context.getuserdata("kms_key_id");
ciphertext = context.getuserdata("cipher_text");
final basiccredentials auth = new basiccredentials().withak(access_key).withsk(secret_access_key).withsecuritytoken(security_token).withprojectid(project_id);
kmsclient = kmsclient.newbuilder().withcredential(auth).withendpoint(kms_endpoint).build();
}
}
byte[] getencryptplainkey() {
final createdatakeyrequest createdatakeyrequest = new createdatakeyrequest().withversionid(kms_interface_version)
.withbody(new createdatakeyrequestbody().withkeyid(keyid).withdatakeylength(aes_key_bit_length));
final createdatakeyresponse createdatakeyresponse = kmsclient.createdatakey(createdatakeyrequest);
final string ciphertext = createdatakeyresponse.getciphertext();
return hextobytes(createdatakeyresponse.getplaintext());
}
byte[] hextobytes(string hexstring) {
final int stringlength = hexstring.length();
assert stringlength > 0;
final byte[] result = new byte[stringlength / 2];
int j = 0;
for (int i = 0; i < stringlength; i = 2) {
result[j ] = (byte) integer.parseint(hexstring.substring(i, i 2), 16);
}
return result;
}
public void setpath(string inputpath, string outputpath) {
this.inputpath = inputpath;
this.outputpath = outputpath;
}
public void encryptfile() {
final file outencryptfile = new file(outputpath);
final file infile = new file(inputpath);
final byte[] iv = new byte[gcm_iv_length];
final securerandom securerandom = new securerandom();
securerandom.nextbytes(iv);
dofilefinal(cipher.encrypt_mode, infile, outencryptfile, getencryptplainkey(), iv);
}
byte[] getdecryptplainkey() {
final createdatakeyrequest createdatakeyrequest = new createdatakeyrequest().withversionid(kms_interface_version)
.withbody(new createdatakeyrequestbody().withkeyid(keyid).withdatakeylength(aes_key_bit_length));
// 创建数据密钥
final createdatakeyresponse createdatakeyresponse = kmsclient.createdatakey(createdatakeyrequest);
final decryptdatakeyrequest decryptdatakeyrequest = new decryptdatakeyrequest().withversionid(kms_interface_version)
.withbody(new decryptdatakeyrequestbody().withkeyid(keyid).withciphertext(createdatakeyresponse.getciphertext()
).withdatakeycipherlength(aes_key_byte_length));
return hextobytes(kmsclient.decryptdatakey(decryptdatakeyrequest).getdatakey());
}
public void decryptfile() {
final file outencryptfile = new file(outputpath);
final file infile = new file(inputpath);
final byte[] iv = new byte[gcm_iv_length];
final securerandom securerandom = new securerandom();
securerandom.nextbytes(iv);
dofilefinal(cipher.decrypt_mode, infile, outencryptfile, getdecryptplainkey(), iv);
}
/** // * 对文件进行加解密 // * // * @param ciphermode 加密模式,可选值为cipher.encrypt_mode或者cipher.decrypt_mode // * @param infile 加解密前的文件 // * @param outfile 加解密后的文件 // * @param keyplain 明文密钥 // * @param iv 初始化向量 // */ void dofilefinal(int ciphermode, file infile, file outfile, byte[] keyplain, byte[] iv) {
try (bufferedinputstream bis = new bufferedinputstream(files.newinputstream(infile.topath()));
bufferedoutputstream bos = new bufferedoutputstream(files.newoutputstream(outfile.topath()))) {
final byte[] bytin = new byte[(int) infile.length()];
final int filelength = bis.read(bytin);
assert filelength > 0;
final secretkeyspec secretkeyspec = new secretkeyspec(keyplain, aes_flag);
final cipher cipher = cipher.getinstance(aes_alg);
final gcmparameterspec gcmparameterspec = new gcmparameterspec(gcm_tag_length * byte.size, iv);
cipher.init(ciphermode, secretkeyspec, gcmparameterspec);
final byte[] bytout = cipher.dofinal(bytin);
bos.write(bytout);
} catch (exception e) {
throw new runtimeexception(e.getmessage());
}
}
}
static class obsclienthandler {
private obsclient obsclient = null;
private string inputbucketname;
private string outputbucketname;
private string objectkey;
private context context;
private string localinpath;
private string localoutpath;
public void init(context context) {
this.context = context;
}
void initobsclient() {
if (obsclient == null) {
inputbucketname = context.getuserdata("input_bucket");
outputbucketname = context.getuserdata("output_bucket");
string security_access_key = context.getsecurityaccesskey();
string security_secret_key = context.getsecuritysecretkey();
string security_token = context.getsecuritytoken();
string obs_endpoint = context.getuserdata("obs_endpoint");
obsclient = new obsclient(security_access_key, security_secret_key, security_token, obs_endpoint);
}
}
public void setobjectinfo(string objectkey, string inpath, string outpath) {
this.objectkey = objectkey;
localinpath = inpath;
localoutpath = outpath;
}
public void downloadfile() {
initobsclient();
try {
obsobject obsobject = obsclient.getobject(inputbucketname, objectkey);
inputstream inputstream = obsobject.getobjectcontent();
byte[] b = new byte[1024];
int len;
fileoutputstream fileoutputstream = new fileoutputstream("/tmp/" objectkey);
while ((len = inputstream.read(b)) != -1) {
fileoutputstream.write(b);
}
inputstream.close();
fileoutputstream.close();
} catch (obsexception ex) {
ex.printstacktrace();
} catch (ioexception e) {
throw new runtimeexception(e);
}
}
public void uploadfile() {
try {
// 待上传的本地文件路径,需要指定到具体的文件名
fileinputstream fis = new fileinputstream(new file("/tmp/" objectkey ".encrypt"));
obsclient.putobject(outputbucketname, objectkey, fis);
fis.close();
} catch (filenotfoundexception e) {
throw new runtimeexception(e);
} catch (ioexception e) {
throw new runtimeexception(e);
}
}
}
}
创建函数
创建函数的时候,必须选择委托包含obs和dew访问权限的委托,否则不能使用obs和dew服务。
- 登录,在左侧导航栏选择“函数 > 函数列表”,进入函数列表界面。
- 单击“创建函数”,进入创建函数流程。
- 选择“创建空白函数”,填写函数配置信息。
输入基础配置信息,完成后单击“创建函数”。
- 函数类型:事件函数。
- 函数名称:输入您自定义的函数名称,此处以“fss_examples_dew”为例。
- 委托名称:选择创建委托中创建的“serverless_trust”。
- 运行时语言:选择“java8”。
- 进入fss_examples_dew函数详情页,配置如下信息。
- 在“代码”页签,代码选择“上传自jar文件”,上传样例代码编译后的jar包,上传成功后单击“确定”。
- 在“设置 > 常规设置”页签,设置如下信息,完成后单击“保存”。
- 内存:选择“128”
- 执行超时时间:输入“3”
- 函数执行入口:默认“com.huawei.kms.fileencryptanddecrypt.encrypt”
- 所属应用:默认“default”
- 描述:输入“文件加解密”
- 在“设置 > 环境变量”页签,输入环境信息,完成后单击“保存”。
dew_endpoint:dew服务的endpoint地址
dew_key_id:用户主密钥id。
input_bucket: 输入文件对应的obs桶。
output_bucket: 加解密后上传的obs桶。
obs_endpoint: obs服务对应的endpoint。
表1 环境变量 环境变量
说明
dew_endpoint
dew服务终端节点,获取地址请参考。
dew_key_id
用户主密钥id。
input_bucket
存放输入文件的obs桶。
output_bucket
存放加密后上传文件的obs桶。
obs_endpoint
obs服务终端节点,获取地址请参考。
相关文档
意见反馈
文档内容是否对您有帮助?
提交成功!非常感谢您的反馈,我们会继续努力做到更好!
您可在查看反馈及问题处理状态。
系统繁忙,请稍后重试
如您有其它疑问,您也可以通过华为云社区问答频道来与我们联系探讨