<?xml version='1.0' encoding="utf-8"?>
      <rss version='2.0'>
      <channel>
      <title>Форум на Исходниках.RU</title>
      <link>https://forum.sources.ru</link>
      <description>Форум на Исходниках.RU</description>
      <generator>Форум на Исходниках.RU</generator>
  	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=2274467</guid>
        <pubDate>Mon, 25 May 2009 13:24:04 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=2274467</link>
        <description><![CDATA[dark_barker: Не, ну можно, конечно, при переписке двух конкретных людей пользоваться открытым-закрытым ключом с любой стороны, для шифрования/дешифрования это непринципиально. Вы тут путаете шифрование и цифровую подпись, где закрытым подписывают, а публичным - &quot;проверяют&quot;]]></description>
        <author>dark_barker</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=2274083</guid>
        <pubDate>Mon, 25 May 2009 06:19:02 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=2274083</link>
        <description><![CDATA[Большой Синий Кит: :) Кажется, тема о ключах уже поднималась на этом форуме, и именно в J2SE :) Кто-то тоже утверждал, что приватный ключ открыт получателю. Закончилось, кажется, тем, что этот кто-то оказался неправ.]]></description>
        <author>Большой Синий Кит</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=2273378</guid>
        <pubDate>Sun, 24 May 2009 03:45:06 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=2273378</link>
        <description><![CDATA[nauris.nikos: <strong class='tag-b'>wind</strong> У меня твой пример кода не расшифровывает сообщение.<br>
 бяка какая то  получается. <br>
в чем трабла?<br>
очень надо. :wacko:]]></description>
        <author>nauris.nikos</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1818505</guid>
        <pubDate>Thu, 27 Dec 2007 02:49:43 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1818505</link>
        <description><![CDATA[wind: <div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=216642&view=findpost&p=1818341'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>igorka &#064; <time class="tag-quote__quoted-time" datetime="2007-12-26T20:55:10+00:00">26.12.07, 20:55</time></span><div class='quote '>Ассиметричные методы имеют свои недостатки, это оочень маленькая скорость шифрования и оочень большой размеш зашифрованых сообщений.</div></div><br>
Есть ещё один недостаток - криптостойкость тем ниже, чем больше блоков, размер которых сравним с размером ключа в сообщении. Это вторая причина, по которым использовать RSA для шифрования данных не рекомендуют.<br>
<br>
По примерам.<br>
<br>
Во-первых, оба иллюстрируют один и тот же механизм, просто в одном из них вместо данных используется хэш. Во-вторых, пример с обменом данными в защищённом канале, мягко говоря, далёк от действительности. В-третьих, вы просто повторили мои слова с точностью до наоборот (насчёт того, какой ключ для чего используется). <br>
<br>
Наверняка вы не так давно получили свои представления из какого-то источника (ведь явно какую-то учебную задачу выполняете). Не могли бы вы дать хоть какую-либо информацию о нём?]]></description>
        <author>wind</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1818341</guid>
        <pubDate>Wed, 26 Dec 2007 20:55:10 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1818341</link>
        <description><![CDATA[igorka: В данном случае RSA используется не для цифровой подписи, а для шифрования. (У RSA как минимум два назначения, исторически первое из них - шифрование).<br>
Самым большим недостатком симметричных систем шифрования была необходимость закрытого канала для передачи СЕКРЕТНОГО ключа.<br>
Ассиметричные системы избавлены от этого недостатка:<br>
<br>
-На сторона ПОЛУЧАТЕЛЯ генерируется пара ключей.<br>
-ЗАКРЫТЫЙ ключ используется для расшифрования и никогда никуда не передается, все остается на стороне ПОЛУЧАТЕЛЯ<br>
-ОТКРЫТЫЙ ключе используется для шифрования сообщений, и открыто публикуется<br>
-ОТПРАВИТЕЛЬ имея только ОТКРЫТЫЙ ключ шифрует сообщение и отправляет ПОЛУЧАТЕЛЮ<br>
-сообщение можно расшифровать ТОЛЬКО ЗАКРЫТЫМ ключом, поэтому никто кроме ПОЛУЧАТЕЛЯ на может его расшифровать<br>
   (помниет, ЗАКРЫТЫЙ ключ остался у ПОЛУЧАТЕЛЯ и никуда не передавался)<br>
-ПОЛУЧАТЕЛЬ расшифровывает сообщение имея свой уникальный ЗАКРЫТЫЙ ключ :)<br>
Вскрыть сообщение по ходу передачи невозможно, канал для передачи ЗАКРЫТОГО ключа не трубуется. Волки целы, овцы сыты.<br>
<br>
Ассиметричные методы имеют свои недостатки, это оочень маленькая скорость шифрования и оочень большой размеш зашифрованых сообщений.<br>
Поэтому используются так званые комбинированые системы шифрования: сообщение шифруется симетричным методом (DES, ГОСТ, и т.д.) а ключ<br>
шифруется ассиметричным методом, тем же RSA.<br>
<br>
Я пишу программулину для шифрования сообщения алгоритмом RSA.<br>
<br>
Второе применение RSA - это цифровая подпись. Основано на ХЭШ функция и взаимозаменяемости ключей в RSA.<br>
-ОТПРАВИТЕЛЬ берет ХЭШ сообщения и фишрует его RSA используя ОТКРЫТЫЙ ключ(можно использовать и ЗАКРЫТЫЙ, они полностью взаимозаменяемы)<br>
-ОТПРАВИТЕЛЬ отправляет сообщение с прекрепленной подписью [ЗАШИФРОВАНЫЙ ХЭШ + ЗАКРЫТЫЙ КЛЮЧ]<br>
-ПОЛУЧАТЕЛЬ расшифровывает ЗАШИФРОВАНЫЙ ХЭШ с помощью ЗАКРЫТОГО КЛЮЧА, получает ХЭШ переданного сообщения, сравнивает расшифрованый и полученый ХЭШи,<br>
   если они совпали - подпись верна, не совпали - не верна.<br>
<br>
Вот вроде, все.<br>
<br>
Я уже почти закончил свою программулину, но вот не могу одалеть этот баг. Если интересно, могу выложить исходный код класса и ГУИ, допишем вместе.<br>
Там еще нужны доработки интерфейса и немного оптимизации, о оптимизировал шифрование, очень сильно затормозив расшифрование:(, ну и конешно баг пофиксить:)<br>
Прога работает с ключами до 8096 - теоретически можно и больше, но кому это надо?]]></description>
        <author>igorka</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1818258</guid>
        <pubDate>Wed, 26 Dec 2007 19:39:57 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1818258</link>
        <description><![CDATA[wind: <div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=216642&view=findpost&p=1818235'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>igorka &#064; <time class="tag-quote__quoted-time" datetime="2007-12-26T19:22:27+00:00">26.12.07, 19:22</time></span><div class='quote '>Если поможете мне с моей проблемкой, и я немного освобожусь, то освежу ваши<br>
знания по защите информации. Все правильно учили, терминология была таже что и сейчас,<br>
просто вы немного запутались.</div></div><br>
Освежите, если вас не затруднит. Также особенно - какой смысл вообще во всём этом предприятии, если закрытый ключ прилагается к сообщению.]]></description>
        <author>wind</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1818235</guid>
        <pubDate>Wed, 26 Dec 2007 19:22:27 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1818235</link>
        <description><![CDATA[igorka: <strong class='tag-b'>wind</strong><br>
<strong class='tag-b'>batigoal</strong><br>
Сейчас немного нехватает времени, чтобы обьяснить схему ассимитричных алгоритмов.<br>
Если поможете мне с моей проблемкой, и я немного освобожусь, то освежу ваши<br>
знания по защите информации. Все правильно учили, терминология была таже что и сейчас,<br>
просто вы немного запутались.]]></description>
        <author>igorka</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1818231</guid>
        <pubDate>Wed, 26 Dec 2007 19:18:24 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1818231</link>
        <description><![CDATA[batigoal: Действительно, википедийные статьи утверждают, что получателю передаётся закрытый ключ (причем и англоязычные тоже). Но я, вроде как, на лекциях по компьютерной безопасности не совсем штаны просиживал, и там терминология была иной. Либо это просто терминологическая путаница, либо нас конкретно штырит.]]></description>
        <author>batigoal</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1818205</guid>
        <pubDate>Wed, 26 Dec 2007 19:00:13 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1818205</link>
        <description><![CDATA[wind: <div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=216642&view=findpost&p=1818190'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>igorka &#064; <time class="tag-quote__quoted-time" datetime="2007-12-26T18:47:26+00:00">26.12.07, 18:47</time></span><div class='quote '>Советую почитать, и не говорить глупостей.</div></div><br>
Если честно, мне лень сейчас искать вам документальные опровержения (статья в википедии не является достоверным документом). Но ещё раз повторяю - публикация приватного ключа - нонсенс. Он используется только при создании шифрованного сообщения.]]></description>
        <author>wind</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1818190</guid>
        <pubDate>Wed, 26 Dec 2007 18:47:26 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1818190</link>
        <description><![CDATA[igorka: <strong class='tag-b'>wind</strong><br>
<strong class='tag-b'>batigoal</strong><br>
http://ru.wikipedia.org/wiki/RSA<br>
Советую почитать, и не говорить глупостей.]]></description>
        <author>igorka</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1817314</guid>
        <pubDate>Wed, 26 Dec 2007 07:05:20 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1817314</link>
        <description><![CDATA[batigoal: <div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=216642&view=findpost&p=1817162'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>igorka &#064; <time class="tag-quote__quoted-time" datetime="2007-12-25T22:23:30+00:00">25.12.07, 22:23</time></span><div class='quote '>У отправителя находится только ОТКРЫТЫЙ ключ</div></div><br>
в чем же тогда его &quot;открытость&quot;?  :blink: Он потому и открытый, что публикуется для получателей. А &quot;закрытый&quot; - потому что он доступен только отправителю.]]></description>
        <author>batigoal</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1817223</guid>
        <pubDate>Wed, 26 Dec 2007 04:24:23 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1817223</link>
        <description><![CDATA[wind: <div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=216642&view=findpost&p=1817162'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>igorka &#064; <time class="tag-quote__quoted-time" datetime="2007-12-25T22:23:30+00:00">25.12.07, 22:23</time></span><div class='quote '>У отправителя находится только ОТКРЫТЫЙ ключ, он им шифрует сообщение и передает получателю.<br>
Получатель расшифровывает сообщения использую ЗАКРЫТЫЙ ключ.</div></div><br>
Нет, <strong class='tag-b'>igorka</strong>, это вас кто-то обманул. Подумайте о смысле и главном предназначении асимметричного шифрования - это цифровая подпись. Расшифровать (проверить) может любой получатель сообщения - для этого используется открытый (публичный) ключ. Но зашифровать (создать, подделать) можно только с помощью закрытого (приватного) ключа. Закрытый ключ всегда остаётся у поставщика сообщения (потому и закрытый), открытый прилагается к сообщению. <br>
<br>
<div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=216642&view=findpost&p=1817162'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>igorka &#064; <time class="tag-quote__quoted-time" datetime="2007-12-25T22:23:30+00:00">25.12.07, 22:23</time></span><div class='quote '>А если надо иметь на входе в encrypt и на выходе с decrypt массив байт, а не строку? Строка используется лишь для хранения зашифрованых файлов.</div></div><br>
Что-то подсказывает мне, что такому развитию событий ничто не мешает :) Просто вы теряете целостность данных где-то по дороге, преобразовывая строку в числа методами, для этого не особо предназначенными :)]]></description>
        <author>wind</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1817162</guid>
        <pubDate>Tue, 25 Dec 2007 22:23:30 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1817162</link>
        <description><![CDATA[igorka: [<strong class='tag-b'>wind</strong><br>
<span class='tag-size' data-value='11' style='font-size:11pt;'><br>
<em class='tag-i'>Шифруем публичным, расшифровываем приватным&#33; Это основа ассимитричных методов шифрования.<br>
У отправителя находится только ОТКРЫТЫЙ ключ, он им шифрует сообщение и передает получателю.<br>
Получатель расшифровывает сообщения использую ЗАКРЫТЫЙ ключ. Предварительно получатель генерирует<br>
пару ключей и передает открытый ключ отправителю. Такая схема не нуждается в защищенном канале<br>
для передачи ЗАКРЫТОГО ключа</em></span> <br>
<br>
<span class="tag-color tag-color-named" data-value="gray" style="color: gray"><span class='tag-size' data-value='7' style='font-size:7pt;'>Добавлено <time class="tag-mergetime" datetime="2007-12-25T22:38:09+00:00">25.12.07, 22:38</time></span></span><br>
А если надо иметь на входе в encrypt  и на выходе с decrypt массив байт, а не строку? Строка используется лишь для хранения зашифрованых файлов.]]></description>
        <author>igorka</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1816997</guid>
        <pubDate>Tue, 25 Dec 2007 17:52:07 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1816997</link>
        <description><![CDATA[wind: Вообще-то, приватный ключ используется для шифрования, а публичный - для расшифровки, а не наоборот. Ещё меня сильно смущают ваши преобразования строк в числа. Вот так всё замечательно работает:<br>
<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">String encryptString(String string) {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;StringBuilder encryptedStringBuilder = new StringBuilder();</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;for (int i = 0, count = string.length(); i &#60; count; i++) {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;BigInteger digit = BigInteger.valueOf(</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;string.charAt(i)</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;encryptedStringBuilder.append(</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;digit.modPow(privateKey, modulus).toString(RADIX)</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;encryptedStringBuilder.append(&quot;,&quot;);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return encryptedStringBuilder.toString();</div><div class="code_line">&nbsp;&nbsp; &nbsp;}</div><div class="code_line">&nbsp;&nbsp; &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;String decryptString(String string) {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;StringBuilder decryptedStringBuilder = new StringBuilder();</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;for (String block : string.split(&quot;,&quot;)) {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;decryptedStringBuilder.append(</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(char) new BigInteger(block, RADIX).modPow(publicKey, modulus).intValue()</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return decryptedStringBuilder.toString();</div><div class="code_line">&nbsp;&nbsp; &nbsp;}</div></ol></div></div></div></div><script>preloadCodeButtons('1');</script>]]></description>
        <author>wind</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1814469</guid>
        <pubDate>Mon, 24 Dec 2007 01:41:29 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1814469</link>
        <description><![CDATA[igorka: Хм, нашелся баг: если в тестовое приложение в качестве параметра указать русские буквы - то неправильно расшифровует.<br> :wall:  ниче нипанимаю<br>основное приложение так же шифрует и расшифровывает только файлы содержащие латиницу, а хочется не зависить от содержания файла.<br>Хелп ми а5&#33;]]></description>
        <author>igorka</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1814445</guid>
        <pubDate>Mon, 24 Dec 2007 00:07:47 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1814445</link>
        <description><![CDATA[wind: <div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=216642&view=findpost&p=1814443'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>igorka &#064; <time class="tag-quote__quoted-time" datetime="2007-12-23T23:57:13+00:00">23.12.07, 23:57</time></span><div class='quote '>Спасибо, что помогли, ну или попытались.</div></div><br>
Честно делали вид :) А что, собственно, было не так, вкратце?<br>
<br>
<div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=216642&view=findpost&p=1814443'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>igorka &#064; <time class="tag-quote__quoted-time" datetime="2007-12-23T23:57:13+00:00">23.12.07, 23:57</time></span><div class='quote '>Еще интересует вопрос по быстродействию, оптимальней будет брать блоки по два байта(или по одному?) как делал я, или <br>
брать блоки размером (РАЗМЕР_КЛЮЧА - 1), что будет быстрее?</div></div><br>
Поверхностно - больший размер блока -&gt; более быстрая обработка. Но на самом деле всё зависит от реализации арифметики в BigInteger, нужно тестировать.]]></description>
        <author>wind</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1814443</guid>
        <pubDate>Sun, 23 Dec 2007 23:57:13 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1814443</link>
        <description><![CDATA[igorka: Спасибо, что помогли, ну или попытались. Вот что у меня получилось, может кто будет страдать <span class="tag-color tag-color-named" data-value="red" style="color: red">подобным</span> и ему пригодится.<br>
Канешна недостатков много, еще дорабатывать и дорабатывать, поэтому выслушаю все рекомендации.<br>
Тестировал ключи вплоть до 8192 - полет нормальный.<br>
<br>
Еще интересует вопрос по быстродействию, оптимальней будет брать блоки по два байта(или по одному?) как делал я, или <br>
брать блоки размером (РАЗМЕР_КЛЮЧА - 1), что будет быстрее?<br>
<br>
<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">import java.math.BigInteger;</div><div class="code_line">import java.security.SecureRandom;</div><div class="code_line">import java.io.ByteArrayOutputStream;</div><div class="code_line">&nbsp;</div><div class="code_line">public class RSA {</div><div class="code_line">&nbsp;&nbsp; private final static BigInteger one &nbsp; &nbsp; &nbsp;= new BigInteger(&quot;1&quot;);</div><div class="code_line">&nbsp;&nbsp; private final static SecureRandom random = new SecureRandom();</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; private BigInteger privateKey;</div><div class="code_line">&nbsp;&nbsp; private BigInteger publicKey;</div><div class="code_line">&nbsp;&nbsp; private BigInteger modulus;</div><div class="code_line">&nbsp;&nbsp; private final static int N = 64;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; // generate an N-bit (roughly) public and private key</div><div class="code_line">&nbsp;&nbsp; RSA() {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;BigInteger p;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;BigInteger q;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;BigInteger e;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;BigInteger d;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;do{ </div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;p = BigInteger.probablePrime(N/2, random);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;System.out.println(&quot;p = &quot; + p);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;q = BigInteger.probablePrime(N/2, random);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;System.out.println(&quot;q = &quot; + q);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;}</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;while(p == q);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;BigInteger phi = (p.subtract(one)).multiply(q.subtract(one));</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;System.out.println(&quot;phi = &quot; + phi);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;modulus &nbsp; &nbsp;= p.multiply(q); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;System.out.println(&quot;mod = &quot; + modulus);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;e = new BigInteger(&quot;3&quot;);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; while(phi.gcd(e).intValue() &#62; 1) e = e.add(new BigInteger(&quot;2&quot;));</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;d = e.modInverse(phi);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;System.out.println(&quot;e = &quot; + e);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;System.out.println(&quot;d = &quot; + d);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;publicKey = e;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;privateKey = d;</div><div class="code_line">&nbsp;&nbsp; }</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; String encrypt(byte [] message) throws Exception {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;int blockSize = 2;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;byte[] block = new byte[blockSize];</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;System.out.println(&quot;message length &nbsp;= &quot; + message.length );</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;StringBuffer sb = new StringBuffer();</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;ByteArrayOutputStream mes = new ByteArrayOutputStream();</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;for(int i = 0; i &#60; message.length; i+=blockSize){</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(message.length == (i+1)){</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;blockSize--;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;block = new byte[blockSize];</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(&quot;block decrement!&quot;);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.arraycopy(message, i, block, 0, blockSize);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;byte [] tmp = new BigInteger(block).modPow(publicKey, modulus).toByteArray();</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;mes.write(tmp);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sb.append(new BigInteger(tmp).toString(16)).append(&quot;\n&quot;); &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return sb.toString(); &nbsp; &nbsp; &nbsp; </div><div class="code_line">&nbsp;&nbsp; &nbsp;}</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; String decrypt(String encrypted) throws Exception {</div><div class="code_line">&nbsp;&nbsp; System.out.println(&quot;N length &nbsp; = &quot; + modulus.bitLength()/8); </div><div class="code_line">&nbsp;&nbsp; System.out.println(&quot;encrypted len &nbsp; = &quot; + encrypted.length());</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;BigInteger block;</div><div class="code_line">&nbsp;&nbsp; ByteArrayOutputStream mes = new ByteArrayOutputStream();</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;int i = 0;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;int j = 0;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;while(i &#60; (encrypted.length()-1)){</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; i++;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if(encrypted.charAt(i) == &#39;\n&#39;){</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;block = new BigInteger(encrypted.substring(j, i), 16);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;mes.write(block.modPow(privateKey, modulus).toByteArray());</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;System.out.println(&quot;block = &quot; + encrypted.substring(j, i) + &quot;end&quot; );</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;j = i+1;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; return mes.toString();</div><div class="code_line">&nbsp;&nbsp; }</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; public String toString() {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;String s = &quot;&quot;;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;s += &quot;public &nbsp;= &quot; + publicKey &nbsp;+ &quot;\n&quot;;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;s += &quot;private = &quot; + privateKey + &quot;\n&quot;;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;s += &quot;modulus = &quot; + modulus;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;return s;</div><div class="code_line">&nbsp;&nbsp; }</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; public static void main(String[] args) {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;RSA key = new RSA();</div><div class="code_line">&nbsp;&nbsp; &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;byte[] bytes = args[0].getBytes();</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;BigInteger message = new BigInteger(bytes);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;try{</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;System.out.println(&quot;message &nbsp; = &quot; + message);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;String encrypt = key.encrypt(bytes);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;System.out.println(&quot;encrpyted = &quot; + encrypt);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;String decrypt = key.decrypt(encrypt);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;System.out.println(&quot;decrypted = &quot; + decrypt);</div><div class="code_line">&nbsp;&nbsp; &nbsp;}</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;catch(Exception e) {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;System.out.println(&quot;Exception&quot; );</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;e.printStackTrace();</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;};</div><div class="code_line">&nbsp;&nbsp; }</div><div class="code_line">}</div></ol></div></div></div></div>]]></description>
        <author>igorka</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1813725</guid>
        <pubDate>Sun, 23 Dec 2007 00:15:08 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1813725</link>
        <description><![CDATA[igorka: <div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">import java.math.BigInteger;</div><div class="code_line">import java.security.SecureRandom;</div><div class="code_line">import java.io.ByteArrayOutputStream;</div><div class="code_line">&nbsp;</div><div class="code_line">public class RSA {</div><div class="code_line">&nbsp;&nbsp; private final static BigInteger one &nbsp; &nbsp; &nbsp;= new BigInteger(&quot;1&quot;);</div><div class="code_line">&nbsp;&nbsp; private final static SecureRandom random = new SecureRandom();</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; private BigInteger privateKey;</div><div class="code_line">&nbsp;&nbsp; private BigInteger publicKey;</div><div class="code_line">&nbsp;&nbsp; private BigInteger modulus;</div><div class="code_line">&nbsp;&nbsp; private final static int N = 64;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; // generate an N-bit (roughly) public and private key</div><div class="code_line">&nbsp;&nbsp; RSA() {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;BigInteger p;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;BigInteger q;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;BigInteger e;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;BigInteger d;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;do{ </div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;p = BigInteger.probablePrime(N/2, random);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;System.out.println(&quot;p = &quot; + p);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;q = BigInteger.probablePrime(N/2, random);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;System.out.println(&quot;q = &quot; + q);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;}</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;while(p == q);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;BigInteger phi = (p.subtract(one)).multiply(q.subtract(one));</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;System.out.println(&quot;phi = &quot; + phi);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;modulus &nbsp; &nbsp;= p.multiply(q); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;System.out.println(&quot;mod = &quot; + modulus);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;//publicKey &nbsp;= new BigInteger(&quot;65537&quot;); &nbsp; &nbsp; // common value in practice = 2^16 + 1</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;//privateKey = publicKey.modInverse(phi);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;e = new BigInteger(&quot;3&quot;);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; while(phi.gcd(e).intValue() &#62; 1) e = e.add(new BigInteger(&quot;2&quot;));</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;d = e.modInverse(phi);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;System.out.println(&quot;e = &quot; + e);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;System.out.println(&quot;d = &quot; + d);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;publicKey = e;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;privateKey = d;</div><div class="code_line">&nbsp;&nbsp; }</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; BigInteger encrypt(byte [] message) throws Exception {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;byte[] block = new byte[2];</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;ByteArrayOutputStream mes = new ByteArrayOutputStream();</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;for(int i = 0; i &#60; message.length; i+=2){</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.arraycopy(message, i, block, 0, 2);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;byte [] tmp = new BigInteger(block).modPow(publicKey, modulus).toByteArray();</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(tmp.length % 8 != 0) &nbsp;{</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(&quot;Dow! length = &quot; + tmp.length);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} </div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;mes.write(tmp); &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp; &nbsp; </div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return new BigInteger(mes.toByteArray());</div><div class="code_line">&nbsp;&nbsp; &nbsp;}</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; BigInteger decrypt(byte [] encrypted) throws Exception {</div><div class="code_line">&nbsp;&nbsp; System.out.println(&quot;N length &nbsp; = &quot; + modulus.bitLength()/8); </div><div class="code_line">&nbsp;&nbsp; System.out.println(&quot;encrypted len &nbsp; = &quot; + encrypted.length); </div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;byte[] block = new byte[modulus.bitLength()/8];</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;ByteArrayOutputStream mes = new ByteArrayOutputStream();</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;for(int i = 0; i &#60; encrypted.length; i+=modulus.bitLength()/8){</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.arraycopy(encrypted, i, block, 0, modulus.bitLength()/8);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;mes.write(new BigInteger(block).modPow(privateKey, modulus).toByteArray()); &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp; &nbsp; </div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;return new BigInteger(mes.toByteArray());</div><div class="code_line">&nbsp;&nbsp; }</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; public String toString() {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;String s = &quot;&quot;;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;s += &quot;public &nbsp;= &quot; + publicKey &nbsp;+ &quot;\n&quot;;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;s += &quot;private = &quot; + privateKey + &quot;\n&quot;;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;s += &quot;modulus = &quot; + modulus;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;return s;</div><div class="code_line">&nbsp;&nbsp; }</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; public static void main(String[] args) {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;//int N = Integer.parseInt(args[0]);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;RSA key = new RSA();</div><div class="code_line">&nbsp;&nbsp; &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;// create random message, encrypt and decrypt</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;//BigInteger message = new BigInteger(N-1, random);</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;//// create message by converting string to integer</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;// String s = &quot;test&quot;;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;byte[] bytes = args[0].getBytes();</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;BigInteger message = new BigInteger(bytes);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;try{</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;System.out.println(&quot;message &nbsp; = &quot; + message);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;BigInteger encrypt = key.encrypt(message.toByteArray());</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;System.out.println(&quot;encrpyted = &quot; + encrypt);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;BigInteger decrypt = key.decrypt(encrypt.toByteArray());</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;System.out.println(&quot;decrypted = &quot; + decrypt);</div><div class="code_line">&nbsp;&nbsp; &nbsp;}</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;catch(Exception e) {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;System.out.println(&quot;Exception&quot; );</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;e.printStackTrace();</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;};</div><div class="code_line">&nbsp;&nbsp; }</div><div class="code_line">}</div></ol></div></div></div></div><br>
<br>
Сделаем вот так. В качестве параметра передаем четное кол-во символов. <br>
Кодирует нормально, а вот декодирует не всегда.  :wall: я уже ничего не могу понять, <br>
может проблема где-то рядом, но что-то никак не могу разобратся. Повториете запуск<br>
програмы с одними и теми же параметрами несколько раз. <br>
<br>
<br>
Вот что получается у меня... где трабля вылазит?]]></description>
        <author>igorka</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1813714</guid>
        <pubDate>Sat, 22 Dec 2007 23:37:04 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1813714</link>
        <description><![CDATA[wind: <div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=216642&view=findpost&p=1813709'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>igorka &#064; <time class="tag-quote__quoted-time" datetime="2007-12-22T23:21:16+00:00">22.12.07, 23:21</time></span><div class='quote '>Тоесть при всех вызовах modPow() разрядность должна оставатся одна и таже и зависеть от modulus.</div></div><br>
Нет. При неизменном modulus число разрядов результата зависит от исходного числа. Вы уверены в содержимом message и modulus?]]></description>
        <author>wind</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1813709</guid>
        <pubDate>Sat, 22 Dec 2007 23:21:16 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1813709</link>
        <description><![CDATA[igorka: <strong class='tag-b'>wind</strong><br>
Вот именно. Но разве разрядность не должна сохранятся? Тоесть при всех вызовах modPow() разрядность должна оставатся одна и таже и зависеть от modulus.<br>
?&#33;?]]></description>
        <author>igorka</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1813707</guid>
        <pubDate>Sat, 22 Dec 2007 23:12:23 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1813707</link>
        <description><![CDATA[wind: Размер массива байт, который возвращает BigInteger.toByteArray(), зависит от разрядности числа.]]></description>
        <author>wind</author>
        <category>Java</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1813702</guid>
        <pubDate>Sat, 22 Dec 2007 22:43:52 +0000</pubDate>
        <title>I need help. RSA in java</title>
        <link>https://forum.sources.ru/index.php?showtopic=216642&amp;view=findpost&amp;p=1813702</link>
        <description><![CDATA[igorka: <div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">&nbsp;&nbsp; BigInteger encrypt(byte [] message) throws Exception {</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;byte[] block = new byte[2];</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;ByteArrayOutputStream mes = new ByteArrayOutputStream();</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;for(int i = 0; i &#60; message.length; i+=2){</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.arraycopy(message, i, block, 0, 2);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;byte [] tmp = new BigInteger(block).modPow(publicKey, modulus).toByteArray();</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(tmp.length % 8 != 0) &nbsp;{</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(&quot;Dow! length = &quot; + tmp.length);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} </div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;mes.write(tmp); &nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp; &nbsp; </div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return new BigInteger(mes.toByteArray());</div><div class="code_line">&nbsp;&nbsp; &nbsp;}</div></ol></div></div></div></div><br>
<br>
Это дебаг версия функции кодирования. В качестве параметров функция принимает исходное сообщение(условно четной длинны).<br>
Потом сообщение разбивается на блоки по два байта, и шифруется алгоритмом RSA. Длинна ключа(модуля) 64 бит, 8 байт.<br>
<br>
Проблема заключается в том что раз от разу <span class='tag-size' data-value='14' style='font-size:14pt;'>[B]гуляет длина закодированого блока&#33;</span>, <br>
для проверки добавлено условие if(tmp.length % 8 &#33;= 0)<br>
<br>
Подозреваю что собака зарыта где-то в классе BigInteger. modPow() должна возвращать всегда числа одинаковой разрядности? или нет?<br>
Что делать? Хелп ми плз.]]></description>
        <author>igorka</author>
        <category>Java</category>
      </item>
	
      </channel>
      </rss>
	