Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java: Общие вопросы > Криптография, проблемс


Автор: yezh 15.4.2006, 10:59
При шифровании файла алгоритмом RSA компилятор не находит класс com.sun.net.ssl.internal.ssl.JSA_RSAPublicKey. Среда IntelliJ Idea 5. В нете на sun.com ничего не нашел ((. Мож кто подскажет где взять этот класс?

Автор: LSD 15.4.2006, 11:25
Вообще то, для шифрования он и не нужен. Приведи свой код.

Автор: yezh 15.4.2006, 11:54
Код

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
/*Пример использования алгоритма шифрования RSA
java RSATest -genkey public privatte
java RSATest -encrypt plaintext encrypted public
java RSAText -decrypt encrypted decrypted private*/
public class RSATest
{
public static void main(String[] args)
{
    try
    {
        if(args[0].equals("-genkey"))
        {
            KeyPairGenerator pairgen=KeyPairGenerator.getInstance("RSA");
            SecureRandom random=new SecureRandom();
            pairgen.initialize(KEYSIZE, random);
            KeyPair keyPair=pairgen.generateKeyPair();
            ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(args[1]));
            out.writeObject(keyPair.getPublic());
            out.close();
            out=new ObjectOutputStream(new FileOutputStream(args[2]));
            out.writeObject(keyPair.getPrivate());
            out.close();
        }
        else
        if(args[0].equals("-encrypt"))
        {
            Security.addProvider(new BouncyCastleProvider());
            KeyGenerator keygen=KeyGenerator.getInstance("DES");
            SecureRandom random=new SecureRandom();
            keygen.init(random);
            SecretKey key=keygen.generateKey();
            //Свертывание с помощью открытого ключа RSA
            ObjectInputStream keyIn=new ObjectInputStream(new FileInputStream(args[3]));
            Key publicKey=(Key) keyIn.readObject();
            keyIn.close();

            Cipher cipher=Cipher.getInstance("RSA","BC");
            cipher.init(Cipher.WRAP_MODE,publicKey);
            byte[] wrappedKey=cipher.wrap(key);
            DataOutputStream out=new DataOutputStream(new FileOutputStream(args[2]));
            out.writeInt(wrappedKey.length);
            out.write(wrappedKey);

            InputStream in=new FileInputStream(args[1]);
            cipher=Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE,key);
            crypt(in,out,cipher);
            in.close();
            out.close();
         }
            else
            {
                DataInputStream in=new DataInputStream(new FileInputStream(args[1]));
                int length=in.readInt();
                byte[] wrappedKey=new byte[length];
                in.read(wrappedKey,0,length);

                //Развертывание с помщью открытого ключа RSA
                ObjectInputStream keyIn=new ObjectInputStream(new FileInputStream(args[3]));
                Key privateKey=(Key) keyIn.readObject();
                keyIn.close();

                Cipher cipher=Cipher.getInstance("RSA","BC");
                cipher.init(Cipher.UNWRAP_MODE,privateKey);
                Key key=cipher.unwrap(wrappedKey,"DES",Cipher.SECRET_KEY);
                OutputStream out=new FileOutputStream(args[2]);
                cipher=Cipher.getInstance("DES","BC");
                cipher.init(Cipher.DECRYPT_MODE,key);
                crypt(in,out,cipher);
                in.close();
                out.close();
            }
    }
            catch(IOException exception)
            {
                exception.printStackTrace();
            }
            catch(GeneralSecurityException exception)
            {
                exception.printStackTrace();
            }
            catch(ClassNotFoundException exception)
            {
                exception.printStackTrace();
            }
        }

        public static void crypt(InputStream in,OutputStream out,Cipher cipher) throws IOException, GeneralSecurityException
        {
            int blockSize=cipher.getBlockSize();
            int outputSize=cipher.getOutputSize(blockSize);
            byte[] inBytes=new byte[blockSize];
            byte[] outBytes=new byte[outputSize];

            int inLength=0;
            boolean more=true;
            while(more)
            {
                inLength=in.read(inBytes);
                if(inLength==blockSize)
                {
                    int outLength=cipher.update(inBytes,0,blockSize,outBytes);
                    out.write(outBytes,0,outLength);
                }
                else more=false;
            }
            if(inLength>0)
                outBytes=cipher.doFinal(inBytes,0,inLength);
            else
                outBytes=cipher.doFinal();
            out.write(outBytes);
          }
            public static final int KEYSIZE=512;
}



Взято из книжки

Автор: LSD 15.4.2006, 12:08
Вот так все работает:
Код
import javax.crypto.*;
import java.io.*;
import java.security.*;

public class RSATest
{
  public static final int KEYSIZE = 512;

  public static void main(String[] args)
  {
    try
    {
      if(args[0].equals("-genkey"))
      {
        KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = new SecureRandom();
        pairgen.initialize(KEYSIZE, random);
        KeyPair keyPair = pairgen.generateKeyPair();
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1]));
        out.writeObject(keyPair.getPublic());
        out.close();
        out = new ObjectOutputStream(new FileOutputStream(args[2]));
        out.writeObject(keyPair.getPrivate());
        out.close();
      }
      else if(args[0].equals("-encrypt"))
      {
        KeyGenerator keygen = KeyGenerator.getInstance("DES");
        SecureRandom random = new SecureRandom();
        keygen.init(random);
        SecretKey key = keygen.generateKey();
        //Свертывание с помощью открытого ключа RSA
        ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
        Key publicKey = (Key) keyIn.readObject();
        keyIn.close();
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.WRAP_MODE, publicKey);
        byte[] wrappedKey = cipher.wrap(key);
        DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2]));
        out.writeInt(wrappedKey.length);
        out.write(wrappedKey);
        InputStream in = new FileInputStream(args[1]);
        cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        crypt(in, out, cipher);
        in.close();
        out.close();
      }
      else
      {
        DataInputStream in = new DataInputStream(new FileInputStream(args[1]));
        int length = in.readInt();
        byte[] wrappedKey = new byte[length];
        in.read(wrappedKey, 0, length);
        //Развертывание с помщью открытого ключа RSA
        ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
        Key privateKey = (Key) keyIn.readObject();
        keyIn.close();
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.UNWRAP_MODE, privateKey);
        Key key = cipher.unwrap(wrappedKey, "DES", Cipher.SECRET_KEY);
        OutputStream out = new FileOutputStream(args[2]);
        cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        crypt(in, out, cipher);
        in.close();
        out.close();
      }
    }
    catch(Exception ex)
    {
      ex.printStackTrace();
    }
  }

  public static void crypt(InputStream in, OutputStream out, Cipher cipher) throws IOException, GeneralSecurityException
  {
    int blockSize = cipher.getBlockSize();
    int outputSize = cipher.getOutputSize(blockSize);
    byte[] inBytes = new byte[blockSize];
    byte[] outBytes = new byte[outputSize];
    int inLength = 0;
    boolean more = true;
    while(more)
    {
      inLength = in.read(inBytes);
      if(inLength == blockSize)
      {
        int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
        out.write(outBytes, 0, outLength);
      }
      else
        more = false;
    }
    if(inLength > 0)
      outBytes = cipher.doFinal(inBytes, 0, inLength);
    else
      outBytes = cipher.doFinal();
    out.write(outBytes);
  }
}

Автор: garm 15.4.2006, 12:53
Цитата(LSD @ 15.4.2006, 16:08 Найти цитируемый пост)
Вот так все работает:

А у меня не работает, ключи генерятся нормально, а при попытке шифрования выдаёт:
Код

java.security.NoSuchAlgorithmException: Cannot find any provider supporting RSA
        at javax.crypto.Cipher.getInstance(DashoA6275)
        at RSATest.main(RSATest.java:34)

Может дело в том, что у меня java всё ещё 1.4?

yezh, а вот твой код работает, только нужно в тот блок, где происходит дешифрование, в самое начало, добавить:
Код

Security.addProvider(new BouncyCastleProvider());

Автор: LSD 15.4.2006, 14:48
Цитата(garm @ 15.4.2006, 13:53 Найти цитируемый пост)
Может дело в том, что у меня java всё ещё 1.4?

Действительно в 1.4, не работает. Правда не совсем понимаю почему.

Автор: garm 15.4.2006, 16:12
Цитата(LSD @ 15.4.2006, 18:48 Найти цитируемый пост)
Правда не совсем понимаю почему.

Если верить официальной документации, то это новая фишка 1.5.
http://java.sun.com/j2se/1.5.0/docs/guide/security/CryptoSpec.html#WhatsNew

Автор: LSD 15.4.2006, 16:41
Странно, зачем тогда нужен генератор ключей, если алгоритм не доступен. Возможно он есть в JCE.

Автор: garm 15.4.2006, 19:10
Цитата(LSD @ 15.4.2006, 20:41 Найти цитируемый пост)
Странно, зачем тогда нужен генератор ключей, если алгоритм не доступен.

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

Цитата(LSD @ 15.4.2006, 20:41 Найти цитируемый пост)
Возможно он есть в JCE.

Мне казалось, что начиная с какой-то версии JCE является частью SDK, нет?
Или есть ещё какая-то JCE?

Автор: powerOn 15.4.2006, 22:03
Взгляните вот на эту штуку http://www.ntua.gr/cryptix/products/jce/
Она считается неплохой альтернативой Sun-скому JCE

Автор: LSD 16.4.2006, 12:30
Цитата(garm @  15.4.2006,  20:10 Найти цитируемый пост)
Мне казалось, что начиная с какой-то версии JCE является частью SDK, нет?

Да, начиная с версии 1.4 она является частью JDK.

Значит для ранних JDK надо использовать сторонние пакеты. 

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)