21xrx.com
2024-09-17 04:55:15 Tuesday
登录
文章检索 我的文章 写文章
最近
2023-06-10 14:17:18 深夜i     --     --
Java加密 MessageDigest Cipher KeyStore

最近,我开始对Java加密技术进行了一些深入的研究。在探索的过程中,我了解到Java中存在多种可用于加密的方法。在本文中,我将介绍三种主要的加密方法。

第一种加密方式是 MessageDigest。该方法使用“数字摘要”算法来加密数据。下面是一个使用SHA-256算法加密的例子:


import java.security.MessageDigest;

public class MessageDigestExample {

  public static void main(String[] args)throws Exception{

   String password = "myPassword123";

   MessageDigest md = MessageDigest.getInstance("SHA-256");

   md.update(password.getBytes());

   byte[] bytes = md.digest();

   StringBuilder sb = new StringBuilder();

   for(int i=0; i< bytes.length ;i++){

     sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));

   }

   String encryptedPassword = sb.toString();

   System.out.println(encryptedPassword);

  }

}

第二种加密方式是 Cipher。Cipher可以使用许多加密算法,例如AES、DES等。下面是一个使用AES算法加密的例子:


import javax.crypto.Cipher;

import javax.crypto.spec.IvParameterSpec;

import javax.crypto.spec.SecretKeySpec;

public class CipherExample {

  public static void main(String[] args) throws Exception {

   String password = "myPassword123";

   String key = "myEncryptionKey";

   String initVector = "encryptionIntVec";

   IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));

   SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

   Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");

   cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

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

   System.out.println(new String(encrypted));

  }

}

最后一种加密方式是 KeyStore。它是一种用于保护密钥的存储介质。下面是一个简单的KeyStore示例:


import java.io.*;

import java.security.*;

public class KeyStoreExample {

  public static void main(String[] args) throws Exception {

   String password = "myPassword123";

   KeyStore ks = KeyStore.getInstance("JKS");

   FileInputStream fis = new FileInputStream("keystore.jks");

   ks.load(fis, password.toCharArray());

   fis.close();

  }

}

总的来说,Java提供了许多种加密方式以供使用。我已经向您介绍了三种主要的方式,但这其中还有很多其他的方法和算法。现在,您可以使用这些方法确保您的敏感信息得到最好的保护。

标题:Java加密的几种常见方法

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章