package com.zt.life.modules.mainPart.test.controller; import cn.hutool.core.io.IoUtil; import com.zt.core.oss.encry.IOssEncryptService; import org.springframework.web.bind.annotation.*; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import java.io.File; import java.io.InputStream; import java.security.Key; import java.security.SecureRandom; @RestController @RequestMapping("sys/OssDecryptFile") public class OssDecryptFileControl implements IOssEncryptService { // optional value AES/DES/DESede public static String DES = "AES"; // optional value AES/DES/DESede public static String CIPHER_ALGORITHM = "AES"; private static String KEY = "zhpt-key#%W"; @Override public InputStream encrypt(InputStream inputStream) { try { return encrypt(inputStream, KEY); } catch (Exception e) { return inputStream; } } @Override public InputStream decrypt(File file) { try { return decrypt(file, KEY); } catch (Exception e) { return IoUtil.toStream(file); } } public static Key getKey(String strKey) { try { if (strKey == null) { strKey = ""; } KeyGenerator _generator = KeyGenerator.getInstance("AES"); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); secureRandom.setSeed(strKey.getBytes()); _generator.init(128, secureRandom); return _generator.generateKey(); } catch (Exception e) { throw new RuntimeException(" 密钥出现异常 "); } } public static InputStream encrypt(InputStream inputStream, String key) throws Exception { SecureRandom sr = new SecureRandom(); Key secureKey = getKey(key); Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secureKey, sr); byte[] bt = cipher.doFinal(IoUtil.readBytes(inputStream)); String strS = new BASE64Encoder().encode(bt); return IoUtil.toStream(strS.getBytes()); } public static InputStream decrypt(File file, String key) throws Exception { SecureRandom sr = new SecureRandom(); Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); Key secureKey = getKey(key); cipher.init(Cipher.DECRYPT_MODE, secureKey, sr); byte[] res = new BASE64Decoder().decodeBuffer(IoUtil.toStream(file)); res = cipher.doFinal(res); return IoUtil.toStream(res); } }