Java 简单加密解密算法示例:结合 ID 和字符串

本文提供一个简单的 Java 加密解密算法示例,使用 Base64 编码将 ID 和字符串加密成新的字符串,并提供解密方法恢复原始数据。示例代码易于理解,适合初学者学习加密解密的基本概念。

示例代码:

import java.util.Base64;

public class EncryptionAlgorithm {
    
    private static final String SECRET_KEY = 'secret_key';
    
    public static void main(String[] args) {
        long id = 123456789L;
        String text = 'Hello World!';
        
        // 加密
        String encryptedString = encrypt(id, text);
        System.out.println('Encrypted String: ' + encryptedString);
        
        // 解密
        DecryptionResult decryptionResult = decrypt(encryptedString);
        System.out.println('Decrypted Id: ' + decryptionResult.getId());
        System.out.println('Decrypted Text: ' + decryptionResult.getText());
    }
    
    public static String encrypt(long id, String text) {
        String input = id + '-' + text;
        String encryptedString = Base64.getEncoder().encodeToString(input.getBytes());
        return encryptedString;
    }
    
    public static DecryptionResult decrypt(String encryptedString) {
        String decryptedString = new String(Base64.getDecoder().decode(encryptedString));
        String[] parts = decryptedString.split('-');
        long id = Long.parseLong(parts[0]);
        String text = parts[1];
        return new DecryptionResult(id, text);
    }
    
    public static class DecryptionResult {
        private long id;
        private String text;
        
        public DecryptionResult(long id, String text) {
            this.id = id;
            this.text = text;
        }
        
        public long getId() {
            return id;
        }
        
        public String getText() {
            return text;
        }
    }
}

算法原理:

这个示例使用了 Base64 编码来进行加密和解密,同时将 id 和字符串用 '-' 连接在一起形成一个输入字符串。在解密时,通过分割字符串,获取原始的 id 和字符串。

注意:

这个示例中的加密算法并不是特别安全,仅仅是为了演示目的。在实际应用中,你可能需要使用更复杂和安全的加密算法来保护你的数据。

更多学习资源:

Java 简单加密解密算法示例:结合 ID 和字符串

原文地址: https://www.cveoy.top/t/topic/hOAr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录