Java API를 사용하여 Word 파일에 비밀번호를 설정하고 암호화하는 것은 배포 전에 민감한 문서를 보호해야 하는 기업에게 일반적인 요구 사항입니다. Aspose.Words Cloud SDK for Java는 Java 애플리케이션에서 직접 DOCX 파일에 비밀번호 보호 및 암호화를 추가할 수 있는 간단한 라이브러리를 제공합니다. 이 가이드에서는 SDK를 구성하고, 문서를 업로드하며, 비밀번호를 사용한 읽기 전용 보호를 적용하고, 보호된 파일을 가져오는 방법을 배웁니다. 또한 이 튜토리얼에는 REST API 사용자를 위한 동등한 cURL 명령과 안전한 문서 처리를 위한 모범 사례 권장 사항이 포함되어 있습니다.

Java API를 사용하여 Word 파일을 비밀번호로 보호하고 암호화하는 5단계

  1. 소스 DOCX를 Aspose Cloud 스토리지에 업로드: UploadFileRequest를 사용하여 로컬 파일을 클라우드로 전송합니다.

    Path inputPath = Paths.get(localInputPath);
    byte[] inputData = Files.readAllBytes(inputPath);
    UploadFileRequest uploadRequest = new UploadFileRequest(remoteInputFile, inputData, null, null);
    wordsApi.uploadFile(uploadRequest);
    
  2. 비밀번호로 보호 요청 생성: ProtectionRequest를 인스턴스화하고, 비밀번호를 설정한 뒤 READ_ONLY 보호를 선택합니다.

    ProtectionRequest protection = new ProtectionRequest();
    protection.setPassword(documentPassword);
    protection.setProtectionType(ProtectionRequest.ProtectionTypeEnum.READ_ONLY);
    
  3. 보호를 적용하고 문서를 암호화: 소스와 대상 파일 이름을 사용하여 PutProtectDocumentRequest를 호출합니다.

    PutProtectDocumentRequest protectRequest = new PutProtectDocumentRequest(
            remoteInputFile,
            protection,
            null,
            null,
            null,
            null,
            remoteOutputFile,
            null,
            null);
    wordsApi.putProtectDocument(protectRequest);
    
  4. 보호된 DOCX 다운로드: DownloadFileRequest를 사용하여 암호화된 파일을 가져옵니다.

    DownloadFileRequest downloadRequest = new DownloadFileRequest(remoteOutputFile, null, null);
    byte[] protectedData = wordsApi.downloadFile(downloadRequest);
    Path outputPath = Paths.get(localOutputPath);
    Files.write(outputPath, protectedData);
    
  5. (선택 사항) 원격 파일 정리: 더 이상 필요하지 않은 경우 스토리지에서 임시 파일을 삭제합니다.

자세한 클래스 정보는 WordsApi 참조를 확인하십시오.

Java API를 사용한 Word 파일 비밀번호 보호 및 암호화 - 전체 코드 예제

이 예제에서는 DOCX 파일을 업로드하고, 비밀번호 보호를 적용한 뒤, Aspose.Words Cloud SDK for Java를 사용하여 보안된 파일을 다운로드하는 방법을 보여줍니다.

import com.aspose.words.cloud.ApiClient;
import com.aspose.words.cloud.api.WordsApi;
import com.aspose.words.cloud.model.ProtectionRequest;
import com.aspose.words.cloud.model.requests.DownloadFileRequest;
import com.aspose.words.cloud.model.requests.PutProtectDocumentRequest;
import com.aspose.words.cloud.model.requests.UploadFileRequest;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ProtectAndEncryptWord {
    public static void main(String[] args) {
        // Replace with your actual Aspose Cloud credentials
        final String clientId = "YOUR_CLIENT_ID";
        final String clientSecret = "YOUR_CLIENT_SECRET";

        // File locations (local)
        final String localInputPath = "input.docx";
        final String localOutputPath = "output_protected.docx";

        // Remote file names (in Aspose Cloud storage)
        final String remoteInputFile = "input.docx";
        final String remoteOutputFile = "output_protected.docx";

        // Password to protect the document
        final String documentPassword = "MySecretPassword";

        // Initialize API client
        ApiClient apiClient = new ApiClient();
        apiClient.setBasePath("https://api.aspose.cloud");
        apiClient.setAppSid(clientId);
        apiClient.setAppKey(clientSecret);
        WordsApi wordsApi = new WordsApi(apiClient);

        try {
            // Upload local document to Aspose Cloud storage
            Path inputPath = Paths.get(localInputPath);
            byte[] inputData = Files.readAllBytes(inputPath);
            UploadFileRequest uploadRequest = new UploadFileRequest(remoteInputFile, inputData, null, null);
            wordsApi.uploadFile(uploadRequest);

            // Create protection request with password and protection type
            ProtectionRequest protection = new ProtectionRequest();
            protection.setPassword(documentPassword);
            protection.setProtectionType(ProtectionRequest.ProtectionTypeEnum.READ_ONLY);

            // Apply protection and encrypt the document
            PutProtectDocumentRequest protectRequest = new PutProtectDocumentRequest(
                    remoteInputFile,          // source file name
                    protection,              // protection settings
                    null,                    // folder (root)
                    null,                    // storage
                    null,                    // loadEncoding
                    null,                    // password (none, because we are adding one)
                    remoteOutputFile,        // destination file name
                    null,                    // revisionAuthor
                    null                     // revisionDateTime
            );
            wordsApi.putProtectDocument(protectRequest);

            // Download the protected document back to local storage
            DownloadFileRequest downloadRequest = new DownloadFileRequest(remoteOutputFile, null, null);
            byte[] protectedData = wordsApi.downloadFile(downloadRequest);
            Path outputPath = Paths.get(localOutputPath);
            Files.write(outputPath, protectedData);

            // Optional: clean up remote files
            // wordsApi.deleteFile(new DeleteFileRequest(remoteInputFile, null, null));
            // wordsApi.deleteFile(new DeleteFileRequest(remoteOutputFile, null, null));

            System.out.println("Document protected and saved to: " + localOutputPath);
        } catch (IOException e) {
            System.err.println("File I/O error: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("Aspose API error: " + e.getMessage());
        }
    }
}

Note: 이 코드 예제는 핵심 기능을 보여줍니다. 프로젝트에 사용하기 전에 파일 경로와 구성 값을 실제 환경에 맞게 업데이트하고, 모든 필수 종속성이 올바르게 설치되었는지 확인하며, 개발 환경에서 충분히 테스트하십시오. 문제가 발생하면 공식 문서를 참조하거나 지원 팀에 문의하십시오.

cURL을 사용한 REST API를 통한 Word 문서 보호 및 암호화

다음 cURL 명령은 Java 코드와 동일한 작업을 수행하지만 Aspose.Words Cloud REST 엔드포인트를 통해 실행됩니다.

  1. 액세스 토큰 얻기
    YOUR_CLIENT_ID와 YOUR_CLIENT_SECRET를 귀하의 자격 증명으로 교체하십시오.

    curl -X POST "https://api.aspose.cloud/connect/token" \
         -H "Content-Type: application/x-www-form-urlencoded" \
         -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"
    
  2. 소스 DOCX 업로드

curl -X PUT "https://api.aspose.cloud/v4.0/words/storage/file/input.docx" \
        -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
        -H "Content-Type: application/octet-stream" \
        --data-binary "@input.docx"
  1. 비밀번호 보호 적용 (읽기 전용)
curl -X PUT "https://api.aspose.cloud/v4.0/words/input.docx/protect?destFileName=output_protected.docx" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{
           "Password": "MySecretPassword",
           "ProtectionType": "ReadOnly"
         }'
  1. 보호된 DOCX 다운로드
curl -X GET "https://api.aspose.cloud/v4.0/words/storage/file/output_protected.docx" \
        -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
        -o output_protected.docx

자세한 내용은 공식 API 문서를 참조하십시오.

Aspose.Words Cloud SDK for Java 설치 및 구성

Add the Maven dependency to your project’s pom.xml (or the equivalent Gradle snippet).

<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-words-cloud</artifactId>
    <version>26.10.0</version>
</dependency>

Download the latest library from the release page.
Initialize the client as shown in the code example (excerpt):

ApiClient apiClient = new ApiClient();
apiClient.setBasePath("https://api.aspose.cloud");
apiClient.setAppSid("YOUR_CLIENT_ID");
apiClient.setAppKey("YOUR_CLIENT_SECRET");
WordsApi wordsApi = new WordsApi(apiClient);

Make sure you have a valid Aspose Cloud account and have generated the client ID and secret.

Aspose.Words Cloud SDK for Java 문서 보안 기능

  • Password protection - 사용자 지정 비밀번호로 읽기 전용, 주석 또는 추적 변경 보호를 적용합니다.
  • Encryption - 비밀번호가 설정되면 SDK가 전체 DOCX 파일을 암호화하여 무단 접근을 방지합니다.
  • Cloud storage integration - Aspose Cloud 스토리지에서 파일을 직접 업로드 및 다운로드하여 워크플로 자동화를 간소화합니다.
  • Fine‑grained control - 보안 정책에 맞게 여러 ProtectionTypeEnum 값 중에서 선택합니다.
  • Cross‑platform support - 데스크톱 애플리케이션부터 서버 측 서비스까지 Java 호환 환경에서 모두 작동합니다.

Best Practices for Securing Word Files with Aspose.Words

  • 강력한 비밀번호 사용: 대문자, 소문자, numbers, 및 기호를 결합하여 무차별 대입 공격에 대비합니다.
  • 자격 증명을 안전하게 저장: clientId와 clientSecret을 소스 코드에 포함하지 말고, 환경 변수나 비밀 관리자를 사용하십시오.
  • 파일 크기 검증: 업로드된 문서의 크기를 확인하여 암호화 중 과도한 메모리 사용을 방지합니다.
  • 권한 제한: 보호 작업에 사용되는 API 키에 필요한 저장 권한만 부여합니다.
  • 복호화 테스트: 보호를 적용한 후 파일을 다운로드하고 비밀번호가 예상대로 작동하는지 확인한 뒤 사용자에게 배포합니다.

최종 생각

Java API를 사용하여 Word 파일에 비밀번호 보호 및 암호화를 적용하는 것은 현대 애플리케이션에서 기밀 정보를 보호하는 데 필수적입니다. Aspose.Words Cloud SDK for Java을 활용하면 개발자는 DOCX를 업로드하고 읽기 전용 보호를 적용한 후 암호화된 결과를 가져오는 전체 워크플로를 자동화할 수 있습니다. SDK의 풍부한 API와 간단한 cURL 대안이 결합되어 문서 보안을 모든 Java 기반 시스템에 쉽게 통합할 수 있습니다. 프로덕션 사용을 위해 적절한 라이선스를 확보하는 것을 기억하세요; 가격 세부 정보는 제품 페이지에서 확인할 수 있으며, 솔루션을 평가하는 동안 임시 라이선스 페이지에서 임시 라이선스를 얻을 수 있습니다.

자주 묻는 질문

Aspose.Words에서 Java API를 사용하여 Word 파일을 비밀번호로 보호하고 암호화하는 방법은 어떻게 작동합니까?
이 프로세스는 DOCX 파일을 Aspose Cloud 저장소에 업로드하고, 비밀번호와 보호 유형을 포함하는 ProtectionRequest를 생성한 다음, PutProtectDocument를 호출하여 설정을 적용하고, 마지막으로 암호화된 파일을 다운로드합니다. SDK는 모든 암호화 세부 정보를 내부적으로 처리합니다.

Java에서 프로그래밍으로 Word 문서를 암호화할 때 읽기 전용 외에 다른 보호 유형을 사용할 수 있나요?
예. ProtectionRequest.ProtectionTypeEnum 열거형에는 COMMENTS, TRACK_CHANGES, FORMS와 같은 옵션이 포함되어 있습니다. 보안 요구 사항에 맞는 유형을 선택하십시오.

문서를 먼저 로컬에 다운로드하지 않고 보호할 수 있나요?
물론입니다. 모든 작업은 클라우드 스토리지에서 직접 수행할 수 있습니다. 보호 후에는 파일을 Aspose Cloud에 보관하거나 나중에 DownloadFileRequest를 사용하여 다운로드할 수 있습니다.

Aspose.Words Java API의 프로덕션 배포에 필요한 라이선스는 무엇인가요?
프로덕션에서는 상업용 라이선스가 필요합니다. 제품 페이지에서 가격을 확인하고 임시 라이선스 페이지에서 임시 평가 라이선스를 얻을 수 있습니다.

계속 탐색하기