Что не так с этим кодом? - PullRequest
0 голосов
/ 23 марта 2012

Спасибо за помощь, помогите мне ... но все еще есть 2 проблемы после редактирования кода

import java.io.*;
import java.math.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class RCC4 {
    public RCC4(){} 

    public static void main(String[] args)throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException{
        String test = "testisperfect";
        System.out.println(RCC4.keyGet());
        byte b[] = RCC4.keyGet().getBytes();
        byte plain[] = test.getBytes();
        **byte c[] = RCC4.encrypt(plain,b);**
        **byte p[] = RCC4.decrypt(c,b);**

        **System.out.println(new String(c)) ;
        System.out.println(new String(p));**

    }
    public static byte[] encrypt(byte[] plaintext,byte[] keyBytes)
    {
        byte[] e = null;
        try
        {
            Key key = new SecretKeySpec(keyBytes,"RC4");
            Cipher enCipher = Cipher.getInstance("RC4");
            **enCipher.init(Cipher.ENCRYPT_MODE ,key);**
            e = enCipher.doFinal(plaintext);           
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        return e;
    }
    public static byte[] decrypt(byte[] ciphertext,byte[] keyBytes)
    {
        byte de[] = null;
        try
        {
           Key key = new SecretKeySpec(keyBytes,"RC4");
            Cipher deCipher = Cipher.getInstance("RC4");
           **deCipher.init(Cipher.DECRYPT_MODE, key);**
            de = deCipher.doFinal(ciphertext);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        } 
        return de;

    }

    public static Key getKey()
    {
        Key key = null;
        try
        {
            SecureRandom sr = new SecureRandom();
            KeyGenerator kg = KeyGenerator.getInstance("RC4");
            kg.init(128,sr);
            key = kg.generateKey(); 
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        return key;
    }
    public static String keyGet()
    {
        Key k = RCC4.getKey();
        byte[] b = k.getEncoded();
    BigInteger big = new BigInteger(b);
        String s = big.toString();
        return s;
    }

    }

Когда я нажимаю "Build file", он говорит, что процесс завершен, но при запуске файла появляется сообщение

112670544188765215715791498302542646231


java.security.InvalidKeyException: Illegal key size or default parameters
       at RCC4.encrypt(RCC4.java:37)
    at RCC4.main(RCC4.java:23)


java.security.InvalidKeyException: Illegal key size or default parameters
    at RCC4.decrypt(RCC4.java:53)
    at RCC4.main(RCC4.java:24)


Exception in thread "main" java.lang.NullPointerException
    at java.lang.String.<init>(String.java:479)
    at RCC4.main(RCC4.java:26)

Process completed.

Эти строки обозначены как *

Ответы [ 4 ]

3 голосов
/ 23 марта 2012

Ответ на оригинальный вопрос:

Key key = new SecretKeySpec(byte[]keyBytes,RC4);

должно быть

Key key = new SecretKeySpec(keyBytes, "RC4");

Также

deCipher.init(Cipher.WHATEVER, keyBytes);

должно быть

deCipher.init(Cipher.WHATEVER, key);

Затем он компилируется, однако все еще есть некоторые проблемы с логикой приложения.Это опять ваше дело:).

Ответ на новый вопрос:

Проблема заключалась в ненужном использовании SecretKeySpec.Где-то между getKey(), keyGet() всеми byte[] играми и SecretKeySpec что-то пошло не так.У меня не хватило терпения отследить его, поэтому я просто удалил его и сделал код несколько более читабельным, чтобы быть уверенным, что ничего не пропустил.Я думаю, вы все равно поймете это, так как это по-прежнему ваш код, и теперь он намного проще.

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

public class RCC4 {

    public static void main(String[] args) throws Exception {
        String plain = "testisperfect";
        Key key = RCC4.getKey();
        String encrypted = RCC4.encrypt(plain, key);
        String decrypted = RCC4.decrypt(encrypted, key);
        System.out.println(encrypted);
        System.out.println(decrypted);
    }

    private static String rc4(String plaintext, int mode, Key key) throws Exception {
        Cipher cipher = Cipher.getInstance("RC4");
        cipher.init(mode, key);
        return new String(cipher.doFinal(plaintext.getBytes()));
    }

    public static String encrypt(String plaintext, Key key) throws Exception {
        return rc4(plaintext, Cipher.ENCRYPT_MODE, key);
    }

    public static String decrypt(String ciphertext, Key key) throws Exception {
        return rc4(ciphertext, Cipher.DECRYPT_MODE, key);
    }

    public static Key getKey() throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance("RC4");
        SecureRandom sr = new SecureRandom();
        kg.init(128, sr);
        return kg.generateKey();
    }

}
2 голосов
/ 23 марта 2012

Вам нужен импорт SecretKeySpec, который находится под пакетом javax.crypto.spec.

1 голос
/ 23 марта 2012
package test;

import java.io.*;
import java.math.*;
import java.security.*;

import javax.crypto.*;
import javax.crypto.spec.*;

public class RCC4 {

    public RCC4() {
    }

    public static void main(String[] args) throws NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException, IOException {
        String test = "testisperfect";
        System.out.println(RCC4.keyGet());
        byte b[] = RCC4.keyGet().getBytes();
        byte plain[] = test.getBytes();
        byte c[] = RCC4.encrypt(plain, b);
        byte p[] = RCC4.decrypt(c, b);

        System.out.println(new String(c));
        System.out.println(new String(p));
    }

    public static byte[] encrypt(byte[] plaintext, byte[] keyBytes) {
        byte[] e = null;
        try {
            Key key = new SecretKeySpec(keyBytes, "RC4");
            Cipher enCipher = Cipher.getInstance("RC4");
            enCipher.init(Cipher.ENCRYPT_MODE, key);
            e = enCipher.doFinal(plaintext);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return e;
    }

    public static byte[] decrypt(byte[] ciphertext, byte[] keyBytes) {
        byte de[] = null;
        try {
            Key key = new SecretKeySpec(keyBytes, "RC4");
            Cipher deCipher = Cipher.getInstance("RC4");
            deCipher.init(Cipher.DECRYPT_MODE, RCC4.getKey());
            de = deCipher.doFinal(ciphertext);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return de;
    }

    public static Key getKey() {
        Key key = null;
        try {
            SecureRandom sr = new SecureRandom();
            KeyGenerator kg = KeyGenerator.getInstance("RC4");
            kg.init(128, sr);
            key = kg.generateKey();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return key;
    }

    public static String keyGet() {
        Key k = RCC4.getKey();
        byte[] b = k.getEncoded();
        BigInteger big = new BigInteger(b);
        String s = big.toString();
        return s;
    }
}
1 голос
/ 23 марта 2012

Вы неправильно вызываете метод, поскольку передаете тип параметра вместе с параметром.Типы параметров отображаются только тогда, когда объявляет метод, а не при вызове метода.

Другими словами, это не

Key key = new SecretKeySpec(byte[] keyBytes, RC4);

, а вместо этого

Key key = new SecretKeySpec(keyBytes, RC4);

Вам, конечно, потребуется объявить и инициализировать переменную keyBytes, прежде чем пытаться передать еев параметр этого метода.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...