21xrx.com
2024-09-17 04:12:41 Tuesday
登录
文章检索 我的文章 写文章
Java加密解密实现代码
2023-06-14 18:19:22 深夜i     --     --
Java加密 Java解密 对称加密 非对称加密 哈希加密

Java是一种广泛使用的编程语言,自然而然地也被用于加密和解密数据。本文将介绍一些常见的Java加密解密实现,并附上相应的代码案例。

一. 对称加密

对称加密算法指的是加密和解密使用同一个密钥的算法,其中最常见的是AES算法。以下是一个使用AES对称加密算法的示例代码:


import javax.crypto.Cipher;

import javax.crypto.spec.SecretKeySpec;

import java.util.Base64;

public class AESUtil {

  private static final String ALGORITHM = "AES";

  private static final String CHARSET = "UTF-8";

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

    try {

      byte[] raw = key.getBytes(CHARSET);

      SecretKeySpec skey = new SecretKeySpec(raw, ALGORITHM);

      Cipher cipher = Cipher.getInstance(ALGORITHM);

      cipher.init(Cipher.ENCRYPT_MODE, skey);

      byte[] encrypted = cipher.doFinal(data.getBytes(CHARSET));

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

    } catch (Exception e) {

      e.printStackTrace();

      return null;

    }

  }

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

    try {

      byte[] raw = key.getBytes(CHARSET);

      SecretKeySpec skey = new SecretKeySpec(raw, ALGORITHM);

      Cipher cipher = Cipher.getInstance(ALGORITHM);

      cipher.init(Cipher.DECRYPT_MODE, skey);

      byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedData));

      return new String(decrypted, CHARSET);

    } catch (Exception e) {

      e.printStackTrace();

      return null;

    }

  }

}

上述代码中,通过调用`encrypt`方法可以对数据进行加密,调用`decrypt`方法可以对加密数据进行解密。其中参数`key`为密钥,`data`为待加密数据,`encryptedData`为待解密数据(已经进行过Base64编码)。

二. 非对称加密

非对称加密算法指的是加密和解密使用不同密钥的算法,其中最常见的是RSA算法。以下是一个使用RSA非对称加密算法的示例代码:


import javax.crypto.Cipher;

import java.io.ByteArrayOutputStream;

import java.security.Key;

import java.security.KeyFactory;

import java.security.KeyPair;

import java.security.KeyPairGenerator;

import java.security.PrivateKey;

import java.security.PublicKey;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

public class RSAUtil {

  private static final String ALGORITHM = "RSA";

  private static final int KEY_LENGTH = 1024;

  public static KeyPair generateKeyPair() {

    try {

      KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM);

      keyPairGen.initialize(KEY_LENGTH);

      return keyPairGen.generateKeyPair();

    } catch (Exception e) {

      e.printStackTrace();

      return null;

    }

  }

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

    try {

      Cipher cipher = Cipher.getInstance(ALGORITHM);

      cipher.init(Cipher.ENCRYPT_MODE, publicKey);

      int blockSize = cipher.getBlockSize();

      ByteArrayOutputStream out = new ByteArrayOutputStream();

      int index = 0;

      while (index < data.length()) {

        int endIndex = Math.min(index + blockSize, data.length());

        byte[] encryptData = cipher.doFinal(data.substring(index, endIndex).getBytes());

        out.write(encryptData);

        index += blockSize;

      }

      return Base64.getEncoder().encodeToString(out.toByteArray());

    } catch (Exception e) {

      e.printStackTrace();

      return null;

    }

  }

  public static String decrypt(String encryptedData, PrivateKey privateKey) {

    try {

      Cipher cipher = Cipher.getInstance(ALGORITHM);

      cipher.init(Cipher.DECRYPT_MODE, privateKey);

      int blockSize = cipher.getBlockSize();

      ByteArrayOutputStream out = new ByteArrayOutputStream();

      byte[] decryptedData = Base64.getDecoder().decode(encryptedData);

      int index = 0;

      while (index < decryptedData.length) {

        int endIndex = Math.min(index + blockSize, decryptedData.length);

        byte[] data = cipher.doFinal(decryptedData, index, endIndex - index);

        out.write(data);

        index += blockSize;

      }

      return new String(out.toByteArray());

    } catch (Exception e) {

      e.printStackTrace();

      return null;

    }

  }

  public static PublicKey getPublicKey(String publicKey) {

    try {

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

      X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubKey);

      KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);

      return keyFactory.generatePublic(keySpec);

    } catch (Exception e) {

      e.printStackTrace();

      return null;

    }

  }

  public static PrivateKey getPrivateKey(String privateKey) {

    try {

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

      PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(priKey);

      KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);

      return keyFactory.generatePrivate(keySpec);

    } catch (Exception e) {

      e.printStackTrace();

      return null;

    }

  }

}

上述代码中,通过调用`generateKeyPair`方法可以生成公私密钥对,调用`encrypt`方法可以对数据进行加密,调用`decrypt`方法可以对加密数据进行解密。其中参数`publicKey`和`privateKey`分别为公钥和私钥(已经进行过Base64编码)。

三. 哈希加密

哈希加密算法指的是将任意长度的数据通过哈希函数,转换成固定长度的hash值(摘要),其中最常见的是MD5和SHA-1算法。以下是一个使用SHA-1哈希算法的示例代码:


import java.security.MessageDigest;

public class SHA1Util {

  private static final String ALGORITHM = "SHA-1";

  public static String encrypt(String data) {

    try {

      MessageDigest digest = MessageDigest.getInstance(ALGORITHM);

      digest.update(data.getBytes());

      byte[] messageDigest = digest.digest();

      StringBuilder hexString = new StringBuilder();

      for (byte b : messageDigest) {

        String hex = Integer.toHexString(0xFF & b);

        if (hex.length() == 1) {

          hexString.append('0');

        }

        hexString.append(hex);

      }

      return hexString.toString();

    } catch (Exception e) {

      e.printStackTrace();

      return null;

    }

  }

}

在上述代码中,通过调用`encrypt`方法可以对数据进行SHA-1哈希加密,其中参数`data`为待加密数据。

四. 总结

本文介绍了Java加密解密实现的三种常见方式:对称加密、非对称加密和哈希加密,分别附上了相应的代码案例。对于开发人员来说,熟知这些加密解密算法的原理和实现方式,是保障数据安全的关键之一。

  
  

评论区

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