All Products
Search
Document Center

Key Management Service:Quick start of Encryption SDK for Java

Last Updated:Jun 15, 2023

Encryption SDK is a client-side encryption library and is used with Key Management Service (KMS). This way, you can encrypt data, decrypt data, and sign data and verify signatures. This topic describes how to use Encryption SDK for Java to encrypt and decrypt data.

Background information

For more information about sample code, visit alibabacloud-encryption-sdk-java.

Install Encryption SDK on your on-premises machine

  1. Compile and install Encryption SDK.

    git clone https://github.com/aliyun/alibabacloud-encryption-sdk-java.git
    cd alibabacloud-encryption-sdk-java
    mvn clean install -DskipTests
  2. Add a dependency to your project.

    <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
    </dependency>
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>alibabacloud-encryption-sdk-java</artifactId>
        <version>X.X.X</version>
    </dependency>

Install Encryption SDK from the Maven repository

Add the alibabacloud-encryption-sdk-java dependency to your project. Then, your project can automatically download the published Java package of Encryption SDK from the Maven repository.

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>alibabacloud-encryption-sdk-java</artifactId>
    <version>X.X.X</version>
</dependency>
Note

For more information about the latest version of Encryption SDK, visit Alibaba Cloud Encryption SDK for Java.

Examples of data encryption and decryption

Note

The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using the AccessKey pair to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised.

In this example, the AccessKey pair is saved in ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to implement identity authentication. For more information about how to configure authentication information, see Credentials.

  • Encrypt and decrypt data of the byte array type.

    public class BasicEncryptionExample {
        private static final String ACCESS_KEY_ID = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        private static final String ACCESS_KEY_SECRET = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        private static final String CMK_ARN = "acs:kms:RegionId:UserId:key/CmkId";
        private static final byte[] PLAIN_TEXT = "Hello World".getBytes(StandardCharsets.UTF_8);
    
        public static void main(String[] args) {
            // 1. Configure parameters to access Alibaba Cloud. 
            AliyunConfig config = new AliyunConfig();
            config.withAccessKey(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
    
            // 2. Create an SDK object and specify the parameters that are used to access Alibaba Cloud. 
            AliyunCrypto aliyunSDK = new AliyunCrypto(config);
    
            // 3. Create a provider that provides a data key or signature. 
            BaseDataKeyProvider provider = new DefaultDataKeyProvider(CMK_ARN);
            // Configure the algorithm. The default algorithm is AES_GCM_NOPADDING_256. 
            //provider.setAlgorithm(CryptoAlgorithm.SM4_GCM_NOPADDING_128);
    
            // 4. Configure the encryption context. 
            Map<String, String> encryptionContext = new HashMap<>();
            encryptionContext.put("one", "one");
            encryptionContext.put("two", "two");
    
            // 5. Call the Encrypt and Decrypt operations. 
            CryptoResult<byte[]> cipherResult = aliyunSDK.encrypt(provider, PLAIN_TEXT, encryptionContext);
            CryptoResult<byte[]> plainResult = aliyunSDK.decrypt(provider, cipherResult.getResult());
    
            Assert.assertArrayEquals(PLAIN_TEXT, plainResult.getResult());
        }
    }
    Note
  • Encrypt and decrypt data of the byte stream type.

    public class FileStreamSample {
        private static final String FILE = "README.md";
        // accessKeyId accessKeySecret
        private static final String ACCESS_KEY_ID = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        private static final String ACCESS_KEY_SECRET = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // The log system. 
        private static final Logger LOGGER = LoggerFactory.getLogger(FileStreamSample.class);
        // The ID of the customer master key (CMK) in the Alibaba Cloud Resource Name (ARN) format. 
        private static final String CMK_ARN = "acs:kms:RegionId:UserId:key/CmkId";
    
        public static void main(String[] args) throws IOException {
            AliyunConfig config = new AliyunConfig();
            config.withAccessKey(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
            encryptStream(config);
            decryptStream(config);
            Assert.assertEquals(getFileMD5(FILE), getFileMD5(FILE + ".decrypted"));
        }
    
        private static void encryptStream(AliyunConfig config) throws IOException {
            // 1. Create an SDK object and specify the parameters that are used to access Alibaba Cloud. 
            AliyunCrypto aliyunSDK = new AliyunCrypto(config);
    
            // 2. Configure the encryption context. 
            final Map<String, String> encryptionContext = new HashMap<>();
            encryptionContext.put("this", "context");
            encryptionContext.put("can help you", "to confirm");
            encryptionContext.put("this data", "is your original data");
    
            // 3. Create a provider that provides a data key. 
            BaseDataKeyProvider provider = new DefaultDataKeyProvider(CMK_ARN);
    
            // 4. Create input and output streams. 
            FileInputStream inputStream = new FileInputStream(FILE);
            FileOutputStream outputStream = new FileOutputStream(FILE + ".encrypted");
    
            // 5. Call the Encrypt operation. 
            try {
                aliyunSDK.encrypt(provider, inputStream, outputStream, encryptionContext);
            } catch (InvalidAlgorithmException e) {
                System.out.println("Failed.");
                System.out.println("Error message: " + e.getMessage());
            }
        }
    
        private static void decryptStream(AliyunConfig config) throws IOException {
            // 1. Create an SDK object and specify the parameters that are used to access Alibaba Cloud. 
            AliyunCrypto aliyunSDK = new AliyunCrypto(config);
    
            // 2. Create a provider that provides a data key. 
            BaseDataKeyProvider provider = new DefaultDataKeyProvider(CMK_ARN);
    
            // 3. Create input and output streams. 
            FileInputStream inputStream = new FileInputStream(FILE + ".encrypted");
            FileOutputStream outputStream = new FileOutputStream(FILE + ".decrypted");
    
            // 4. Call the Decrypt operation. 
            try {
                aliyunSDK.decrypt(provider, inputStream, outputStream);
            } catch (InvalidAlgorithmException e) {
                System.out.println("Failed.");
                System.out.println("Error message: " + e.getMessage());
            }
        }
    
        private static String getFileMD5(String fileName) {
            File file = new File(fileName);
            if  (!file.isFile()) {
                return null;
            }
            MessageDigest digest;
            byte[] buffer = new byte[4096];
            try (FileInputStream in = new FileInputStream(file)){
                digest = MessageDigest.getInstance("MD5");
                int len;
                while  ((len = in.read(buffer)) != -1) {
                    digest.update(buffer,  0 , len);
                }
                return Hex.encodeHexString(digest.digest());
            }  catch  (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }