English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Spiegazione dettagliata dei metodi di crittografia/sdecrittografia comuni in Java

Il problema della sicurezza è diventato un problema sempre più importante, come crittografare e decrittare i dati importanti in Java è il contenuto principale di questo articolo.

Primo: algoritmi di crittografia/descrittura comuni

1.Base64

In termini rigorosi, Base64 non è un algoritmo di crittografia/descrittura, ma un metodo di codifica. La codifica Base64 non genera una chiave, ma il testo crittografato codificato con Base64 può essere direttamente 'tradotto' in chiaro, ma è possibile ottenere un effetto di crittografia aggiungendo caratteri di confusione al testo chiaro.

2.DES

DES è un algoritmo simmetrico basato su una chiave di 56 bit, stabilito dal National Bureau of Standards (NBS) statunitense nel 1976 come standard federale per la elaborazione dei dati (FIPS), e successivamente reso noto a livello internazionale. Ora, DES non è più un algoritmo di crittografia sicuro, è stato decrittato pubblicamente e sostituito dallo standard di crittografia avanzata (AES).

3.3DES

3DES è una derivata dell'algoritmo DES, che migliora la sicurezza necessaria in alcuni casi di utilizzo del DES.

4.AES

AES è una delle algoritmi di crittografia simmetrica più popolari in uso oggi.

二、实现所需的一些库

为了实现上述的算法,我们可以实用JDK自带的实现,也可以使用一些开源的第三方库,例如Bouncy Castle(https://www.bouncycastle.org/)和comnons codec(https://commons.apache.org/proper/commons-codec/)。

三、具体实现

1.Base64

package com.tancky.security;
import java.io.IOException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Base64Demo {
 private static String src = "TestBase64";
 public static void main(String[] args) {
 Base64Demo.jdkBase64();
 Base64Demo.commonsCodecBase64 ();
 Base64Demo.bouncyCastleBase64 ();
 }
 //使用JDK的base64实现,
 public static void jdkBase64 (){
 BASE64Encoder encoder = new BASE64Encoder();
 String encode = encoder.encode(Base64Demo.src.getBytes());
 System.out.println("encode: " + encode);
 BASE64Decoder decoder = new BASE64Decoder();
 try {
  String decode = new String ( decoder.decodeBuffer(encode));
  System.out.println("decode: " + decode);
 } catch (IOException e) {
  e.printStackTrace();
 } 
 }
 //使用apache的commonsCodec实现
 public static void commonsCodecBase64 (){
 byte[] encodeBytes = org.apache.commons.codec.binary.Base64.encodeBase64(Base64Demo.src.getBytes());
 String encode = new String (encodeBytes);
 System.out.println("encode: " + encode);
 byte[] decodeBytes = org.apache.commons.codec.binary.Base64.decodeBase64(encode);
 String decode = new String(decodeBytes);
 System.out.println("decode: " + decode);
 }
 //使用bouncyCastlede实现
 public static void bouncyCastleBase64 () {
 byte[] encodeBytes = org.bouncycastle.util.encoders.Base64.encode(Base64Demo.src.getBytes()) ;
 String encode = new String (encodeBytes);
 System.out.println("encode: " + encode);
 byte[] decodeBytes = org.bouncycastle.util.encoders.Base64.decode(encode);
 String decode = new String(decodeBytes);
 System.out.println("decode: " + decode);
 }
}

2.DES

package com.tancky.security;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
public class DESDemo {
 private static String src = "TestDES";
 public static void jdkDES () {
 try {
  //生成密钥Key
  KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
  keyGenerator.init(56);
  SecretKey secretKey = keyGenerator.generateKey();
  byte[] bytesKey = secretKey.getEncoded();
  //KEY转换
  DESKeySpec deSedeKeySpec = new DESKeySpec(bytesKey);
  SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
  Key convertSecretKey = factory.generateSecret(deSedeKeySpec);
  //加密
  Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
  cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
  byte[] encodeResult = cipher.doFinal(DESDemo.src.getBytes());
  System.out.println("DESEncode :" + Hex.toHexString(encodeResult));
  // Decrittografia
  cipher.init(Cipher.DECRYPT_MODE,convertSecretKey);
  byte[] DecodeResult = cipher.doFinal(encodeResult);
  System.out.println("DESDncode :" + new String (DecodeResult));
 } catch (NoSuchAlgorithmException e) {
  e.printStackTrace();
 } catch (InvalidKeyException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (InvalidKeySpecException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (NoSuchPaddingException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (IllegalBlockSizeException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (BadPaddingException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 }
 }
 public static void bcDES (){
 try {
  //使用BouncyCastle 的DES加密
  Security.addProvider(new BouncyCastleProvider());
  //生成密钥Key
  KeyGenerator keyGenerator = KeyGenerator.getInstance("DES","BC");
  keyGenerator.init(56);
  SecretKey secretKey = keyGenerator.generateKey();
  byte[] bytesKey = secretKey.getEncoded();
  //KEY转换
  DESKeySpec deSedeKeySpec = new DESKeySpec(bytesKey);
  SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
  Key convertSecretKey = factory.generateSecret(deSedeKeySpec);
  //加密
  Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
  cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
  byte[] encodeResult = cipher.doFinal(DESDemo.src.getBytes());
  System.out.println("DESEncode :" + Hex.toHexString(encodeResult));
  // Decrittografia
  cipher.init(Cipher.DECRYPT_MODE,convertSecretKey);
  byte[] DecodeResult = cipher.doFinal(encodeResult);
  System.out.println("DESDncode :" + new String (DecodeResult));
 } catch (NoSuchAlgorithmException e) {
  e.printStackTrace();
 } catch (InvalidKeyException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (InvalidKeySpecException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (NoSuchPaddingException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (IllegalBlockSizeException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (BadPaddingException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (NoSuchProviderException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 }
 }
 public static void main(String[] args) {
 DESDemo.jdkDES ();
 DESDemo.bcDES();
 }
}

3.3DES

package com.tancky.security;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
public class TripleDESDemo {
 private static String src = "TestTripleDES";
 public static void jdkTripleDES () {
 try {
  //生成密钥Key
  KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
  keyGenerator.init(168);
  SecretKey secretKey = keyGenerator.generateKey();
  byte[] bytesKey = secretKey.getEncoded();
  //KEY转换
  DESedeKeySpec deSedeKeySpec = new DESedeKeySpec(bytesKey);
  SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
  Key convertSecretKey = factory.generateSecret(deSedeKeySpec);
  //加密
  Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
  cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
  byte[] encodeResult = cipher.doFinal(TripleDESDemo.src.getBytes());
  System.out.println("TripleDESEncode :" + Hex.toHexString(encodeResult));
  // Decrittografia
  cipher.init(Cipher.DECRYPT_MODE,convertSecretKey);
  byte[] DecodeResult = cipher.doFinal(encodeResult);
  System.out.println("TripleDESDncode :" + new String (DecodeResult));
 } catch (NoSuchAlgorithmException e) {
  e.printStackTrace();
 } catch (InvalidKeyException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (InvalidKeySpecException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (NoSuchPaddingException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (IllegalBlockSizeException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (BadPaddingException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 }
 }
public static void bcTripleDES () {
 try {
  Security.addProvider(new BouncyCastleProvider());
  //生成密钥Key
  KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede","BC");
  keyGenerator.getProvider();
  keyGenerator.init(168);
  SecretKey secretKey = keyGenerator.generateKey();
  byte[] bytesKey = secretKey.getEncoded();
  //KEY转换
  DESedeKeySpec deSedeKeySpec = new DESedeKeySpec(bytesKey);
  SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
  Key convertSecretKey = factory.generateSecret(deSedeKeySpec);
  //加密
  Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
  cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
  byte[] encodeResult = cipher.doFinal(TripleDESDemo.src.getBytes());
  System.out.println("TripleDESEncode :" + Hex.toHexString(encodeResult));
  // Decrittografia
  cipher.init(Cipher.DECRYPT_MODE,convertSecretKey);
  byte[] DecodeResult = cipher.doFinal(encodeResult);
  System.out.println("TripleDESDncode :" + new String (DecodeResult));
 } catch (NoSuchAlgorithmException e) {
  e.printStackTrace();
 } catch (InvalidKeyException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (InvalidKeySpecException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (NoSuchPaddingException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (IllegalBlockSizeException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (BadPaddingException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (NoSuchProviderException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 }
 }
 public static void main(String[] args) {
 jdkTripleDES ();
 bcTripleDES ();
 }
}

4.AES

package com.tancky.security;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
public class AESDemo {
 private static String src = "TestAES";
 public static void jdkAES (){
 try {
  //生成Key
  KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
  keyGenerator.init(128); 
  //keyGenerator.init(128, new SecureRandom("seedseedseed".getBytes())); 
  //使用上面这种初始化方法可以特定种子来生成密钥,这样加密后的密文是唯一固定的。
  SecretKey secretKey = keyGenerator.generateKey();
  byte[] keyBytes = secretKey.getEncoded();
  //Key转换
  Key key = new SecretKeySpec(keyBytes, "AES");
  //加密
  Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
  cipher.init(Cipher.ENCRYPT_MODE, key);
  byte[] encodeResult = cipher.doFinal(AESDemo.src.getBytes());
  System.out.println("AESencode : " + Hex.toHexString(encodeResult) );
  // Decrittografia
  cipher.init(Cipher.DECRYPT_MODE, key);
  byte[] decodeResult = cipher.doFinal(encodeResult);
  System.out.println("AESdecode : " + new String (decodeResult));
 } catch (NoSuchAlgorithmException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (NoSuchPaddingException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (InvalidKeyException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (IllegalBlockSizeException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (BadPaddingException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 }
 }
 public static void bcAES (){
 try {
  //使用BouncyCastle 的DES加密
  Security.addProvider(new BouncyCastleProvider());
  //生成Key
  KeyGenerator keyGenerator = KeyGenerator.getInstance("AES","BC");
  keyGenerator.getProvider();
  keyGenerator.init(128); 
  SecretKey secretKey = keyGenerator.generateKey();
  byte[] keyBytes = secretKey.getEncoded();
  //Key转换
  Key key = new SecretKeySpec(keyBytes, "AES");
  //加密
  Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
  cipher.init(Cipher.ENCRYPT_MODE, key);
  byte[] encodeResult = cipher.doFinal(AESDemo.src.getBytes());
  System.out.println("AESencode : " + Hex.toHexString(encodeResult) );
  // Decrittografia
  cipher.init(Cipher.DECRYPT_MODE, key);
  byte[] decodeResult = cipher.doFinal(encodeResult);
  System.out.println("AESdecode : " + new String (decodeResult));
 } catch (NoSuchAlgorithmException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (NoSuchPaddingException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (InvalidKeyException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (IllegalBlockSizeException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (BadPaddingException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 } catch (NoSuchProviderException e) {
  // TODO blocco catch generato automaticamente
  e.printStackTrace();
 }
 }
 public static void main(String[] args) {
 jdkAES();
 bcAES();
 }
}

Questo è tutto il contenuto dell'articolo, speriamo che il contenuto di questo articolo possa essere di aiuto per il tuo studio o lavoro, e speriamo di ricevere più supporto per il tutorial URL!

Dichiarazione: il contenuto di questo articolo è stato tratto da Internet, il diritto d'autore spetta al proprietario originale, il contenuto è stato contribuito e caricato autonomamente dagli utenti di Internet, questo sito non detiene i diritti di proprietà, non è stato sottoposto a modifica manuale e non assume alcuna responsabilità legale correlata. Se trovi contenuti sospetti di violazione del copyright, ti preghiamo di inviare una e-mail a: notice#oldtoolbag.com (al momento dell'invio dell'e-mail, sostituisci # con @) per segnalare il problema e fornire prove pertinenti. Una volta verificata, questo sito rimuoverà immediatamente il contenuto sospetto di violazione del copyright.

Ti potrebbe interessare