在本文中,我们向您展示如何使用Java Cryptography Extension (JCE)
通过数据加密标准(DES)机制来加密或解密文本。
1. DES密钥
创建一个DES密钥。
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();
2.密码信息
从Cipher类创建一个Cipher实例,指定以下信息并用斜杠(/)分隔。
- 算法名称
- 模式(可选)
- 填充方案(可选)
Cipher desCipher;
// Create the cipher
desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
注意
DES =数据加密标准。
ECB =电子密码本模式。
PKCS5Padding = PKCS#5样式的填充。
在这种情况下,您以PKCS#5样式填充在Electronic Codebook模式下创建了DES(数据加密标准)密码。
3.转换
将String转换为Byte []数组格式。
byte[] text = "No body can see me".getBytes();
4.加密
使Cipher处于加密模式,并使用Cipher.doFinal()
方法Cipher.doFinal()
进行加密。
desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
byte[] textEncrypted = desCipher.doFinal(text);
5.解密
使Cipher处于解密模式,并使用Cipher.doFinal()
方法对其进行解密。
desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
byte[] textDecrypted = desCipher.doFinal(textEncrypted);
6.完整的例子
完整示例展示了如何使用Java的JCE在DES机制中对文本进行加密和解密。
package com.mkyong.util;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class JEncrytion
{
public static void main(String[] argv) {
try{
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();
Cipher desCipher;
// Create the cipher
desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
// Initialize the cipher for encryption
desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
//sensitive information
byte[] text = "No body can see me".getBytes();
System.out.println("Text [Byte Format] : " + text);
System.out.println("Text : " + new String(text));
// Encrypt the text
byte[] textEncrypted = desCipher.doFinal(text);
System.out.println("Text Encryted : " + textEncrypted);
// Initialize the same cipher for decryption
desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
// Decrypt the text
byte[] textDecrypted = desCipher.doFinal(textEncrypted);
System.out.println("Text Decryted : " + new String(textDecrypted));
}catch(NoSuchAlgorithmException e){
e.printStackTrace();
}catch(NoSuchPaddingException e){
e.printStackTrace();
}catch(InvalidKeyException e){
e.printStackTrace();
}catch(IllegalBlockSizeException e){
e.printStackTrace();
}catch(BadPaddingException e){
e.printStackTrace();
}
}
}
输出量
Text [Byte Format] : [B@19b5393
Text : No body can see me
Text Encryted : [B@4e79f1
Text Decryted : No body can see me
参考
翻译自: https://mkyong.com/java/jce-encryption-data-encryption-standard-des-tutorial/