生成DES密钥并使用密码进行加密

时间:2017-05-18 12:32:03

标签: java cryptography

我想了解java的密码学,我找到了 these幻灯片在互联网上。在第9页,我找到了一个例子,我试图使用它。但是,以下代码未编译。哪里出错了?

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class Gen_DESAES_key{


byte[] message = "Hello World".getBytes();

KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey desKey = keygenerator.generateKey();

Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
desCipher.init(Cipher.ENCRYPT_MODE,deskey);

byte[] encryptedMessage = desCipher.doFinal(message);
}

2 个答案:

答案 0 :(得分:4)

修复#1:修复变量名称

Java中的变量名称为case-sensitive。您的变量名称为desKey,而不是deskey

修复#2:将代码包装到方法中并处理异常

除此之外,您必须将代码包装到方法中,如下所示:

import javax.crypto.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class Gen_DESAES_key {

    public static void main(String[] args) throws NoSuchAlgorithmException,
                                                  NoSuchPaddingException,
                                                  BadPaddingException,
                                                  IllegalBlockSizeException,
                                                  InvalidKeyException {

        byte[] message = "Hello World".getBytes();

        KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
        SecretKey desKey = keygenerator.generateKey();

        Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        desCipher.init(Cipher.ENCRYPT_MODE, desKey);

        byte[] encryptedMessage = desCipher.doFinal(message);
        System.out.println(new String(encryptedMessage));
    }
}

请注意,您的代码会引发一系列异常,这些异常必须由try - catch块处理或在方法的throws子句中声明。有关更多详细信息,请参阅documentation

奖金#1:使用Base64

为了避免在显示加密邮件时出现一些奇怪的字符,您可以使用Base64对其进行编码。如果您使用的是Java 8或更高版本,则可以使用java.util.Base64

System.out.println(Base64.getEncoder().encodeToString(encryp‌​tedMessage));

奖金#2:解密你的消息

要解密加密邮件,请使用:

desCipher.init(Cipher.DECRYPT_MODE, desKey);
byte[] decryptedMessage = desCipher.doFinal(encryptedMessage);

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

答案 1 :(得分:3)

您忘了编写方法,并且变量名中存在拼写错误:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class Gen_DESAES_key{

    public static void main(String[] args) {
        byte[] message = "Hello World".getBytes();

        KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
        SecretKey desKey = keygenerator.generateKey();

        Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        desCipher.init(Cipher.ENCRYPT_MODE,desKey);

        byte[] encryptedMessage = desCipher.doFinal(message);
    }
}