maven依赖
<dependency>
<groupId>com.huaweicloud</groupId>
<artifactId>esdk-obs-java</artifactId>
<version>3.20.6.1</version>
</dependency>
yml文件中的配置
#新华为云OSS配置
huaweiobs:
endPoint: https://obs.*****.myhuaweicloud.com
ak: *************
sk: ***************
bucketName: ***********
工具类
package cn.com.yuanquanyun.utils.upload;
import cn.com.jit.cloud.common.MD5Util;
import cn.com.yuanquanyun.common.utils.HmacSha1Util;
import cn.com.yuanquanyun.common.utils.sign.Base64;
import cn.com.yuanquanyun.utils.Des3Util;
import cn.hutool.core.io.IoUtil;
import com.obs.services.model.ObjectMetadata;
import com.obs.services.ObsClient;
import com.obs.services.model.HttpMethodEnum;
import com.obs.services.model.ObsObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 华为云OBS
*/
@Component
public class OSSUtil {
static String endPoint;
static String ak;
static String sk;
static String bucketName;
private final static String KEY_MD5 = "x-obs-meta-plain-md5";
@Value("${huaweiobs.endPoint}")
public void setEndPoint(String endPoint) {
OSSUtil.endPoint = endPoint;
}
@Value("${huaweiobs.ak}")
public void setAk(String ak) {
OSSUtil.ak = ak;
}
@Value("${huaweiobs.sk}")
public void setSk(String sk) {
OSSUtil.sk = sk;
}
@Value("${huaweiobs.bucketName}")
public void setBucketName(String bucketName) {
OSSUtil.bucketName = bucketName;
}
public static void upload(String objectName, byte[] content) throws IOException {
ObsClient obsClient = null;
try{
// 构建metadata对象参数
ObjectMetadata objectMetadata = genMetadata(null, content);
// 创建ObsClient实例
obsClient = new ObsClient(ak, sk, endPoint);
// 使用访问OBS
obsClient.putObject(bucketName, objectName, new ByteArrayInputStream(Des3Util.encodeBytes(content)),objectMetadata);//带MD5校验
//obsClient.putObject(bucketName, objectName, new ByteArrayInputStream(Des3Util.encodeBytes(content)));//上传文件时不带MD5,那么下载时,也就不用校验MD5.
// 关闭obsClient
obsClient.close();
}catch (Exception ex){
}finally {
if(obsClient != null)
obsClient.close();
}
}
public static String getUrl(String objectName) {
// 创建ObsClient实例
ObsClient obsClient = new ObsClient(ak, sk, endPoint);
Date expiryTime = new Date(System.currentTimeMillis() + 3600 * 1000);
String url = obsClient.createSignedUrl(HttpMethodEnum.getValueFromStringCode("GET"),bucketName, objectName, null,expiryTime,null,null);
return url;
}
public static byte[] downloadByte(String objectName) {
ObsClient obsClient = null;
try{
// 创建ObsClient实例
obsClient = new ObsClient(ak, sk, endPoint);
ObsObject obsObject = obsClient.getObject(bucketName, objectName);
InputStream inputStream = obsObject.getObjectContent();
byte[] content = getBytes(inputStream);
byte[] decodeBytes = Des3Util.decodeBytes(content);
return decodeBytes;
}catch (Exception ex){
System.err.println(ex);
} finally {
if(obsClient != null)
try{
obsClient.close();
}catch (Exception ex){
System.err.println(ex);
}
}
return null;
}
public static byte[] getBytes(InputStream fis) {
byte[] buffer = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
public static void deleteLoad(String fileAddress) {
ObsClient obsClient = null;
try{
// 创建ObsClient实例
obsClient = new ObsClient(ak, sk, endPoint);
obsClient.deleteObject(bucketName,fileAddress);
}catch (Exception ex){
System.err.println(ex);
} finally {
if(obsClient != null)
try{
obsClient.close();
}catch (Exception ex){
System.err.println(ex);
}
}
}
public static String downloadBase64(String objectName) throws IOException {
ObsClient obsClient = null;
try{
// 创建ObsClient实例
obsClient = new ObsClient(ak, sk, endPoint);
ObsObject obsObject = obsClient.getObject(bucketName, objectName);
InputStream inputStream = obsObject.getObjectContent();
byte[] content = getBytes(inputStream);
byte[] decodeBytes = Des3Util.decodeBytes(content);
// MD5 校验 开始
String savedMd5 = obsObject.getMetadata().getMetadata().get(KEY_MD5).toString();
System.out.println("savedMd5=="+savedMd5);
if (StringUtils.isNotBlank(savedMd5)) {
//
String calMd5 = MD5Util.MD5(decodeBytes);
if (!savedMd5.equals(calMd5)) {
System.out.println("校验失败!");
throw new Exception(objectName + " 数据对象完整性校验失败");
}else {
System.out.println("校验成功!");
}
}
// MD5 校验 开始
return Base64.encode(decodeBytes);
}catch (Exception ex){
System.err.println(ex);
} finally {
if(obsClient != null)
try{
obsClient.close();
}catch (Exception ex){
System.err.println(ex);
}
}
return null;
}
public static boolean objectExist(String objectName){
ObsClient obsClient = null;
try{
// 创建ObsClient实例
obsClient = new ObsClient(ak, sk, endPoint);
boolean exist = obsClient.doesObjectExist(bucketName, objectName);
obsClient.close();
return exist;
}catch (Exception ex){
System.err.println(ex);
} finally {
if(obsClient != null)
try{
obsClient.close();
}catch (Exception ex){
System.err.println(ex);
}
}
return false;
}
/**
* 构建OSS对象属性信息,并对原文做MD5
*
* @param map
* @return
* @throws Exception
*/
private static ObjectMetadata genMetadata(Map<String, String> map, byte[] content) {
// ADD MD5
if (map == null) {
map = new HashMap<>();
}
String md5val = MD5Util.MD5(content);
map.put(KEY_MD5, md5val);
ObjectMetadata objectMetadata = new ObjectMetadata();
for (Map.Entry<String, String> entry : map.entrySet()) {
String mapKey = entry.getKey();
String mapValue = entry.getValue();
objectMetadata.addUserMetadata(mapKey, mapValue);
}
return objectMetadata;
}
}
package cn.com.yuanquanyun.utils;
import cn.com.yuanquanyun.common.utils.Base64;
import org.apache.commons.lang3.StringUtils;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.lang.reflect.Field;
import java.security.Key;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Des3Util {
// 向量
private final static String iv = "097889273";
// 加解密统一使用的编码方式
private final static String encoding = "UTF-8";
// 加密key TODO 做一下非对称的加密
private final static String secretKey = "dhfkdhdfkliieirtutuj";
/**
* 3DES加密
*
* @param plainText 普通文本
* @return
* @throws Exception
*/
public static String encode(String plainText) {
try {
if (StringUtils.isBlank(plainText)) {
return plainText;
}
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
return Base64.encodeBytes(encryptData);
} catch (Exception e) {
e.printStackTrace();
}
return plainText;
}
/**
* 3DES解密
*
* @param encryptText 加密文本
* @return
* @throws Exception
*/
public static String decode(String encryptText) {
try {
if (StringUtils.isBlank(encryptText)) {
return encryptText;
}
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
byte[] decryptData = cipher.doFinal(Base64.decode(encryptText));
return new String(decryptData, encoding);
} catch (Exception e) {
e.printStackTrace();
}
return encryptText;
}
/**
* 3DES加密
*
* @param plainText 普通文本,加密文本为字节数组
* @return 返回加密后的字节数组
* @throws Exception
*/
public static byte[] encodeBytes(byte[] plainText) {
try {
if (plainText == null) {
return null;
}
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
byte[] encryptData = cipher.doFinal(plainText);
return encryptData;
} catch (Exception e) {
e.printStackTrace();
}
return plainText;
}
/**
* 3DES解密
*
* @param encryptText 加密文本,byte[] 为加密原文未经过任何转码
* @return
* @throws Exception
*/
public static byte[] decodeBytes(byte[] encryptText) {
try {
if (encryptText == null) {
return null;
}
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
byte[] decryptData = cipher.doFinal(encryptText);
return decryptData;
} catch (Exception e) {
e.printStackTrace();
}
return encryptText;
}
/**
* 对listMap中的指定字段进行解密
*
* @param listMap
* @return
*/
public static List<Map<String, Object>> decodeListMap(List<Map<String, Object>> listMap, String... keys) {
if (listMap != null && listMap.size() > 0 && keys != null && keys.length > 0) {
for (Map<String, Object> map : listMap) {
for (int i = 0; i < keys.length; i++) {
String key = keys[i];
map.put(key, decode((String) map.get(key)));
}
}
}
return listMap;
}
/**
* 对listMap中的指定字段进行解密
*
* @param map
* @return
*/
public static Map<String, Object> decodeMap(Map<String, Object> map, String... keys) {
if (map != null && keys != null && keys.length > 0) {
for (int i = 0; i < keys.length; i++) {
String key = keys[i];
map.put(key, decode((String) map.get(key)));
}
}
return map;
}
/**
* 解密List下对象指定的属性值
*
* @param listBean
* @param keys
*/
public static <T> List<T> decodeListBean(List<T> listBean, String... keys) {
if (listBean != null && listBean.size() > 0 && keys != null && keys.length > 0) {
for (T bean : listBean) {
decodeBean(bean, keys);
}
}
return listBean;
}
/**
* 解密List下对象指定的属性值
*
* @param bean
* @param keys
*/
public static <T> T decodeBean(T bean, String... keys) {
if (bean!= null && keys != null && keys.length > 0) {
Class<?> bc = bean.getClass();
for (int i = 0; i < keys.length; i++) {
Field field = null;
try {
field = bc.getDeclaredField(keys[i]);
field.setAccessible(true);
String val = (String) field.get(bean);
field.set(bean, decode(val));
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return bean;
}
private String aa;
public String getAa() {
return aa;
}
public void setAa(String aa) {
this.aa = aa;
}
public static void main(String[] args) {
String text = "17600198405";
String encryptData = encode(text);
System.out.println("原始字符串:" + text);
System.out.println("加密后的值:" + encryptData);
//
String jiami = "G/JhLvch4w22Wgn1kRQ334i23migvMZa";
String decryptorData = decode(jiami);
System.out.println("解密字符串:" + jiami);
System.out.println("解密后的值:" + decryptorData);
List<Des3Util> list = new ArrayList<>();
Des3Util d = new Des3Util();
d.setAa("aWGVfeAnVO9QSN0ZXRZ46f3/apZOOuZP");
list.add(d);
decodeListBean(list, "aa");
System.out.println(d.getAa());
String temp = "R0uiBsi9kEY=";
System.out.println(temp.split(",").length);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/142642.html