21xrx.com
2024-12-23 04:47:50 Monday
登录
文章检索 我的文章 写文章
Java中常用的加密方式及代码示例
2023-06-16 08:47:48 深夜i     --     --
Java加密 对称加密 非对称加密 哈希加密

在Java开发中,数据加密是一个重要的安全措施。常用的加密方式有对称加密、非对称加密和哈希加密。本文将分别介绍这三种加密方式的基本原理和实现方法,同时提供对应的Java代码示例。

1. 对称加密

对称加密是指加密和解密使用相同的密钥的加密方式。对称加密算法的优点是加密速度快,缺点是密钥的传输和管理难度较大。常见的对称加密算法有DES、3DES、AES等。

下面是一个使用AES加密算法进行对称加密的Java代码示例:


import javax.crypto.Cipher;

import javax.crypto.spec.SecretKeySpec;

import java.nio.charset.StandardCharsets;

import java.util.Base64;

public class SymmetricEncryptionDemo {

  // 加密

  public static String encrypt(String key, String data) {

    try {

      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

      SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");

      cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

      byte[] bytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));

      return Base64.getEncoder().encodeToString(bytes);

    } catch (Exception e) {

      e.printStackTrace();

      return null;

    }

  }

  // 解密

  public static String decrypt(String key, String data) {

    try {

      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

      SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");

      cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

      byte[] bytes = Base64.getDecoder().decode(data);

      byte[] result = cipher.doFinal(bytes);

      return new String(result, StandardCharsets.UTF_8);

    } catch (Exception e) {

      e.printStackTrace();

      return null;

    }

  }

  public static void main(String[] args) {

    String key = "1234567890abcdef";

    String data = "Hello, world!";

    String encryptedData = encrypt(key, data);

    System.out.println("Encrypted data: " + encryptedData);

    String decryptedData = decrypt(key, encryptedData);

    System.out.println("Decrypted data: " + decryptedData);

  }

}

2. 非对称加密

非对称加密是指加密和解密使用不同的密钥的加密方式。非对称加密算法的优点是密钥管理方便,缺点是加密速度相对较慢。常见的非对称加密算法有RSA、DSA等。

下面是一个使用RSA加密算法进行非对称加密的Java代码示例:


import javax.crypto.Cipher;

import java.nio.charset.StandardCharsets;

import java.security.KeyPair;

import java.security.KeyPairGenerator;

import java.security.PrivateKey;

import java.security.PublicKey;

import java.util.Base64;

public class AsymmetricEncryptionDemo {

  // 加密

  public static String encrypt(String publicKey, String data) {

    try {

      Cipher cipher = Cipher.getInstance("RSA");

      PublicKey key = getPublicKey(publicKey);

      cipher.init(Cipher.ENCRYPT_MODE, key);

      byte[] bytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));

      return Base64.getEncoder().encodeToString(bytes);

    } catch (Exception e) {

      e.printStackTrace();

      return null;

    }

  }

  // 解密

  public static String decrypt(String privateKey, String data) {

    try {

      Cipher cipher = Cipher.getInstance("RSA");

      PrivateKey key = getPrivateKey(privateKey);

      cipher.init(Cipher.DECRYPT_MODE, key);

      byte[] bytes = Base64.getDecoder().decode(data);

      byte[] result = cipher.doFinal(bytes);

      return new String(result, StandardCharsets.UTF_8);

    } catch (Exception e) {

      e.printStackTrace();

      return null;

    }

  }

  // 获取公钥

  public static PublicKey getPublicKey(String publicKey) {

    try {

      byte[] bytes = Base64.getDecoder().decode(publicKey);

      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

      keyPairGenerator.initialize(1024);

      KeyPair keyPair = keyPairGenerator.generateKeyPair();

      PublicKey publicKeyObj = keyPair.getPublic();

      return publicKeyObj;

    } catch (Exception e) {

      e.printStackTrace();

      return null;

    }

  }

  // 获取私钥

  public static PrivateKey getPrivateKey(String privateKey) {

    try {

      byte[] bytes = Base64.getDecoder().decode(privateKey);

      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

      keyPairGenerator.initialize(1024);

      KeyPair keyPair = keyPairGenerator.generateKeyPair();

      PrivateKey privateKeyObj = keyPair.getPrivate();

      return privateKeyObj;

    } catch (Exception e) {

      e.printStackTrace();

      return null;

    }

  }

  public static void main(String[] args) {

    String data = "Hello, world!";

    // 生成公钥和私钥

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

    keyPairGenerator.initialize(1024);

    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    PublicKey publicKey = keyPair.getPublic();

    PrivateKey privateKey = keyPair.getPrivate();

    String publicKeyStr = Base64.getEncoder().encodeToString(publicKey.getEncoded());

    String privateKeyStr = Base64.getEncoder().encodeToString(privateKey.getEncoded());

    // 加密

    String encryptedData = encrypt(publicKeyStr, data);

    System.out.println("Encrypted data: " + encryptedData);

    // 解密

    String decryptedData = decrypt(privateKeyStr, encryptedData);

    System.out.println("Decrypted data: " + decryptedData);

  }

}

3. 哈希加密

哈希加密是指将任意长度的数据映射为固定长度的数据的一种加密方式。哈希加密的优点是加密速度快,不可逆,缺点是不能解密。常见的哈希加密算法有MD5、SHA-1、SHA-256等。

下面是一个使用MD5加密算法进行哈希加密的Java代码示例:


import java.math.BigInteger;

import java.security.MessageDigest;

public class HashEncryptionDemo {

  // 对字符串进行MD5哈希加密

  public static String md5(String str) {

    try {

      MessageDigest md = MessageDigest.getInstance("MD5");

      md.update(str.getBytes());

      return new BigInteger(1, md.digest()).toString(16);

    } catch (Exception e) {

      e.printStackTrace();

      return null;

    }

  }

  public static void main(String[] args) {

    String str = "Hello, world!";

    String md5Str = md5(str);

    System.out.println("MD5 hash: " + md5Str);

  }

}

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复