后台

42 阅读1分钟

  import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.security.Key; import java.util.Base64;

public class AESUtil { private static final String ALGORITHM = "AES";

public static byte[] encrypt(byte[] data, String key) throws Exception {
    Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    return cipher.doFinal(data);
}

public static String generateKey() {
    // 生成16字节(128位)的随机密钥
    return "ThisIsASecretKey"; // 示例固定密钥,实际应随机生成并安全传输
}

}

  import org.springframework.core.io.ByteArrayResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;

import java.nio.file.Files; import java.nio.file.Paths;

@RestController public class PdfController {

@GetMapping("/encrypted-pdf")
public ResponseEntity<ByteArrayResource> getEncryptedPdf() throws Exception {
    // 读取本地PDF文件
    byte[] pdfBytes = Files.readAllBytes(Paths.get("path/to/your/file.pdf"));
    
    // 生成密钥并加密
    String key = AESUtil.generateKey();
    byte[] encryptedBytes = AESUtil.encrypt(pdfBytes, key);
    
    // 返回加密后的数据及密钥(密钥应通过安全方式传输)
    return ResponseEntity.ok()
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"encrypted.pdf\"")
            .header("Encryption-Key", key) // 实际应使用HTTPS并加密传输密钥
            .body(new ByteArrayResource(encryptedBytes));
}

}