使用RSA_Decrypted 3DES KEY解密纯文本时错误的密钥大小异常

时间:2018-05-08 05:41:01

标签: exception key rsa 3des

我正在尝试实现一个混合密码系统:

  1. 使用3DES加密文本并使用RSA加密算法生成3DES密钥
  2. 解密RSA加密的3DES密钥,然后用它来解密密文以获取加密的明文
  3. 它抛出了一个例外:

      

    无效的密钥大小异常

    如何修复代码?

    import java.security.Key;
    import java.security.InvalidKeyException;
    import java.security.spec.InvalidKeySpecException;
    import java.security.NoSuchAlgorithmException;
    import java.util.Scanner;
    import java.math.BigInteger;
    import java.security.SecureRandom;
    import java.util.Arrays;
    import java.util.Random;
    
    import javax.crypto.Cipher;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESedeKeySpec;
    import javax.crypto.BadPaddingException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    
    import java.io.UnsupportedEncodingException;
    import java.security.GeneralSecurityException;
    import java.security.InvalidKeyException;
    import java.security.KeyFactory;
    import java.security.KeyPair;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    
    
    import org.apache.commons.codec.binary.Base64;
    import java.security.KeyPairGenerator;
    import java.security.NoSuchProviderException;
    import java.security.spec.InvalidKeySpecException;
    
    public class Hybrid_Implementation_V2 {
    
    //3DES_Encryption Algorithm Required Variables
    private byte[] DES_Key;
    private SecretKeyFactory keyfactory;
    private DESedeKeySpec spec;
    private Key deskey;
    private int DES_Key_Length;
    private byte[] data;
    private Cipher cipher;
    private String CipherText;
    private byte [] CIPHERText;
    
    //RSA
    private KeyPairGenerator keyGen;
    private KeyPair pair;
    private PrivateKey privateKey;
    private PublicKey publicKey;
    private final Cipher RSA_cipher;
    
    Hybrid_Implementation_V2() throws InvalidKeyException, 
    NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException
    {
        this.keyGen = KeyPairGenerator.getInstance("RSA");
        this.keyGen.initialize(1024);
        this.RSA_cipher = Cipher.getInstance("RSA");
        DES_Key_Generator();
        RSA_Key_Generation();
    }
    
                    //KEY Generation Mechanism
    //3DES Key Generation
    private void DES_Key_Generator() throws InvalidKeyException, 
    NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException
    {
        Random rnd = new Random();
        String key = rnd.toString();
    
        DES_Key = key.getBytes();
        spec = new DESedeKeySpec(DES_Key);
        keyfactory = SecretKeyFactory.getInstance("desede");
        deskey = keyfactory.generateSecret(spec);
        cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
    }
    
    //RSA Public - Private Key Generation
    private void RSA_create_Key()
    {
        this.pair = this.keyGen.generateKeyPair();
        this.privateKey = pair.getPrivate();
    this.publicKey = pair.getPublic();
    }
    
    public PrivateKey getPrivateKey() 
        {
        return this.privateKey;
    }
    
    public PublicKey getPublicKey() 
        {
        return this.publicKey;
    }
    
        public void RSA_Key_Generation(){RSA_create_Key();}
    
    
    
    // https://docs.oracle.com/javase/8/docs/api/java/security/spec/PKCS8EncodedKeySpec.html
    
    public PrivateKey getPrivate() throws NoSuchAlgorithmException, 
    InvalidKeySpecException
        {
        byte[] keyBytes = getPrivateKey().getEncoded();
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(spec);
    }
    
    // https://docs.oracle.com/javase/8/docs/api/java/security/spec/X509EncodedKeySpec.html
    public PublicKey getPublic() throws NoSuchAlgorithmException, 
    InvalidKeySpecException
        {
        byte[] keyBytes = getPublicKey().getEncoded();
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePublic(spec);
    }
        public String RSA_encryptText(String msg) throws 
    NoSuchAlgorithmException, NoSuchPaddingException, 
    UnsupportedEncodingException, IllegalBlockSizeException, 
    BadPaddingException, InvalidKeyException, InvalidKeySpecException {
     PrivateKey key = getPrivate(); 
            this.RSA_cipher.init(Cipher.ENCRYPT_MODE, key);
        return Base64.encodeBase64String(RSA_cipher.doFinal(msg.getBytes("UTF-8")));
    }
    
    public String RSA_decryptText(String msg)throws InvalidKeyException, 
    UnsupportedEncodingException, IllegalBlockSizeException, 
    BadPaddingException, NoSuchAlgorithmException, InvalidKeySpecException {
        PublicKey key = getPublic();
            this.RSA_cipher.init(Cipher.DECRYPT_MODE, key);
        return new String(RSA_cipher.doFinal(Base64.decodeBase64(msg)), "UTF-8");
    }
                  //Hybrid Encryption Mechanism
    //Encryption Function Caller
    private String encryption(String plaintext) throws InvalidKeyException, 
    IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, 
    NoSuchPaddingException, UnsupportedEncodingException, 
    InvalidKeySpecException
    {
        String cipher_text = DES_Encryption(plaintext);
        String RSA_DESKey = RSA_encryptText(DES_Key.toString());
        DES_Key_Length = RSA_DESKey.length();
        CipherText ="";
        CipherText = new 
    StringBuilder().append(RSA_DESKey).append(cipher_text).toString();
        return CipherText;
    }
    
    //3DES Encryption
     private String DES_Encryption(String plaintext) throws InvalidKeyException, 
    IllegalBlockSizeException, BadPaddingException
    {
        data = plaintext.getBytes();
        cipher.init(Cipher.ENCRYPT_MODE, deskey);
        CIPHERText = cipher.doFinal(data);
        StringBuilder hexCiphertext = new StringBuilder();
        for(int i=0; i<CIPHERText.length; i++)
        {
            int v = CIPHERText[i] & 0xff;
            v+=0x100;
            String temp = Integer.toString(v,16);
            hexCiphertext.append(temp).substring(1);
        }
        return hexCiphertext.toString();
    }
    
                       //Hybrid Decryption Mechanism
     //Decryption Function Caller
     private String decryption(String encrypted_text) throws 
    InvalidKeyException, InvalidKeySpecException, IllegalBlockSizeException, 
    BadPaddingException, UnsupportedEncodingException, NoSuchAlgorithmException, 
    NoSuchPaddingException
    {
        StringBuilder encryptedkey = new StringBuilder();
        StringBuilder cipheredtext = new StringBuilder();
        for(int i = 0 ; i < DES_Key_Length; i++)    //Extraction of Encrypted 
    3DES Key
            encryptedkey.append (encrypted_text.charAt(i));
        for(int j = DES_Key_Length ; j< encrypted_text.length() ; j++)      
    //Extraction of Ciphered Text
            cipheredtext.append (encrypted_text.charAt(j));
        String temp = RSA_decryptText(encryptedkey.toString());
        byte [] DES_KEY = temp.getBytes();
        String plaintext = 
    DES_Decryption(DES_KEY,cipheredtext.toString().getBytes());
           return plaintext;
    }
    
    
     //3DES Decryption
    private String DES_Decryption(byte [] key, byte [] encrypted_text) throws 
    InvalidKeyException, IllegalBlockSizeException, BadPaddingException, 
    InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException
    {
    
        Key deskey;
        DESedeKeySpec spec = new DESedeKeySpec(key);
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE,deskey);
        byte[] plaintext = cipher.doFinal(encrypted_text);
        StringBuilder decrypttext= new StringBuilder();
        for (int i = 0; i < plaintext.length; i++)
            decrypttext.append((char) plaintext[i]);
        return decrypttext.toString();
    }
    
    /**
     * @param args the command line arguments
     * @throws java.security.InvalidKeyException
     * @throws java.security.NoSuchAlgorithmException
     * @throws java.security.spec.InvalidKeySpecException
     * @throws javax.crypto.NoSuchPaddingException
     * @throws javax.crypto.IllegalBlockSizeException
     * @throws javax.crypto.BadPaddingException
     */
    public static void main(String[] args) throws InvalidKeyException, 
    NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, 
    IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException 
    {
    
        String plaintext;
        Hybrid_Implementation_V2 hi = new Hybrid_Implementation_V2 ();
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter Text = ");
        plaintext = sc.nextLine();
        String encrypted_text = hi.encryption(plaintext);
        String decrypted_text = hi.decryption(encrypted_text);
        System.out.println("Plain Text Entered = "+plaintext);
        System.out.println("Encrypted Text = "+encrypted_text);
        System.out.println("Decrypted Text = "+decrypted_text);
    
    }
    
    }
    

0 个答案:

没有答案