jinlin
2024-03-11 b56a59e06e76c635e5f12931ed98852367b867d8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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);
    }
}