数据结构-加解密算法

引言

加解密算法是信息安全领域的重要组成部分,它们用于保护数据的机密性、完整性和可用性。

对称加密算法

对称加密算法使用相同的密钥进行加密和解密。

特性:

加密和解密速度快,适合处理大量数据。

优点:

效率高,速度快。

缺点:

密钥管理困难,需要安全地分发和存储密钥。

运用场景:

文件加密、网络通信等。

Java代码示例(使用AES加密):

java 复制代码
import javax.crypto.Cipher;  
import javax.crypto.spec.SecretKeySpec;  
import java.nio.charset.StandardCharsets;  
import java.util.Base64;  
  
public class AESExample {  
    private static final String ALGORITHM = "AES";  
    private static final byte[] keyValue =   
        new byte[]{'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};  
  
    public static String encrypt(String valueToEnc) throws Exception {  
        Cipher cipher = Cipher.getInstance(ALGORITHM);  
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyValue, ALGORITHM));  
        byte[] encrypted = cipher.doFinal(valueToEnc.getBytes());  
        return Base64.getEncoder().encodeToString(encrypted);  
    }  
  
    public static String decrypt(String encryptedValue) throws Exception {  
        Cipher cipher = Cipher.getInstance(ALGORITHM);  
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyValue, ALGORITHM));  
        byte[] original = cipher.doFinal(Base64.getDecoder().decode(encryptedValue));  
  
        return new String(original);  
    }  
}

非对称加密算法

非对称加密算法使用一对密钥:公钥用于加密,私钥用于解密。

特性:

安全性高,适合密钥交换和数字签名。

优点:

解决了密钥分发和管理的问题。

缺点:

加密和解密速度相对较慢。

运用场景:

SSL/TLS协议、数字签名等。

Java代码示例(使用RSA加密和解密):

java 复制代码
import java.security.*;  
import javax.crypto.Cipher;  
import java.util.Base64;  
  
public class RSAExample {  
    public static void main(String[] args) throws Exception {  
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");  
        keyPairGen.initialize(2048);  
        KeyPair pair = keyPairGen.generateKeyPair();  
        PublicKey pub = pair.getPublic();  
        PrivateKey priv = pair.getPrivate();  
  
        String plainText = "Hello, RSA!";  
        Cipher encryptCipher = Cipher.getInstance("RSA");  
        encryptCipher.init(Cipher.ENCRYPT_MODE, pub);  
        byte[] cipherText = encryptCipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));  
        String encryptedString = Base64.getEncoder().encodeToString(cipherText);  
  
        Cipher decryptCipher = Cipher.getInstance("RSA");  
        decryptCipher.init(Cipher.DECRYPT_MODE, priv);  
        byte[] decryptedBytes = decryptCipher.doFinal(Base64.getDecoder().decode(encryptedString));  
        String decryptedString = new String(decryptedBytes, StandardCharsets.UTF_8);  
  
        System.out.println("Plain Text : " + plainText);  
        System.out.println("Encrypted Text : " + encryptedString);  
        System.out.println("Decrypted Text : " + decryptedString);  
    }  
}

哈希算法

哈希算法将任意长度的输入数据转换为固定长度的哈希值。

特性:

单向性,即无法通过哈希值反推出原始数据。

优点:

快速、高效。

缺点:

存在哈希碰撞的可能性。

运用场景:

数据完整性校验、密码存储等。

Java代码示例(使用SHA-256哈希):

java 复制代码
import java.security.MessageDigest;  
import java.nio.charset.StandardCharsets;  
import java.math.BigInteger;  
  
public class SHA256Example {  
    public static String getSHA256(String input) {  
        try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");  
            byte[] messageDigest = md.digest(input.getBytes(StandardCharsets.UTF_8));  
            BigInteger number = new BigInteger(1, messageDigest);  
            String hashtext = number.toString(16);  
            while (hashtext.length() < 32) {  
                hashtext = "0" + hashtext;  
            }  
            return hashtext;  
        } catch (NoSuchAlgorithmException e) {  
            throw new RuntimeException(e);  
        }  
    }  
  
    public static void main(String[] args) {  
        String input = "Hello, SHA-256!";  
        String sha256 = getSHA256(input);  
        System.out.println("SHA-256 hash of \"" + input + "\": " + sha256);  
    }  
}

总结

每种加密算法都有其特定的用途和适用场景。在实际应用中,您应该根据数据的敏感性、处理性能要求以及安全需求来选择合适的加密算法。此外,还需要考虑算法的安全性、兼容性以及是否受到已知的攻击或漏洞影响。

相关推荐
地平线开发者8 小时前
J6B vio scenario sample
算法
BothSavage20 小时前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn20 小时前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
烬羽1 天前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
先吃饱再说2 天前
判断回文字符串,从一行代码到双指针优化
算法
黄敬峰2 天前
深入理解算法核心:从递归思想、数组扁平化到快速排序
算法
得物技术2 天前
从狂野代码到按目标生产:得物推荐 AI Harness 的工程化实践|AICon 演讲整理
人工智能·算法·架构
AI小老六2 天前
SkillOpt 架构拆解:把 Skill 文本当参数,用执行轨迹训练 Agent
后端·算法·ai编程