Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> cryptography 
:(
    Опции темы
Alone
Дата 30.7.2003, 14:31 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 663
Регистрация: 11.5.2003
Где: Dnepropetrovsk, U A

Репутация: 3
Всего: 6



Народ, подскажите способ криптования сообщения на явеconfused.gif


--------------------
web developer/telecommunication specialist.
mailto: [email protected]
ICQ#28442924

PM MAIL WWW ICQ   Вверх
DarkDS
Дата 30.7.2003, 14:33 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник Клуба
Сообщений: 748
Регистрация: 6.5.2003
Где: Таллинн, Эстония

Репутация: 11
Всего: 16



Сообщений куда? smile.gif
PM MAIL   Вверх
DarkDS
Дата 30.7.2003, 14:39 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник Клуба
Сообщений: 748
Регистрация: 6.5.2003
Где: Таллинн, Эстония

Репутация: 11
Всего: 16



Вообще то если использовать SunJCE то можно использовать DES и MD5 алгоритмы...

На англицком небольшое объяснение...
http://java.sun.com/j2se/1.4.2/docs/guide/...CEProvider.html

Если мало... то могу попробовать достать другой пример... правда он на старой работе лежал sad.gif

Это сообщение отредактировал(а) DarkDS - 30.7.2003, 15:44
PM MAIL   Вверх
DarkDS
Дата 30.7.2003, 14:59 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник Клуба
Сообщений: 748
Регистрация: 6.5.2003
Где: Таллинн, Эстония

Репутация: 11
Всего: 16



Примера найти не удалось... Может вечером напишу небольшой код, как домой приду... Но сам JCE (Java Cryptography Extension) нашел:
http://www.cryptix.org/products/jce/index.html

Это сообщение отредактировал(а) DarkDS - 30.7.2003, 15:44
PM MAIL   Вверх
B2_Russia
Дата 30.7.2003, 15:26 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


В доску свой :)
**


Профиль
Группа: Участник
Сообщений: 344
Регистрация: 3.7.2003
Где: Тверь

Репутация: нет
Всего: 1



На яве не программировал, но способы кодирования реализовывал.
Могу программки дать по кодированию перестановкой, кодир-ие Виженера, смещением.
Не ахти какие, но есть(на Делфи)
PM WWW ICQ   Вверх
DarkDS
Дата 30.7.2003, 15:41 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник Клуба
Сообщений: 748
Регистрация: 6.5.2003
Где: Таллинн, Эстония

Репутация: 11
Всего: 16



Краткий обзор всех JCE:
http://www.nue.et-inf.uni-siegen.de/SignSt...w_provider.html
PM MAIL   Вверх
Alone
Дата 31.7.2003, 11:12 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 663
Регистрация: 11.5.2003
Где: Dnepropetrovsk, U A

Репутация: 3
Всего: 6



to DarkDS
Просто "аттлична!" пошел разбираться.
DES-a фатит с головой...
Пасиб!

Это сообщение отредактировал(а) Alone - 31.7.2003, 11:13


--------------------
web developer/telecommunication specialist.
mailto: [email protected]
ICQ#28442924

PM MAIL WWW ICQ   Вверх
DarkDS
Дата 31.7.2003, 12:15 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник Клуба
Сообщений: 748
Регистрация: 6.5.2003
Где: Таллинн, Эстония

Репутация: 11
Всего: 16



Alone
Кстати я б постоветовал Криптикс посмотреть (http://www.cryptix.org/products/jce/index.html) - он вроде бы был один из... smile.gif
PM MAIL   Вверх
olegrolik
Дата 20.7.2007, 15:23 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 309
Регистрация: 25.1.2006

Репутация: нет
Всего: нет



Что-то не получается создать тему, напишу тут:
Код

package cryptix.openpgp.examples;


import cryptix.message.EncryptedMessage;
import cryptix.message.KeyBundleMessage;
import cryptix.message.LiteralMessage;
import cryptix.message.Message;
import cryptix.message.MessageException;
import cryptix.message.MessageFactory;
import cryptix.message.NotEncryptedToParameterException;
import cryptix.message.SignedMessage;

import cryptix.pki.KeyBundle;
import cryptix.pki.KeyBundleException;

import java.io.FileInputStream;
import java.io.IOException;

import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;

import java.util.Collection;


/**
 * Detailed example for decrypting and verifying a message. It understands 
 * signed-only, encrypted-only and encrypted-and-signed messages.
 *
 * Assumes that the GenerateAndWriteKey and EncryptAndSign examples has been 
 * run, although it also understands the output of the Encrypt and ClearSign
 * examples.
 *
 * @author  Edwin Woudt <[email protected]>
 * @version $Revision: 1.2 $
 */
public class Decrypt {


    //**************************************************************************
    // Main method, will be run on startup.
    //**************************************************************************
    public static void main(String[] args) {
    
        //**********************************************************************
        // Dynamically register both the Cryptix JCE and Cryptix OpenPGP 
        // providers. 
        //**********************************************************************
        java.security.Security.addProvider(
            new cryptix.jce.provider.CryptixCrypto() );
        java.security.Security.addProvider(
            new cryptix.openpgp.provider.CryptixOpenPGP() );


        //**********************************************************************
        // First read the keys. 
        //**********************************************************************
        KeyBundle secretBob   = null;
        KeyBundle publicAlice = null;
        MessageFactory mf     = null;
        
        try {

            FileInputStream in; Collection msgs; KeyBundleMessage kbm;
            
            mf = MessageFactory.getInstance("OpenPGP");

            in = new FileInputStream("c:/pgp/secring.skr");
            msgs = mf.generateMessages(in);
            kbm = (KeyBundleMessage)msgs.iterator().next();
            secretBob = kbm.getKeyBundle();
            in.close();
        
            in = new FileInputStream("c:/pgp/pubring_new.pkr");
            msgs = mf.generateMessages(in);
            kbm = (KeyBundleMessage)msgs.iterator().next();
            publicAlice = kbm.getKeyBundle();
            in.close();
        
        } catch (IOException ioe) {
            System.err.println("IOException... You did remember to run the "+
                "GenerateAndWriteKey example first, right?");
            ioe.printStackTrace();
            System.exit(-1);
        } catch (NoSuchAlgorithmException nsae) {
            System.err.println("Cannot find the OpenPGP MessageFactory. "+
                "This usually means that the Cryptix OpenPGP provider is not "+
                "installed correctly.");
            nsae.printStackTrace();
            System.exit(-1);
        } catch (MessageException me) {
            System.err.println("Reading keybundle failed.");
            me.printStackTrace();
            System.exit(-1);
        }


        //**********************************************************************
        //  Read the message.
        //**********************************************************************
        Message msg = null;
        
        try {

            FileInputStream in = new FileInputStream("c:/123.txt.asc");

            Collection msgs = mf.generateMessages(in);
            msg = (Message)msgs.iterator().next();

            in.close();
        
        } catch (IOException ioe) {
            System.err.println("IOException... You did remember to run the "+
                "Encrypt example first, right?");
            ioe.printStackTrace();
            System.exit(-1);
        } catch (MessageException me) {
            System.err.println("Reading message failed.");
            me.printStackTrace();
            System.exit(-1);
        }
        

        //**********************************************************************
        // Decrypt the message (if encrypted).
        //**********************************************************************
        try {

            if (msg instanceof EncryptedMessage) {

                msg = ((EncryptedMessage)msg).decrypt(secretBob, 
                                            "123".toCharArray());
                       
                System.out.println("Message has been decrypted.");

            } else {
            
                System.out.println("Message is not encrypted.");

            }
        
        } catch (NotEncryptedToParameterException netpe) {
            System.err.println("Not encrypted to this key.");
            netpe.printStackTrace();
            System.exit(-1);
        } catch (UnrecoverableKeyException uke) {
            System.err.println("Invalid passphrase.");
            uke.printStackTrace();
            System.exit(-1);
        } catch (MessageException me) {
            System.err.println("Decrypting message failed.");
            me.printStackTrace();
            System.exit(-1);
        }
        

        //**********************************************************************
        // Verify the signature (if signed).
        //**********************************************************************
        try {
        
            if (msg instanceof SignedMessage) {

                if (((SignedMessage)msg).verify(publicAlice)) {
                    System.out.println("Signature OK.");
                } else {
                    System.out.println("Signature BAD!");
                }

                msg = ((SignedMessage)msg).getContents();

            } else {

                System.out.println("Message is not signed.");

            }
        
        } catch (MessageException me) {
            System.err.println("Verifying the signature failed.");
            me.printStackTrace();
            System.exit(-1);
        }


        //**********************************************************************
        // Show the original message
        //**********************************************************************

        try {
        
            if (msg instanceof LiteralMessage) {

                System.out.println("Original message: ");
                System.out.println(((LiteralMessage)msg).getTextData());

            } else {
            
                System.out.println("Original message is not a literal message");
                System.out.println(msg);

            }

        } catch (MessageException me) {
            System.err.println("Retrieving the original message failed.");
            me.printStackTrace();
            System.exit(-1);
        }

    }
    
}


Данный код дешифрует файл 123.txt.asc. 
При запуске возникает ошибка:
Код

Exception in thread "main" java.lang.RuntimeException: NYI
        at cryptix.jce.provider.elgamal.ElGamalCipher.engineGetParameters(ElGamalCipher.java:120)
        at javax.crypto.Cipher.a(DashoA12275)
        at javax.crypto.Cipher.init(DashoA12275)
        at javax.crypto.Cipher.init(DashoA12275)
        at cryptix.openpgp.algorithm.PGPElGamal.decrypt(PGPElGamal.java:612)
        at cryptix.openpgp.packet.PGPPublicKeyEncryptedSessionKeyPacket.decrypt(PGPPublicKeyEncryptedSessionKeyPacket.java:189)
        at cryptix.openpgp.provider.PGPEncryptedMessageImpl.decrypt(PGPEncryptedMessageImpl.java:186)
        at cryptix.openpgp.provider.PGPEncryptedMessageImpl.decrypt(PGPEncryptedMessageImpl.java:315)
        at cryptix.openpgp.examples.Decrypt.main(Decrypt.java:130)
Java Result: 1


Ошибка возникает на месте - 
Код


msg = ((EncryptedMessage)msg).decrypt(secretBob, 
                                            "123".toCharArray());

Т.е. на непосредственной расшифроке.
Подскажите, как решить проблему?
Спасибо.

Это сообщение отредактировал(а) olegrolik - 20.7.2007, 15:26
PM MAIL   Вверх
olegrolik
Дата 23.7.2007, 10:34 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 309
Регистрация: 25.1.2006

Репутация: нет
Всего: нет



Если использовать зашифровку файла, то результат такой же! 

Код


import cryptix.message.EncryptedMessageBuilder;
import cryptix.message.KeyBundleMessage;
import cryptix.message.LiteralMessage;
import cryptix.message.LiteralMessageBuilder;
import cryptix.message.Message;
import cryptix.message.MessageException;
import cryptix.message.MessageFactory;

import cryptix.openpgp.PGPArmouredMessage;

import cryptix.pki.KeyBundle;
import cryptix.pki.KeyBundleException;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import java.security.NoSuchAlgorithmException;

import java.util.Collection;



/**
 * Detailed example for encrypting a message.
 * This example assumes that the GenerateAndWriteKey example has been run first.
 *
 * @author  Edwin Woudt <[email protected]>
 * @version $Revision: 1.2 $
 */
public class Encrypt {

    public static void main (String[] args) {

        //**********************************************************************
        // Dynamically register both the Cryptix JCE and Cryptix OpenPGP 
        // providers. 
        //**********************************************************************
        java.security.Security.addProvider(
            new cryptix.jce.provider.CryptixCrypto() );
        java.security.Security.addProvider(
            new cryptix.openpgp.provider.CryptixOpenPGP() );
            
        
        //**********************************************************************
        // First read the key. 
        //**********************************************************************
        KeyBundle bundle = null;
        
        try {

            FileInputStream in = new FileInputStream("c:/bob-public.pgp.asc");

            MessageFactory mf = MessageFactory.getInstance("OpenPGP");
            Collection msgs = mf.generateMessages(in);
            
            KeyBundleMessage kbm = (KeyBundleMessage)msgs.iterator().next();
            
            bundle = kbm.getKeyBundle();

            in.close();
        
        } catch (IOException ioe) {
            System.err.println("IOException... You did remember to run the "+
                "GenerateAndWriteKey example first, right?");
            ioe.printStackTrace();
            System.exit(-1);
        } catch (NoSuchAlgorithmException nsae) {
            System.err.println("Cannot find the OpenPGP MessageFactory. "+
                "This usually means that the Cryptix OpenPGP provider is not "+
                "installed correctly.");
            nsae.printStackTrace();
            System.exit(-1);
        } catch (MessageException me) {
            System.err.println("Reading keybundle failed.");
            me.printStackTrace();
            System.exit(-1);
        }


        //**********************************************************************
        //  Build the literal message.
        //**********************************************************************
        LiteralMessage litmsg = null;
        try {
            String msg = "This is a test message.\n" +
                         "This is another line.\n";
            LiteralMessageBuilder lmb = 
                LiteralMessageBuilder.getInstance("OpenPGP");
            lmb.init(msg);
            litmsg = (LiteralMessage)lmb.build();
        } catch (NoSuchAlgorithmException nsae) {
            System.err.println("Cannot find the OpenPGP LiteralMessageBuilder."+
                " This usually means that the Cryptix OpenPGP provider is not "+
                "installed correctly.");
            nsae.printStackTrace();
            System.exit(-1);
        } catch (MessageException me) {
            System.err.println("Creating the literal message failed.");
            me.printStackTrace();
            System.exit(-1);
        }
        

        //**********************************************************************
        // Encrypt the message.
        //**********************************************************************
        Message msg = null;
        try {
            
            EncryptedMessageBuilder emb = 
                EncryptedMessageBuilder.getInstance("OpenPGP");
            emb.init(litmsg);
            emb.addRecipient(bundle);
            msg = emb.build();
        
        } catch (NoSuchAlgorithmException nsae) {
            System.err.println("Cannot find the OpenPGP "+
                "EncryptedMessageBuilder. "+
                "This usually means that the Cryptix OpenPGP provider is not "+
                "installed correctly.");
            nsae.printStackTrace();
            System.exit(-1);
        } catch (MessageException me) {
            System.err.println("Creating the encrypted message failed.");
            me.printStackTrace();
            System.exit(-1);
        }
        

        //**********************************************************************
        // Armour the message and write it to disk
        //**********************************************************************
        try {
            
            PGPArmouredMessage armoured;
        
            armoured = new PGPArmouredMessage(msg);
            FileOutputStream out = new FileOutputStream("c:/encrypted-to-bob.asc");
            out.write(armoured.getEncoded());
            out.close();
        
        } catch (MessageException me) {
            System.err.println("Writing the encrypted message failed.");
            me.printStackTrace();
            System.exit(-1);
        } catch (IOException ioe) {
            System.err.println("Writing the encrypted message failed.");
            ioe.printStackTrace();
            System.exit(-1);
        }
        
    }

}


Оба примера были предоставлены вместе с библиотекой cryptix.
Наверняка кто-нибудь сталкивался с этим!? smile 
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   tux
javastic
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux, javastic.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.2180 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.