0

我想使用 JCE API 使用 DES 算法加密和解密文件和字符串,并且我想提供自己的密钥,但是当我寻找示例时,我发现密钥是这样生成的:

    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();
                    String key = "zertyuio";
            Cipher desCipher;

            // Create the cipher 
            desCipher = Cipher.getInstance("DES");

            // 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();
        } 

    }
}

你有什么主意吗

先感谢您

4

2 回答 2

3

看看课堂javax.crypto.spec.SecretKeySpec。它允许您使用保存密钥的字节数组。

然后可以将实例Cipher.init作为键传递给方法。

于 2012-12-31T09:20:43.537 回答
2

对于 DES,您可以从DESKeySpec创建您的密钥:

SecretKey myDesKey =
    SecretKeyFactory.getInstance("DES").generateSecret(new DESKeyspec(key.getBytes()));
于 2012-12-31T09:31:24.620 回答