fork download
  1. #include <algorithm>
  2. #include <array>
  3. #include <cstdlib>
  4. #include <cstring>
  5. #include <ctime>
  6. #include <iomanip>
  7. #include <iostream>
  8. #include <memory>
  9. #include <string>
  10. #include <utility>
  11. #include <vector>
  12.  
  13. using namespace std;
  14.  
  15. class EA;
  16. class RSA;
  17. class RPG;
  18. class SimpleRPG;
  19. class RBG;
  20. class SimpleRBG;
  21. class Sieve;
  22. class PT;
  23. class MRBPT;
  24. class HA;
  25. class SHA1;
  26. class BigMath;
  27. class BigInt;
  28. class BitField;
  29. class ByteInputStream;
  30. class ByteOutputStream;
  31. class OctetStringByteInputStream;
  32. class OctetStringByteOutputStream;
  33. class StringByteInputStream;
  34. class StringByteOutputStream;
  35. class BitInputStream;
  36. class BitInputStreamConnector;
  37. template <class X> class PrimitiveBitInputStream;
  38. template <class X> class Pool;
  39. template <class X> class ExArray;
  40. template <class X> class PrimitiveExArray;
  41. template <class X> class ClassObjectExArray;
  42. typedef ExArray<unsigned char> OctetString;
  43.  
  44. template <class X>
  45. class ExArray {
  46. public:
  47. virtual X& operator [](const unsigned int& i) = 0;
  48. virtual X& at(const unsigned int& i) = 0;
  49. virtual X& last() = 0;
  50. virtual unsigned int getSize() const = 0;
  51. virtual bool isEmpty() const = 0;
  52. virtual void push(const X& x) = 0;
  53. virtual void pop() = 0;
  54. virtual void clear() = 0;
  55. virtual void resize(const unsigned int& sz) = 0;
  56. };
  57.  
  58. template <class X>
  59. class PrimitiveExArray : public ExArray<X> {
  60. public:
  61. PrimitiveExArray(const unsigned int& sz = 0);
  62. PrimitiveExArray(const PrimitiveExArray& a);
  63. virtual ~PrimitiveExArray();
  64. PrimitiveExArray& operator =(const PrimitiveExArray& a);
  65. virtual X& operator [](const unsigned int& i);
  66. virtual X& at(const unsigned int& i);
  67. virtual X& last();
  68. virtual unsigned int getSize() const;
  69. virtual bool isEmpty() const;
  70. virtual void push(const X& x);
  71. virtual void pop();
  72. virtual void clear();
  73. virtual void resize(const unsigned int& sz);
  74. protected:
  75. X* buf;
  76. unsigned int buf_sz;
  77. unsigned int sz;
  78. };
  79.  
  80. template <class X>
  81. class ClassObjectExArray : public ExArray<X> {
  82. public:
  83. ClassObjectExArray(const unsigned int& sz = 0);
  84. ClassObjectExArray(const ClassObjectExArray& a);
  85. virtual ~ClassObjectExArray();
  86. ClassObjectExArray& operator =(const ClassObjectExArray& a);
  87. virtual X& operator [](const unsigned int& i);
  88. virtual X& at(const unsigned int& i);
  89. virtual X& last();
  90. virtual unsigned int getSize() const;
  91. virtual bool isEmpty() const;
  92. virtual void push(const X& x);
  93. virtual void pop();
  94. virtual void clear();
  95. virtual void resize(const unsigned int& sz);
  96. protected:
  97. X* buf;
  98. unsigned int buf_sz;
  99. unsigned int sz;
  100. };
  101.  
  102. template <class X>
  103. class Pool {
  104. public:
  105. class Ptr {
  106. public:
  107. Ptr(Pool* pool);
  108. Ptr(const Ptr& ptr);
  109. virtual ~Ptr();
  110. Ptr& operator =(const Ptr& ptr);
  111. X& operator *() const;
  112. X* operator ->() const;
  113. X* get() const;
  114. protected:
  115. Pool* pool;
  116. pair<X*, unsigned int*> x_cnt;
  117. void release();
  118. };
  119. Pool();
  120. virtual ~Pool();
  121. protected:
  122. PrimitiveExArray<pair<X*, unsigned int*> > xa;
  123. Pool(const Pool& pool);
  124. Pool& operator =(const Pool& pool);
  125. pair<X*, unsigned int*> get();
  126. void putBack(const pair<X*, unsigned int*>& x_cnt);
  127. friend Ptr;
  128. };
  129.  
  130. class BigInt {
  131. public:
  132. BigInt();
  133. BigInt(const int& num);
  134. BigInt(const string& str, const unsigned int& base = 10);
  135. BigInt(const BitField& fld, const int& sign = 1);
  136. BigInt(const BigInt& num);
  137. BigInt operator -() const;
  138. BigInt operator +(const BigInt& ade) const;
  139. BigInt operator -(const BigInt& sub) const;
  140. BigInt operator *(const BigInt& mer) const;
  141. BigInt operator /(const BigInt& dsr) const;
  142. BigInt operator %(const BigInt& nrm) const;
  143. pair<BigInt, BigInt> divide(const BigInt& dsr) const;
  144. BigInt operator <<(const size_t& num) const;
  145. BigInt operator >>(const size_t& num) const;
  146. BigInt& operator =(const BigInt& num);
  147. BigInt& operator +=(const BigInt& ade);
  148. BigInt& operator -=(const BigInt& sub);
  149. BigInt& operator *=(const BigInt& mer);
  150. BigInt& operator /=(const BigInt& dsr);
  151. BigInt& operator %=(const BigInt& nrm);
  152. BigInt& operator <<=(const unsigned int& num);
  153. BigInt& operator >>=(const unsigned int& num);
  154. BigInt& operator ++();
  155. BigInt operator ++(int);
  156. BigInt& operator --();
  157. BigInt operator --(int);
  158. bool operator ==(const BigInt& num) const;
  159. bool operator <(const BigInt& num) const;
  160. bool operator >(const BigInt& num) const;
  161. bool operator !=(const BigInt& num) const;
  162. bool operator <=(const BigInt& num) const;
  163. bool operator >=(const BigInt& num) const;
  164. BigInt abs() const;
  165. bool isZero() const;
  166. int getSign() const;
  167. bool getLSBit() const;
  168. unsigned char getByte(const unsigned int ls_pos) const;
  169. unsigned char getLSByte() const;
  170. unsigned long getLSLong() const;
  171. void setInt(const int& num);
  172. string toString(const unsigned int& base = 10) const;
  173. unsigned int getLength() const;
  174. protected:
  175. class BFPtr : public Pool<BitField>::Ptr {
  176. public:
  177. BFPtr();
  178. BFPtr(const unsigned long& num);
  179. BFPtr(const BitField& fld);
  180. protected:
  181. static Pool<BitField> pool;
  182. };
  183. int sign;
  184. BFPtr fld;
  185. BigInt(const BFPtr& fld, const int& sign);
  186. static BFPtr add(const BFPtr& age, const BFPtr& ade);
  187. static BFPtr subtract(const BFPtr& min, const BFPtr& sub);
  188. static BFPtr multiply(const BFPtr& mca, const BFPtr& mer);
  189. static pair<BFPtr, BFPtr> divide(const BFPtr& dde, const BFPtr& dsr);
  190. static unsigned int digitToNumber(const char& dig);
  191. static char numberToDigit(const unsigned int& num);
  192. };
  193.  
  194. class EA {
  195. public:
  196. virtual void encrypt(const shared_ptr<ByteInputStream>& msg_in, const shared_ptr<ByteOutputStream>& cip_out) = 0;
  197. virtual void decrypt(const shared_ptr<ByteInputStream>& cip_in, const shared_ptr<ByteOutputStream>& msg_out) = 0;
  198. };
  199.  
  200. class RSA : public EA {
  201. public:
  202. struct Key {
  203. BigInt n;
  204. BigInt e;
  205. };
  206. RSA(const Key& key);
  207. virtual void encrypt(const shared_ptr<ByteInputStream>& msg_in, const shared_ptr<ByteOutputStream>& cip_out);
  208. virtual void decrypt(const shared_ptr<ByteInputStream>& cip_in, const shared_ptr<ByteOutputStream>& msg_out);
  209. static pair<Key, Key> generateKeys(const unsigned int& len);
  210. static Key makeKey(const BigInt& n, const BigInt& e);
  211. protected:
  212. Key key;
  213. unsigned int key_len;
  214. shared_ptr<RBG> rbg;
  215. RSA(const RSA& rsa);
  216. RSA& operator =(const RSA& rsa);
  217. shared_ptr<OctetString> encrypt(const shared_ptr<OctetString>& msg);
  218. shared_ptr<OctetString> decrypt(const shared_ptr<OctetString>& cip);
  219. };
  220.  
  221. class RPG {
  222. public:
  223. virtual BigInt generatePrime(const unsigned int& len) = 0;
  224. protected:
  225. static bool findSmallPrimeFactor(const BigInt& num);
  226. };
  227.  
  228. class SimpleRPG : public RPG {
  229. public:
  230. SimpleRPG();
  231. virtual BigInt generatePrime(const unsigned int& len);
  232. protected:
  233. shared_ptr<RBG> rbg;
  234. shared_ptr<PT> pt;
  235. SimpleRPG(const SimpleRPG& simple_rpg);
  236. SimpleRPG& operator =(const SimpleRPG& simple_rpg);
  237. };
  238.  
  239. class RBG {
  240. public:
  241. virtual bool generateBit() = 0;
  242. };
  243.  
  244. class SimpleRBG : public RBG {
  245. public:
  246. SimpleRBG();
  247. virtual bool generateBit();
  248. protected:
  249. shared_ptr<BitField> hash;
  250. unsigned int pos;
  251. SimpleRBG(const SimpleRBG& simple_rbg);
  252. SimpleRBG& operator =(const SimpleRBG& simple_rbg);
  253. };
  254.  
  255. class Sieve {
  256. public:
  257. unsigned int getNextPrime(const unsigned int& prev_num);
  258. static Sieve instance;
  259. protected:
  260. shared_ptr<PrimitiveExArray<bool> > tab;
  261. Sieve();
  262. };
  263.  
  264. class PT {
  265. public:
  266. virtual bool isPrime(const BigInt& p) = 0;
  267. };
  268.  
  269. class MRBPT : public PT {
  270. public:
  271. MRBPT();
  272. virtual bool isPrime(const BigInt& p);
  273. protected:
  274. MRBPT(const MRBPT& mrbpt);
  275. MRBPT& operator =(const MRBPT& mrbpt);
  276. };
  277.  
  278. class HA {
  279. public:
  280. virtual shared_ptr<BitField> computeHash(const shared_ptr<BitInputStream>& msg) = 0;
  281. };
  282.  
  283. class SHA1 : public HA {
  284. public:
  285. SHA1();
  286. virtual shared_ptr<BitField> computeHash(const shared_ptr<BitInputStream>& msg);
  287. protected:
  288. typedef unsigned long (*FUNCTION)(const unsigned long& x, const unsigned long& y, const unsigned long& z);
  289. SHA1(const SHA1& sha1);
  290. SHA1& operator =(const SHA1& sha1);
  291. static const FUNCTION FUNCTIONS[4];
  292. static const unsigned long K[4];
  293. static const unsigned long INITIAL_HASH_VALUES[5];
  294. static unsigned long ch(const unsigned long& x, const unsigned long& y, const unsigned long& z);
  295. static unsigned long parity(const unsigned long& x, const unsigned long& y, const unsigned long& z);
  296. static unsigned long maj(const unsigned long& x, const unsigned long& y, const unsigned long& z);
  297. };
  298.  
  299. class BigMath {
  300. public:
  301. static BigInt power(const BigInt& base, const BigInt& exp);
  302. static BigInt power(const BigInt& base, const BigInt& exp, const BigInt& nrm);
  303. static BigInt gcd(const BigInt& a, const BigInt& b);
  304. static BigInt lcm(const BigInt& a, const BigInt& b);
  305. static BigInt inverse(const BigInt& num, const BigInt& nrm);
  306. protected:
  307. BigMath();
  308. };
  309.  
  310. class BitField {
  311. public:
  312. class LongInputStream {
  313. public:
  314. LongInputStream(const BitField* fld);
  315. bool isEOF() const;
  316. unsigned long getLong();
  317. protected:
  318. const BitField* fld;
  319. unsigned int end;
  320. unsigned int cur;
  321. unsigned int low_len;
  322. unsigned int high_len;
  323. unsigned long low_mask;
  324. unsigned long high_mask;
  325. unsigned long rem;
  326. unsigned long num;
  327. };
  328. class LongOutputStream {
  329. public:
  330. LongOutputStream(BitField* fld);
  331. virtual ~LongOutputStream();
  332. void putLong(const unsigned long& num);
  333. void flush();
  334. protected:
  335. BitField* fld;
  336. unsigned int cur;
  337. unsigned int low_len;
  338. unsigned int high_len;
  339. unsigned long low_mask;
  340. unsigned long high_mask;
  341. unsigned long high_buf;
  342. bool bufed;
  343. };
  344. class ReverseLongInputStream {
  345. public:
  346. ReverseLongInputStream(const BitField* fld);
  347. bool isEOF() const;
  348. unsigned long getLong();
  349. protected:
  350. const BitField* fld;
  351. unsigned int end;
  352. unsigned int cur;
  353. unsigned int low_len;
  354. unsigned int high_len;
  355. unsigned long low_mask;
  356. unsigned long high_mask;
  357. unsigned long rem;
  358. unsigned long num;
  359. };
  360. class ReverseLongOutputStream {
  361. public:
  362. ReverseLongOutputStream(BitField* fld);
  363. virtual ~ReverseLongOutputStream();
  364. void putLong(const unsigned long& num);
  365. void flush();
  366. protected:
  367. BitField* fld;
  368. unsigned int low_len;
  369. unsigned int high_len;
  370. unsigned long low_mask;
  371. unsigned long high_mask;
  372. unsigned long low_buf;
  373. bool bufed;
  374. };
  375. BitField();
  376. BitField(const unsigned long& num);
  377. BitField(const BitField& fld);
  378. virtual ~BitField();
  379. BitField& operator =(const BitField& fld);
  380. unsigned int getLength() const;
  381. bool isEmpty() const;
  382. bool isZero() const;
  383. bool isOne() const;
  384. bool isPowerOf2() const;
  385. bool getBit(const unsigned int& pos) const;
  386. bool getLSBit() const;
  387. bool getMSBit() const;
  388. unsigned char getByte(const unsigned int& ls_pos) const;
  389. unsigned char getLSByte() const;
  390. unsigned long getLong(const unsigned int& ls_pos) const;
  391. unsigned long getLSLong() const;
  392. void setBit(const unsigned int& pos, const bool& bit);
  393. void pushMS(const bool& bit);
  394. template <class X> void pushMS(const X& x);
  395. void pushLS(const bool& bit);
  396. template <class X> void pushLS(const X& x);
  397. void setLong(const unsigned long& num);
  398. void shift(const int& num);
  399. void trim();
  400. void clear();
  401. int compare(const BitField& fld) const;
  402. string toString() const;
  403. BitField getSubfield(const unsigned int& ls_pos, const unsigned int& len) const;
  404. protected:
  405. unsigned char* buf;
  406. unsigned int buf_sz;
  407. int beg;
  408. unsigned int len;
  409. void extendIfNecessary(const int& len);
  410. friend LongInputStream;
  411. friend LongOutputStream;
  412. friend ReverseLongInputStream;
  413. friend ReverseLongOutputStream;
  414. };
  415.  
  416. class ByteInputStream {
  417. public:
  418. virtual unsigned char getByte() = 0;
  419. virtual bool isEOF() = 0;
  420. };
  421.  
  422. class ByteOutputStream {
  423. public:
  424. virtual void putByte(const unsigned char& byte) = 0;
  425. virtual void flush() = 0;
  426. };
  427.  
  428. class OctetStringByteInputStream : public ByteInputStream {
  429. public:
  430. OctetStringByteInputStream(const shared_ptr<OctetString>& os);
  431. virtual unsigned char getByte();
  432. virtual bool isEOF();
  433. protected:
  434. shared_ptr<OctetString> os;
  435. unsigned int i;
  436. OctetStringByteInputStream(const OctetStringByteInputStream& os_in);
  437. OctetStringByteInputStream& operator =(const OctetStringByteInputStream& os_in);
  438. };
  439.  
  440. class OctetStringByteOutputStream : public ByteOutputStream {
  441. public:
  442. OctetStringByteOutputStream();
  443. virtual void putByte(const unsigned char& byte);
  444. virtual void flush();
  445. shared_ptr<OctetString> getResult();
  446. protected:
  447. shared_ptr<OctetString> os;
  448. OctetStringByteOutputStream(const OctetStringByteOutputStream& os_out);
  449. OctetStringByteOutputStream& operator =(const OctetStringByteOutputStream& os_out);
  450. };
  451.  
  452. class StringByteInputStream : public ByteInputStream {
  453. public:
  454. StringByteInputStream(const string& str);
  455. virtual unsigned char getByte();
  456. virtual bool isEOF();
  457. protected:
  458. string str;
  459. size_t pos;
  460. StringByteInputStream(const StringByteInputStream& str_in);
  461. StringByteInputStream& operator =(const StringByteInputStream& str_in);
  462. };
  463.  
  464. class StringByteOutputStream : public ByteOutputStream {
  465. public:
  466. StringByteOutputStream();
  467. virtual void putByte(const unsigned char& byte);
  468. virtual void flush();
  469. string getResult();
  470. protected:
  471. string str;
  472. StringByteOutputStream(const StringByteOutputStream& str_out);
  473. StringByteOutputStream& operator =(const StringByteOutputStream& str_out);
  474. };
  475.  
  476. class BitInputStream {
  477. public:
  478. virtual bool getBit() = 0;
  479. virtual bool isEOF() = 0;
  480. };
  481.  
  482. class BitInputStreamConnector : public BitInputStream {
  483. public:
  484. BitInputStreamConnector(const shared_ptr<vector<shared_ptr<BitInputStream> > >& ins);
  485. virtual bool getBit();
  486. virtual bool isEOF();
  487. protected:
  488. shared_ptr<vector<shared_ptr<BitInputStream> > > ins;
  489. unsigned int i;
  490. };
  491.  
  492. template <class X>
  493. class PrimitiveBitInputStream : public BitInputStream {
  494. public:
  495. PrimitiveBitInputStream(const X& x);
  496. virtual bool getBit();
  497. virtual bool isEOF();
  498. protected:
  499. X x;
  500. unsigned int pos;
  501. PrimitiveBitInputStream(const PrimitiveBitInputStream& pri_in);
  502. PrimitiveBitInputStream& operator =(const PrimitiveBitInputStream& pri_in);
  503. };
  504.  
  505. template <class X> X rotateLeft(const X& x, const unsigned int& n, const unsigned int& w = (sizeof(X) << 3));
  506.  
  507. ////////////////////////////////////////////////////////////////////////////////
  508.  
  509. RSA::RSA(const Key& key) : key(key), key_len((key.n.getLength() + 7) / 8), rbg(new SimpleRBG) {}
  510.  
  511. void RSA::encrypt(const shared_ptr<ByteInputStream>& msg_in, const shared_ptr<ByteOutputStream>& cip_out) {
  512. unsigned int max_msg_len = this->key_len - 3 - 8;
  513. shared_ptr<OctetString> msg(new PrimitiveExArray<unsigned char>);
  514. while (!msg_in->isEOF()) {
  515. msg->clear();
  516. while (!msg_in->isEOF() && msg->getSize() < max_msg_len)
  517. msg->push(msg_in->getByte());
  518. shared_ptr<OctetString> cip = encrypt(msg);
  519. for (unsigned int i = 0; i < cip->getSize(); i++)
  520. cip_out->putByte(cip->at(i));
  521. }
  522. cip_out->flush();
  523. }
  524.  
  525. void RSA::decrypt(const shared_ptr<ByteInputStream>& cip_in, const shared_ptr<ByteOutputStream>& msg_out) {
  526. unsigned int max_cip_len = this->key_len;
  527. shared_ptr<OctetString> cip(new PrimitiveExArray<unsigned char>);
  528. while (!cip_in->isEOF()) {
  529. cip->clear();
  530. while (!cip_in->isEOF() && cip->getSize() < max_cip_len)
  531. cip->push(cip_in->getByte());
  532. shared_ptr<OctetString> msg = decrypt(cip);
  533. for (unsigned int i = 0; i < msg->getSize(); i++)
  534. msg_out->putByte(msg->at(i));
  535. }
  536. msg_out->flush();
  537. }
  538.  
  539. pair<RSA::Key, RSA::Key> RSA::generateKeys(const unsigned int& len) {
  540. if (len < 96) throw string("鍵の長さが96ビット未満。");
  541. if (len % 8 != 0) throw string("鍵の長さが8の倍数ではない。");
  542. shared_ptr<RPG> rpg(new SimpleRPG());
  543. BigInt p = rpg->generatePrime(len / 2);
  544. BigInt q = rpg->generatePrime(len / 2);
  545. BigInt n = p * q;
  546. BigInt e = rpg->generatePrime(len / 4);
  547. BigInt d = BigMath::inverse(e, BigMath::lcm(p - 1, q - 1));
  548. return make_pair(makeKey(n, e), makeKey(n, d));
  549. }
  550.  
  551. RSA::Key RSA::makeKey(const BigInt& n, const BigInt& e) {
  552. Key res;
  553. res.n = n;
  554. res.e = e;
  555. return res;
  556. }
  557.  
  558. shared_ptr<OctetString> RSA::encrypt(const shared_ptr<OctetString>& msg) {
  559. BitField fld;
  560. fld.pushLS<unsigned char>(0x00);
  561. fld.pushLS<unsigned char>(0x02);
  562. unsigned int pad_len = this->key_len - 3 - msg->getSize();
  563. for (unsigned int i = 0; i < pad_len; i++) {
  564. fld.pushLS(true);
  565. for (unsigned int j = 0; j < 7; j++)
  566. fld.pushLS(this->rbg->generateBit());
  567. }
  568. fld.pushLS<unsigned char>(0x00);
  569. for (unsigned int i = 0; i < msg->getSize(); i++)
  570. fld.pushLS<unsigned char>(msg->at(i));
  571. BigInt msg_num(fld);
  572. BigInt cip_num = BigMath::power(msg_num, this->key.e, this->key.n);
  573. shared_ptr<OctetString> cip(new PrimitiveExArray<unsigned char>);
  574. for (unsigned int i = 0; i < this->key_len; i++)
  575. cip->push(cip_num.getByte((this->key_len - 1 - i) << 3));
  576. return cip;
  577. }
  578.  
  579. shared_ptr<OctetString> RSA::decrypt(const shared_ptr<OctetString>& cip) {
  580. BitField fld;
  581. for (unsigned int i = 0; i < cip->getSize(); i++)
  582. fld.pushLS<unsigned char>(cip->at(i));
  583. BigInt cip_num(fld);
  584. BigInt msg_num = BigMath::power(cip_num, this->key.e, this->key.n);
  585. shared_ptr<OctetString> msg(new PrimitiveExArray<unsigned char>);
  586. bool pad_end = false;
  587. for (unsigned int i = 0; i < this->key_len; i++) {
  588. unsigned char byte = msg_num.getByte((this->key_len - 1 - i) << 3);
  589. if (i < 2) {
  590. if ((i == 0 && byte != 0x00) || (i == 1 && byte != 0x02))
  591. throw string("復号化できない。");
  592. }
  593. else if (!pad_end) {
  594. if (byte == 0x00) pad_end = true;
  595. }
  596. else msg->push(byte);
  597. }
  598. return msg;
  599. }
  600.  
  601. bool RPG::findSmallPrimeFactor(const BigInt& num) {
  602. bool res = false;
  603. unsigned int end = (num.getLength() * num.getLength()) >> 8;
  604. for (unsigned int prime = 3; prime < end; prime = Sieve::instance.getNextPrime(prime)) {
  605. if ((num % prime).isZero()) {
  606. res = true;
  607. break;
  608. }
  609. }
  610. return res;
  611. }
  612.  
  613. SimpleRPG::SimpleRPG() : rbg(new SimpleRBG), pt(new MRBPT) {}
  614.  
  615. BigInt SimpleRPG::generatePrime(const unsigned int& len) {
  616. if (len < 2) throw string("生成する素数の長さが2ビット未満。");
  617. BigInt num;
  618. bool found = false;
  619. while (!found) {
  620. BitField fld;
  621. if (len == 2) fld.pushMS(this->rbg->generateBit());
  622. else {
  623. fld.pushMS(true);
  624. for (unsigned int i = 0; i < len - 2; i++)
  625. fld.pushMS(this->rbg->generateBit());
  626. }
  627. fld.pushMS(true);
  628. for (num = BigInt(fld); num.getLength() == len; num += 2) {
  629. if (!findSmallPrimeFactor(num) && this->pt->isPrime(num)) {
  630. found = true;
  631. break;
  632. }
  633. }
  634. }
  635. return num;
  636. }
  637.  
  638. SimpleRBG::SimpleRBG() : pos(160) {
  639. unsigned long long t = time(nullptr);
  640. unsigned long long c = clock();
  641. srand((t >> 32) ^ (t & 0xffffffff) ^ (c >> 32) ^ (c & 0xffffffff));
  642. }
  643.  
  644. bool SimpleRBG::generateBit() {
  645. if (this->pos >= 160) {
  646. shared_ptr<HA> ha(new SHA1);
  647. shared_ptr<vector<shared_ptr<BitInputStream> > > ins(new vector<shared_ptr<BitInputStream> >);
  648. ins->push_back(shared_ptr<BitInputStream>(new PrimitiveBitInputStream<unsigned long long>(time(nullptr))));
  649. ins->push_back(shared_ptr<BitInputStream>(new PrimitiveBitInputStream<unsigned long long>(clock())));
  650. ins->push_back(shared_ptr<BitInputStream>(new PrimitiveBitInputStream<int>(rand())));
  651. this->hash = ha->computeHash(shared_ptr<BitInputStream>(new BitInputStreamConnector(ins)));
  652. this->pos = 0;
  653. }
  654. bool res = this->hash->getBit(this->pos);
  655. this->pos++;
  656. return res;
  657. }
  658.  
  659. unsigned int Sieve::getNextPrime(const unsigned int& prev_num) {
  660. unsigned int res;
  661. for (;;) {
  662. {
  663. unsigned int i = prev_num + 1;
  664. for (; i < this->tab->getSize(); i++) {
  665. if (this->tab->at(i) == true) {
  666. res = i;
  667. break;
  668. }
  669. }
  670. if (i < this->tab->getSize()) break;
  671. }
  672. unsigned int new_sz = this->tab->getSize() << 1;
  673. if (new_sz == 0) new_sz = 1;
  674. for (unsigned int i = this->tab->getSize(); i < new_sz; i++)
  675. this->tab->push(true);
  676. for (unsigned int i = 0; i < this->tab->getSize(); i++) {
  677. if (this->tab->at(i) == true) {
  678. for (unsigned int j = i + i; j < this->tab->getSize(); j += i)
  679. this->tab->at(j) = false;
  680. }
  681. }
  682. }
  683. return res;
  684. }
  685.  
  686. Sieve Sieve::instance;
  687.  
  688. Sieve::Sieve() : tab(new PrimitiveExArray<bool>) {
  689. this->tab->push(false);
  690. this->tab->push(false);
  691. }
  692.  
  693. MRBPT::MRBPT() {}
  694.  
  695. bool MRBPT::isPrime(const BigInt& p) {
  696. bool res = true;
  697. if (p == 1) res = false;
  698. else if (p == 2) res = true;
  699. else if (p.getLSBit() == false) res = false;
  700. else {
  701. BigInt o = p - 1;
  702. BigInt q = o;
  703. BigInt k(1);
  704. while (q.getLSBit() == false) {
  705. q >>= 1;
  706. k++;
  707. }
  708. BigInt cnt(3072 / p.getLength());
  709. if (cnt == 0) cnt = 1;
  710. BigInt a(2);
  711. BigInt gap(p / cnt);
  712. if (gap.isZero()) gap = 1;
  713. for (; a < p; a += gap) {
  714. BigInt b = BigMath::power(a, q, p);
  715. if (b != 1 && b != o) {
  716. BigInt i(1);
  717. for (; i < k; i++) {
  718. b = (b * b) % p;
  719. if (b == o) break;
  720. }
  721. if (i == k) {
  722. res = false;
  723. break;
  724. }
  725. }
  726. }
  727. }
  728. return res;
  729. }
  730.  
  731. const SHA1::FUNCTION SHA1::FUNCTIONS[4] = {
  732. ch,
  733. parity,
  734. maj,
  735. parity,
  736. };
  737.  
  738. const unsigned long SHA1::K[4] = {
  739. 0x5a827999,
  740. 0x6ed9eba1,
  741. 0x8f1bbcdc,
  742. 0xca62c1d6,
  743. };
  744.  
  745. const unsigned long SHA1::INITIAL_HASH_VALUES[5] = {
  746. 0x67452301,
  747. 0xefcdab89,
  748. 0x98badcfe,
  749. 0x10325476,
  750. 0xc3d2e1f0,
  751. };
  752.  
  753. SHA1::SHA1() {}
  754.  
  755. shared_ptr<BitField> SHA1::computeHash(const shared_ptr<BitInputStream>& msg) {
  756. shared_ptr<array<unsigned long, 5> > hash(new array<unsigned long, 5>);
  757. copy(INITIAL_HASH_VALUES, INITIAL_HASH_VALUES + 5, &hash->front());
  758. shared_ptr<array<unsigned long, 16> > block(new array<unsigned long, 16>);
  759. shared_ptr<array<unsigned long, 80> > sche(new array<unsigned long, 80>);
  760. unsigned long long len = 0;
  761. bool put_end = false;
  762. bool put_len = false;
  763. while (!put_len) {
  764. block->fill(0);
  765. unsigned int block_pos = 0;
  766. for (; block_pos < 512 && !msg->isEOF(); block_pos++) {
  767. block->at(block_pos >> 5) |= (msg->getBit() == true ? 1 : 0) << (32 - 1 - (block_pos & 0x1f));
  768. len++;
  769. }
  770. if (block_pos < 512) {
  771. if (!put_end) {
  772. block->at(block_pos >> 5) |= 1 << (32 - 1 - (block_pos & 0x1f));
  773. block_pos++;
  774. put_end = true;
  775. }
  776. if (block_pos + 64 <= 512) {
  777. block->at(14) = len >> 32;
  778. block->at(15) = len & 0xffffffff;
  779. put_len = true;
  780. }
  781. }
  782. for (unsigned int i = 0; i < 80; i++) {
  783. if (i < 16) sche->at(i) = block->at(i);
  784. else sche->at(i) = rotateLeft(
  785. sche->at(i - 3) ^
  786. sche->at(i - 8) ^
  787. sche->at(i - 14) ^
  788. sche->at(i - 16), 1);
  789. }
  790. unsigned long a = hash->at(0);
  791. unsigned long b = hash->at(1);
  792. unsigned long c = hash->at(2);
  793. unsigned long d = hash->at(3);
  794. unsigned long e = hash->at(4);
  795. for (unsigned int i = 0; i < 80; i++) {
  796. unsigned long t =
  797. rotateLeft(a, 5) +
  798. FUNCTIONS[i / 20](b, c, d) +
  799. e +
  800. K[i / 20] +
  801. sche->at(i);
  802. e = d;
  803. d = c;
  804. c = rotateLeft(b, 30);
  805. b = a;
  806. a = t;
  807. }
  808. hash->at(0) += a;
  809. hash->at(1) += b;
  810. hash->at(2) += c;
  811. hash->at(3) += d;
  812. hash->at(4) += e;
  813. }
  814. shared_ptr<BitField> res(new BitField);
  815. for (unsigned int i = 0; i < 5; i++) res->pushMS(hash->at(i));
  816. return res;
  817. }
  818.  
  819. unsigned long SHA1::ch(const unsigned long& x, const unsigned long& y, const unsigned long& z) {
  820. return (x & y) ^ (~x & z);
  821. }
  822.  
  823. unsigned long SHA1::parity(const unsigned long& x, const unsigned long& y, const unsigned long& z) {
  824. return x ^ y ^ z;
  825. }
  826.  
  827. unsigned long SHA1::maj(const unsigned long& x, const unsigned long& y, const unsigned long& z) {
  828. return (x & y) ^ (x & z) ^ (y & z);
  829. }
  830.  
  831. BigInt BigMath::power(const BigInt& base, const BigInt& exp) {
  832. BigInt res;
  833. if (base.isZero()) res = BigInt(0);
  834. else if (exp.isZero()) res = BigInt(1);
  835. else if (exp < 0) res = BigInt(1) / power(base, -exp);
  836. else {
  837. res.setInt(1);
  838. BigInt coef = base;
  839. for (BigInt exp2 = exp;;) {
  840. if (exp2.getLSBit()) res *= coef;
  841. exp2 >>= 1;
  842. if (exp2.isZero()) break;
  843. coef *= coef;
  844. }
  845. }
  846. return res;
  847. }
  848.  
  849. BigInt BigMath::power(const BigInt& base, const BigInt& exp, const BigInt& nrm) {
  850. BigInt res;
  851. if (base.isZero()) res = BigInt(0);
  852. else if (exp.isZero()) res = BigInt(1);
  853. else if (exp < 0) res = (BigInt(1) / power(base, -exp)) % nrm;
  854. else {
  855. res.setInt(1);
  856. BigInt coef = base % nrm;
  857. for (BigInt exp2 = exp;;) {
  858. if (exp2.getLSBit()) res = (res * coef) % nrm;
  859. exp2 >>= 1;
  860. if (exp2.isZero()) break;
  861. coef = (coef * coef) % nrm;
  862. }
  863. }
  864. return res;
  865. }
  866.  
  867. BigInt BigMath::gcd(const BigInt& a, const BigInt& b) {
  868. BigInt c(a.abs()), d(b.abs()), r;
  869. if (c < d) swap(c, d);
  870. for (;;) {
  871. r = c % d;
  872. if (r == 0) break;
  873. c = d;
  874. d = r;
  875. };
  876. if (d.getSign() != a.getSign()) d = -d;
  877. return d;
  878. }
  879.  
  880. BigInt BigMath::lcm(const BigInt& a, const BigInt& b) {
  881. return a * b / gcd(a, b);
  882. }
  883.  
  884. BigInt BigMath::inverse(const BigInt& num, const BigInt& nrm) {
  885. BigInt a(num.abs()), b(nrm.abs()), c, d(1), e(0);
  886. pair<BigInt, BigInt> q_r;
  887. if (a < b) {
  888. swap(a, b);
  889. swap(d, e);
  890. }
  891. for (;;) {
  892. q_r = a.divide(b);
  893. if (q_r.second == 0) break;
  894. c = d - e * q_r.first;
  895. d = e;
  896. e = c;
  897. a = b;
  898. b = q_r.second;
  899. };
  900. if (c.getSign() != nrm.getSign()) c += nrm;
  901. return c;
  902. }
  903.  
  904. class MColPtr : public Pool<PrimitiveExArray<unsigned long> >::Ptr {
  905. public:
  906. MColPtr();
  907. protected:
  908. static Pool<PrimitiveExArray<unsigned long> > pool;
  909. };
  910.  
  911. class MTabPtr : public Pool<ClassObjectExArray<MColPtr> >::Ptr {
  912. public:
  913. MTabPtr();
  914. protected:
  915. static Pool<ClassObjectExArray<MColPtr> > pool;
  916. };
  917.  
  918. BigInt::BigInt() : sign(0) {}
  919.  
  920. BigInt::BigInt(const int& num) {
  921. this->sign = num == 0 ? 0 : (num > 0 ? 1 : -1);
  922. this->fld->setLong(num < 0 ? -num : num);
  923. }
  924.  
  925. BigInt::BigInt(const string& str, const unsigned int& base) {
  926. this->sign = 1;
  927. this->fld->setLong(0);
  928. BFPtr base_fld(base);
  929. auto iter = str.begin();
  930. if (*iter == '+') {
  931. this->sign = 1;
  932. iter++;
  933. }
  934. else if (*iter == '-') {
  935. this->sign = -1;
  936. iter++;
  937. }
  938. for (; iter != str.end(); iter++) {
  939. if (iter != str.begin()) {
  940. this->fld = multiply(this->fld, base_fld);
  941. }
  942. unsigned int num = digitToNumber(*iter);
  943. if (num >= base) throw string("値が範囲を逸脱している。");
  944. this->fld = add(this->fld, BFPtr(num));
  945. }
  946. if (this->fld->isZero()) this->sign = 0;
  947. }
  948.  
  949. BigInt::BigInt(const BitField& fld, const int& sign) {
  950. *this->fld = fld;
  951. this->fld->trim();
  952. this->sign = fld.isZero() ? 0 : sign;
  953. }
  954.  
  955. BigInt::BigInt(const BigInt& num) : sign(num.sign), fld(*num.fld) {}
  956.  
  957. BigInt BigInt::operator -() const {
  958. return BigInt(BFPtr(*this->fld), -this->sign);
  959. }
  960.  
  961. BigInt BigInt::operator +(const BigInt& ade) const {
  962. BigInt res;
  963. if (this->sign == 0)
  964. res = ade;
  965. else if (ade.sign == 0)
  966. res = *this;
  967. else if (this->sign == ade.sign)
  968. res = BigInt(add(this->fld, ade.fld), this->sign);
  969. else {
  970. int cmp_res = this->fld->compare(*ade.fld);
  971. if (cmp_res == 0) res.setInt(0);
  972. else {
  973. int sign;
  974. BFPtr gre_fld, less_fld;
  975. if (cmp_res > 0) {
  976. sign = this->sign;
  977. gre_fld = this->fld;
  978. less_fld = ade.fld;
  979. }
  980. else {
  981. sign = ade.sign;
  982. gre_fld = ade.fld;
  983. less_fld = this->fld;
  984. }
  985. res = BigInt(subtract(gre_fld, less_fld), sign);
  986. }
  987. }
  988. return res;
  989. }
  990.  
  991. BigInt BigInt::operator -(const BigInt& sub) const {
  992. return operator +(-sub);
  993. }
  994.  
  995. BigInt BigInt::operator *(const BigInt& mer) const {
  996. return BigInt(multiply(this->fld, mer.fld), this->sign * mer.sign);
  997. }
  998.  
  999. BigInt BigInt::operator /(const BigInt& dsr) const {
  1000. return BigInt(divide(this->fld, dsr.fld).first, this->sign * dsr.sign);
  1001. }
  1002.  
  1003. BigInt BigInt::operator %(const BigInt& nrm) const {
  1004. return BigInt(divide(this->fld, nrm.fld).second, this->sign);
  1005. }
  1006.  
  1007. pair<BigInt, BigInt> BigInt::divide(const BigInt& dsr) const {
  1008. pair<BFPtr, BFPtr> quo_rem = divide(this->fld, dsr.fld);
  1009. return make_pair(BigInt(quo_rem.first, this->sign * dsr.sign), BigInt(quo_rem.second, this->sign));
  1010. }
  1011.  
  1012. BigInt BigInt::operator <<(const unsigned int& num) const {
  1013. BFPtr fld(*this->fld);
  1014. fld->shift(-num);
  1015. return BigInt(fld, this->sign);
  1016. }
  1017.  
  1018. BigInt BigInt::operator >>(const unsigned int& num) const {
  1019. BFPtr fld(*this->fld);
  1020. fld->shift(num);
  1021. return BigInt(fld, this->sign);
  1022. }
  1023.  
  1024. BigInt& BigInt::operator =(const BigInt& num) {
  1025. if (&num != this) {
  1026. this->sign = num.sign;
  1027. *this->fld = *num.fld;
  1028. }
  1029. return *this;
  1030. }
  1031.  
  1032. BigInt& BigInt::operator +=(const BigInt& add) {
  1033. return *this = *this + add;
  1034. }
  1035.  
  1036. BigInt& BigInt::operator -=(const BigInt& sub) {
  1037. return *this = *this - sub;
  1038. }
  1039.  
  1040. BigInt& BigInt::operator *=(const BigInt& mer) {
  1041. return *this = *this * mer;
  1042. }
  1043.  
  1044. BigInt& BigInt::operator /=(const BigInt& dsr) {
  1045. return *this = *this / dsr;
  1046. }
  1047.  
  1048. BigInt& BigInt::operator %=(const BigInt& nrm) {
  1049. return *this = *this % nrm;
  1050. }
  1051.  
  1052. BigInt& BigInt::operator <<=(const size_t& num) {
  1053. return *this = *this << num;
  1054. }
  1055.  
  1056. BigInt& BigInt::operator >>=(const size_t& num) {
  1057. return *this = *this >> num;
  1058. }
  1059.  
  1060. BigInt& BigInt::operator ++() {
  1061. return *this += 1;
  1062. }
  1063.  
  1064. BigInt BigInt::operator ++(int) {
  1065. BigInt res = *this;
  1066. *this += 1;
  1067. return res;
  1068. }
  1069.  
  1070. BigInt& BigInt::operator --() {
  1071. return *this -= 1;
  1072. }
  1073.  
  1074. BigInt BigInt::operator --(int) {
  1075. BigInt res = *this;
  1076. *this -= 1;
  1077. return res;
  1078. }
  1079.  
  1080. bool BigInt::operator ==(const BigInt& num) const {
  1081. if (&num == this) return true;
  1082. return this->sign == num.sign && this->fld->compare(*num.fld) == 0;
  1083. }
  1084.  
  1085. bool BigInt::operator <(const BigInt& num) const {
  1086. if (&num == this) return false;
  1087. int cmp_res = this->fld->compare(*num.fld);
  1088. return (this->sign >= 0 && num.sign >= 0 && cmp_res < 0) ||
  1089. (this->sign < 0 && num.sign >= 0) ||
  1090. (this->sign < 0 && num.sign < 0 && cmp_res > 0);
  1091. }
  1092.  
  1093. bool BigInt::operator >(const BigInt& num) const {
  1094. if (&num == this) return false;
  1095. int cmp_res = this->fld->compare(*num.fld);
  1096. return (this->sign >= 0 && num.sign >= 0 && cmp_res > 0) ||
  1097. (this->sign >= 0 && num.sign < 0) ||
  1098. (this->sign < 0 && num.sign < 0 && cmp_res < 0);
  1099. }
  1100.  
  1101. bool BigInt::operator !=(const BigInt& num) const {
  1102. return !operator ==(num);
  1103. }
  1104.  
  1105. bool BigInt::operator <=(const BigInt& num) const {
  1106. return !operator >(num);
  1107. }
  1108.  
  1109. bool BigInt::operator >=(const BigInt& num) const {
  1110. return !operator <(num);
  1111. }
  1112.  
  1113. BigInt BigInt::abs() const {
  1114. return BigInt(BFPtr(*this->fld), 1);
  1115. }
  1116.  
  1117. bool BigInt::isZero() const {
  1118. return this->fld->isZero();
  1119. }
  1120.  
  1121. int BigInt::getSign() const {
  1122. return this->sign;
  1123. }
  1124.  
  1125. bool BigInt::getLSBit() const {
  1126. return this->fld->getLSBit();
  1127. }
  1128.  
  1129. unsigned char BigInt::getByte(const unsigned int ls_pos) const {
  1130. return this->fld->getByte(ls_pos);
  1131. }
  1132.  
  1133. unsigned char BigInt::getLSByte() const {
  1134. return this->fld->getLSByte();
  1135. }
  1136.  
  1137. unsigned long BigInt::getLSLong() const {
  1138. return this->fld->getLSLong();
  1139. }
  1140.  
  1141. void BigInt::setInt(const int& num) {
  1142. this->sign = num == 0 ? 0 : (num > 0 ? 1 : -1);
  1143. this->fld->setLong(num < 0 ? -num : num);
  1144. }
  1145.  
  1146. string BigInt::toString(const unsigned int& base) const {
  1147. string res = "";
  1148. pair<BFPtr, BFPtr> quo_rem(BFPtr(*this->fld), BFPtr());
  1149. BFPtr base_fld;
  1150. base_fld->setLong(base);
  1151. while (!quo_rem.first->isZero()) {
  1152. quo_rem = divide(quo_rem.first, base_fld);
  1153. res += numberToDigit(quo_rem.second->getLSLong());
  1154. }
  1155. if (res.empty()) res += '0';
  1156. if (this->sign < 0) res += '-';
  1157. reverse(res.begin(), res.end());
  1158. size_t pos = 0;
  1159. for (; pos < res.length() - 1; pos++) if (res[pos] != '0') break;
  1160. return res.substr(pos, res.length() - pos);
  1161. }
  1162.  
  1163. unsigned int BigInt::getLength() const {
  1164. return this->fld->getLength();
  1165. }
  1166.  
  1167. BigInt::BFPtr::BFPtr() : Pool<BitField>::Ptr(&pool) {
  1168. this->x_cnt.first->clear();
  1169. }
  1170.  
  1171. BigInt::BFPtr::BFPtr(const unsigned long& num) : Pool<BitField>::Ptr(&pool) {
  1172. this->x_cnt.first->setLong(num);
  1173. }
  1174.  
  1175. BigInt::BFPtr::BFPtr(const BitField& fld) : Pool<BitField>::Ptr(&pool) {
  1176. *this->x_cnt.first = fld;
  1177. }
  1178.  
  1179. Pool<BitField> BigInt::BFPtr::pool;
  1180.  
  1181. BigInt::BigInt(const BFPtr& fld, const int& sign) {
  1182. this->fld = fld;
  1183. this->fld->trim();
  1184. this->sign = fld->isZero() ? 0 : sign;
  1185. }
  1186.  
  1187. BigInt::BFPtr BigInt::add(const BFPtr& age, const BFPtr& ade) {
  1188. BFPtr sum;
  1189. if (age->isZero()) *sum = *ade;
  1190. else if (ade->isZero()) *sum = *age;
  1191. else {
  1192. BitField::LongOutputStream sum_out(sum.get());
  1193. BitField::LongInputStream age_in(age.get());
  1194. BitField::LongInputStream ade_in(ade.get());
  1195. bool carry = false;
  1196. while (!age_in.isEOF() || !ade_in.isEOF()) {
  1197. unsigned long age_num = !age_in.isEOF() ? age_in.getLong() : 0;
  1198. unsigned long ade_num = !ade_in.isEOF() ? ade_in.getLong() : 0;
  1199. unsigned long sum_num = (age_num & ((1 << (32 - 1)) - 1)) + (ade_num & ((1 << (32 - 1)) - 1)) + (carry ? 1 : 0);
  1200. int ms_num = (age_num >> (32 - 1)) + (ade_num >> (32 - 1)) + (sum_num >> (32 - 1));
  1201. carry = ms_num > 1;
  1202. if (carry) ms_num -= 2;
  1203. sum_num = (sum_num & ((1 << (32 - 1)) - 1)) | (ms_num << (32 - 1));
  1204. sum_out.putLong(sum_num);
  1205. }
  1206. sum_out.flush();
  1207. if (carry) sum->pushMS(true);
  1208. }
  1209. if (sum->isEmpty()) sum->pushMS(false);
  1210. else sum->trim();
  1211. return sum;
  1212. }
  1213.  
  1214. BigInt::BFPtr BigInt::subtract(const BFPtr& min, const BFPtr& sub) {
  1215. BFPtr dif;
  1216. if (sub->isZero()) *dif = *min;
  1217. else {
  1218. BitField::LongOutputStream dif_out(dif.get());
  1219. BitField::LongInputStream min_in(min.get());
  1220. BitField::LongInputStream sub_in(sub.get());
  1221. bool borrow = false;
  1222. while (!min_in.isEOF() || !sub_in.isEOF()) {
  1223. unsigned int min_num = !min_in.isEOF() ? min_in.getLong() : 0;
  1224. unsigned int sub_num = !sub_in.isEOF() ? sub_in.getLong() : 0;
  1225. unsigned int dif_num = (min_num | (1 << (32 - 1))) - (sub_num & ((1 << (32 - 1)) - 1)) - (borrow ? 1 : 0);
  1226. int ms_num = (min_num >> (32 - 1)) - (sub_num >> (32 - 1)) - (1 - (dif_num >> (32 - 1)));
  1227. borrow = ms_num < 0;
  1228. if (borrow) ms_num += 2;
  1229. dif_num = (dif_num & ((1 << (32 - 1)) - 1)) | (ms_num << (32 - 1));
  1230. dif_out.putLong(dif_num);
  1231. }
  1232. dif_out.flush();
  1233. if (borrow) throw string("被減数が減数より小さい。");
  1234. }
  1235. if (dif->isEmpty()) dif->pushMS(false);
  1236. else dif->trim();
  1237. return dif;
  1238. }
  1239.  
  1240. BigInt::BFPtr BigInt::multiply(const BFPtr& mca, const BFPtr& mer) {
  1241. BFPtr pro;
  1242. if (mca->isZero() || mer->isZero()) pro->setLong(0);
  1243. else if (mca->isPowerOf2()) {
  1244. *pro = *mer;
  1245. pro->shift(-(mca->getLength() - 1));
  1246. }
  1247. else if (mer->isPowerOf2()) {
  1248. *pro = *mca;
  1249. pro->shift(-(mer->getLength() - 1));
  1250. }
  1251. else {
  1252. BitField::LongOutputStream pro_out(pro.get());
  1253. BitField::LongInputStream mer_in(mer.get());
  1254. MTabPtr tab;
  1255. for (unsigned int base_col = 0; !mer_in.isEOF(); base_col++) {
  1256. unsigned long mer_num = mer_in.getLong();
  1257. BitField::LongInputStream mca_in(mca.get());
  1258. for (unsigned int col = base_col; !mca_in.isEOF(); col++) {
  1259. unsigned long mca_num = mca_in.getLong();
  1260. unsigned long long pro_num = (unsigned long long)mer_num * mca_num;
  1261. unsigned long rem_num = pro_num & (((unsigned long long)1 << 32) - 1);
  1262. unsigned long carry_num = pro_num >> 32;
  1263. if (tab->getSize() <= col) tab->push(MColPtr());
  1264. tab->at(col)->push(rem_num);
  1265. if (carry_num != 0) {
  1266. if (tab->getSize() <= col + 1) tab->push(MColPtr());
  1267. tab->at(col + 1)->push(carry_num);
  1268. }
  1269. }
  1270. }
  1271. for (unsigned int col = 0; col < tab->getSize(); col++) {
  1272. unsigned long age_num = 0;
  1273. unsigned long carry_num = 0;
  1274. for (unsigned int i = 0; i < tab->at(col)->getSize(); i++) {
  1275. unsigned long ade_num = tab->at(col)->at(i);
  1276. unsigned long sum_num = (age_num & ((1 << (32 - 1)) - 1)) + (ade_num & ((1 << (32 - 1)) - 1));
  1277. int ms_num = (age_num >> (32 - 1)) + (ade_num >> (32 - 1)) + (sum_num >> (32 - 1));
  1278. if (ms_num > 1) {
  1279. carry_num++;
  1280. ms_num -= 2;
  1281. }
  1282. age_num = (sum_num & ((1 << (32 - 1)) - 1)) | (ms_num << (32 - 1));
  1283. }
  1284. pro_out.putLong(age_num);
  1285. if (carry_num != 0) {
  1286. if (tab->getSize() <= col + 1) tab->push(MColPtr());
  1287. tab->at(col + 1)->push(carry_num);
  1288. }
  1289. }
  1290. pro_out.flush();
  1291. }
  1292. if (pro->isEmpty()) pro->pushMS(false);
  1293. else pro->trim();
  1294. return pro;
  1295. }
  1296.  
  1297. pair<BigInt::BFPtr, BigInt::BFPtr> BigInt::divide(const BFPtr& dde, const BFPtr& dsr) {
  1298. if (dsr->isZero()) throw string("除数がゼロ。");
  1299. pair<BFPtr, BFPtr> quo_rem;
  1300. int cmp_res = dde->compare(*dsr);
  1301. if (cmp_res == 0) {
  1302. quo_rem.first->setLong(1);
  1303. quo_rem.second->setLong(0);
  1304. }
  1305. else if (cmp_res < 0) {
  1306. quo_rem.first->setLong(0);
  1307. *quo_rem.second = *dde;
  1308. }
  1309. else if (dsr->isPowerOf2()) {
  1310. *quo_rem.first = *dde;
  1311. quo_rem.first->shift(dsr->getLength() - 1);
  1312. *quo_rem.second = dde->getSubfield(0, dsr->getLength() - 1);
  1313. }
  1314. else {
  1315. BitField::ReverseLongOutputStream quo_out(quo_rem.first.get());
  1316. unsigned int k = (32 - (dsr->getLength() & (32 - 1))) & (32 - 1);
  1317. BFPtr k_dde(*dde);
  1318. k_dde->shift(-k);
  1319. BFPtr k_dsr(*dsr);
  1320. k_dsr->shift(-k);
  1321. BitField::ReverseLongInputStream dde_in(k_dde.get());
  1322. BitField::ReverseLongInputStream dsr_in(k_dsr.get());
  1323. unsigned long dsr_ms_num = dsr_in.getLong();
  1324. while (!dde_in.isEOF()) {
  1325. BitField::ReverseLongOutputStream rem_out(quo_rem.second.get());
  1326. rem_out.putLong(dde_in.getLong());
  1327. rem_out.flush();
  1328. quo_rem.second->trim();
  1329. int cmp_res = quo_rem.second->compare(*k_dsr);
  1330. if (cmp_res == 0) {
  1331. quo_out.putLong(1);
  1332. quo_rem.second->clear();
  1333. }
  1334. else if (cmp_res < 0) quo_out.putLong(0);
  1335. else {
  1336. BitField::ReverseLongInputStream rem_in(quo_rem.second.get());
  1337. unsigned long long rem_ms_num = rem_in.getLong();
  1338. if (rem_ms_num < dsr_ms_num)
  1339. rem_ms_num = (rem_ms_num << 32) | rem_in.getLong();
  1340. unsigned long long quo_num = min(rem_ms_num / dsr_ms_num, ((unsigned long long)1 << 32) - 1);
  1341. BFPtr pro = multiply(k_dsr, BFPtr(quo_num));
  1342. while (quo_rem.second->compare(*pro) < 0) {
  1343. quo_num--;
  1344. quo_rem.second = add(quo_rem.second, k_dsr);
  1345. }
  1346. quo_out.putLong(quo_num);
  1347. quo_rem.second = subtract(quo_rem.second, pro);
  1348. }
  1349. }
  1350. quo_out.flush();
  1351. quo_rem.second->shift(k);
  1352. }
  1353. if (quo_rem.first->isEmpty()) quo_rem.first->pushMS(false);
  1354. else quo_rem.first->trim();
  1355. if (quo_rem.second->isEmpty()) quo_rem.second->pushMS(false);
  1356. else quo_rem.second->trim();
  1357. return quo_rem;
  1358. }
  1359.  
  1360. unsigned int BigInt::digitToNumber(const char& dig) {
  1361. unsigned int res;
  1362. if (dig >= '0' && dig <= '9') res = dig - '0';
  1363. else if (dig >= 'A' && dig <= 'Z') res = 10 + dig - 'A';
  1364. else if (dig >= 'a' && dig <= 'z') res = 10 + dig - 'a';
  1365. else throw string("文字が数ではない。");
  1366. return res;
  1367. }
  1368.  
  1369. char BigInt::numberToDigit(const unsigned int& num) {
  1370. char res;
  1371. if (num >= 0 && num <= 9) res = '0' + num;
  1372. else if (num >= 10 && num <= 36) res = 'a' + (num - 10);
  1373. else throw string("数が範囲を逸脱している。");
  1374. return res;
  1375. }
  1376.  
  1377. MColPtr::MColPtr() : Pool<PrimitiveExArray<unsigned long> >::Ptr(&pool) {
  1378. this->x_cnt.first->clear();
  1379. }
  1380.  
  1381. Pool<PrimitiveExArray<unsigned long> > MColPtr::pool;
  1382.  
  1383. MTabPtr::MTabPtr() : Pool<ClassObjectExArray<MColPtr> >::Ptr(&pool) {
  1384. this->x_cnt.first->clear();
  1385. }
  1386.  
  1387. Pool<ClassObjectExArray<MColPtr> > MTabPtr::pool;
  1388.  
  1389. BitField::LongInputStream::LongInputStream(const BitField* fld) {
  1390. this->fld = fld;
  1391. this->rem = this->fld->len;
  1392. if (this->rem != 0) {
  1393. this->high_len = this->fld->beg & (32 - 1);
  1394. this->low_len = 32 - this->high_len;
  1395. this->high_mask = (1 << this->high_len) - 1;
  1396. this->low_mask = ~this->high_mask;
  1397. this->end = this->fld->buf_sz >> 2;
  1398. this->cur = this->fld->beg >> 5;
  1399. this->num = ((unsigned long*)this->fld->buf)[this->cur];
  1400. }
  1401. }
  1402.  
  1403. bool BitField::LongInputStream::isEOF() const {
  1404. return this->rem == 0;
  1405. }
  1406.  
  1407. unsigned long BitField::LongInputStream::getLong() {
  1408. unsigned int res = 0;
  1409. res |= (this->num & this->low_mask) >> this->high_len;
  1410. if (this->rem >= this->low_len) {
  1411. this->rem -= this->low_len;
  1412. if (this->rem != 0) {
  1413. this->cur++;
  1414. if (this->cur == this->end) this->cur = 0;
  1415. this->num = ((unsigned long*)this->fld->buf)[this->cur];
  1416. if (this->high_len != 0) {
  1417. res |= (this->num & this->high_mask) << this->low_len;
  1418. if (this->rem >= this->high_len)
  1419. this->rem -= this->high_len;
  1420. else {
  1421. res &= (1 << (this->low_len + this->rem)) - 1;
  1422. this->rem = 0;
  1423. }
  1424. }
  1425. }
  1426. }
  1427. else {
  1428. res &= (1 << this->rem) - 1;
  1429. this->rem = 0;
  1430. }
  1431. return res;
  1432. }
  1433.  
  1434. BitField::LongOutputStream::LongOutputStream(BitField* fld) {
  1435. this->fld = fld;
  1436. unsigned int fld_end = this->fld->beg + this->fld->len;
  1437. unsigned int buf_len = this->fld->buf_sz << 3;
  1438. unsigned int act_fld_end;
  1439. if (fld_end <= buf_len) act_fld_end = fld_end;
  1440. else act_fld_end = fld_end - buf_len;
  1441. this->high_len = act_fld_end & (32 - 1);
  1442. this->low_len = 32 - this->high_len;
  1443. this->high_mask = (1 << this->high_len) - 1;
  1444. this->low_mask = ~this->high_mask;
  1445. this->cur = act_fld_end >> 5;
  1446. unsigned int end = this->fld->buf_sz >> 2;
  1447. if (this->fld->len != 0 && this->cur != end)
  1448. this->high_buf = ((unsigned long*)this->fld->buf)[this->cur] & this->high_mask;
  1449. else this->high_buf = 0;
  1450. this->bufed = false;
  1451. }
  1452.  
  1453. BitField::LongOutputStream::~LongOutputStream() {
  1454. flush();
  1455. }
  1456.  
  1457. void BitField::LongOutputStream::putLong(const unsigned long& num) {
  1458. this->fld->extendIfNecessary(32);
  1459. unsigned int end = this->fld->buf_sz >> 2;
  1460. if (this->cur == end) this->cur = 0;
  1461. ((unsigned long*)this->fld->buf)[this->cur] = this->high_buf | (num << this->high_len);
  1462. if (this->high_len != 0) {
  1463. this->high_buf = num >> this->low_len;
  1464. this->bufed = true;
  1465. }
  1466. this->cur++;
  1467. }
  1468.  
  1469. void BitField::LongOutputStream::flush() {
  1470. if (this->bufed) {
  1471. unsigned int fld_end = this->fld->beg + this->fld->len;
  1472. unsigned int buf_len = this->fld->buf_sz << 3;
  1473. unsigned int act_fld_end;
  1474. if (fld_end <= buf_len) act_fld_end = fld_end;
  1475. else act_fld_end = fld_end - buf_len;
  1476. unsigned int cur = act_fld_end >> 5;
  1477. if (cur == 0) cur = (this->fld->buf_sz >> 2) - 1;
  1478. else cur--;
  1479. ((unsigned long*)this->fld->buf)[cur] =
  1480. this->high_buf | (((unsigned long*)this->fld->buf)[cur] & this->low_mask);
  1481. this->bufed = false;
  1482. }
  1483. }
  1484.  
  1485. BitField::ReverseLongInputStream::ReverseLongInputStream(const BitField* fld) {
  1486. this->fld = fld;
  1487. this->rem = this->fld->len;
  1488. if (this->rem != 0) {
  1489. this->end = this->fld->buf_sz >> 2;
  1490. this->high_len = this->fld->beg & (32 - 1);
  1491. this->low_len = 32 - this->high_len;
  1492. this->high_mask = (1 << this->high_len) - 1;
  1493. this->low_mask = ~this->high_mask;
  1494. unsigned int fld_end = this->fld->beg + this->fld->len;
  1495. unsigned int buf_len = this->fld->buf_sz << 3;
  1496. unsigned int act_fld_end;
  1497. if (fld_end <= buf_len) act_fld_end = fld_end;
  1498. else act_fld_end = fld_end - buf_len;
  1499. unsigned int last_len = act_fld_end & (32 - 1);
  1500. if (last_len <= this->high_len) this->cur = act_fld_end >> 5;
  1501. else this->cur = (act_fld_end + (32 - 1)) >> 5;
  1502. if (this->cur != this->end)
  1503. this->num = ((unsigned long*)this->fld->buf)[this->cur];
  1504. }
  1505. }
  1506.  
  1507. bool BitField::ReverseLongInputStream::isEOF() const {
  1508. return this->rem == 0;
  1509. }
  1510.  
  1511. unsigned long BitField::ReverseLongInputStream::getLong() {
  1512. unsigned int res = 0;
  1513. unsigned int len = this->rem & (32 - 1);
  1514. if (len == 0) len = 32;
  1515. if (len > this->low_len) {
  1516. res |= this->num & this->high_mask;
  1517. unsigned int high_len = len - this->low_len;
  1518. if (high_len < this->high_len)
  1519. res &= (1 << high_len) - 1;
  1520. res <<= this->low_len;
  1521. }
  1522. if (this->cur == 0) this->cur = this->end;
  1523. this->cur--;
  1524. this->num = ((unsigned long*)this->fld->buf)[this->cur];
  1525. res |= (this->num & this->low_mask) >> this->high_len;
  1526. if (len < this->low_len) res &= (1 << len) - 1;
  1527. this->rem -= len;
  1528. return res;
  1529. }
  1530.  
  1531. BitField::ReverseLongOutputStream::ReverseLongOutputStream(BitField* fld) {
  1532. this->fld = fld;
  1533. this->high_len = this->fld->beg & (32 - 1);
  1534. this->low_len = 32 - this->high_len;
  1535. this->high_mask = (1 << this->high_len) - 1;
  1536. this->low_mask = ~this->high_mask;
  1537. unsigned int cur = this->fld->beg >> 5;
  1538. unsigned int end = this->fld->buf_sz >> 2;
  1539. if (this->fld->len != 0 && cur != end)
  1540. this->low_buf = ((unsigned long*)this->fld->buf)[cur] & this->low_mask;
  1541. else this->low_buf = 0;
  1542. this->bufed = false;
  1543. }
  1544.  
  1545. BitField::ReverseLongOutputStream::~ReverseLongOutputStream() {
  1546. flush();
  1547. }
  1548.  
  1549. void BitField::ReverseLongOutputStream::putLong(const unsigned long& num) {
  1550. this->fld->extendIfNecessary(-32);
  1551. unsigned int cur = (this->fld->beg >> 5) + 1;
  1552. unsigned int end = this->fld->buf_sz >> 2;
  1553. if (cur == end) cur = 0;
  1554. if (this->high_len != 0) {
  1555. ((unsigned long*)this->fld->buf)[cur] = (num >> this->low_len) | this->low_buf;
  1556. this->low_buf = num << this->high_len;
  1557. }
  1558. else {
  1559. ((unsigned long*)this->fld->buf)[cur] = this->low_buf;
  1560. this->low_buf = num;
  1561. }
  1562. this->bufed = true;
  1563. }
  1564.  
  1565. void BitField::ReverseLongOutputStream::flush() {
  1566. if (this->bufed) {
  1567. unsigned int cur = this->fld->beg >> 5;
  1568. ((unsigned long*)this->fld->buf)[cur] =
  1569. (((unsigned long*)this->fld->buf)[cur] & this->high_mask) | this->low_buf;
  1570. this->bufed = false;
  1571. }
  1572. }
  1573.  
  1574. BitField::BitField() : buf(nullptr), buf_sz(0), beg(0), len(0) {}
  1575.  
  1576. BitField::BitField(const unsigned long& num) : buf(nullptr), buf_sz(0), beg(0), len(0) {
  1577. extendIfNecessary(32);
  1578. *(unsigned long*)this->buf = num;
  1579. trim();
  1580. }
  1581.  
  1582. BitField::BitField(const BitField& fld) : buf(nullptr), buf_sz(0), beg(0), len(0) {
  1583. if (fld.len != 0) {
  1584. this->buf_sz = fld.buf_sz;
  1585. this->buf = new unsigned char[this->buf_sz];
  1586. memcpy(this->buf, fld.buf, fld.buf_sz);
  1587. this->beg = fld.beg;
  1588. this->len = fld.len;
  1589. }
  1590. }
  1591.  
  1592. BitField::~BitField() {
  1593. if (this->buf) delete[] this->buf;
  1594. }
  1595.  
  1596. BitField& BitField::operator =(const BitField& fld) {
  1597. if (&fld != this) {
  1598. this->len = 0;
  1599. if (fld.len != 0) {
  1600. this->buf_sz = fld.buf_sz;
  1601. this->buf = new unsigned char[this->buf_sz];
  1602. memcpy(this->buf, fld.buf, fld.buf_sz);
  1603. this->beg = fld.beg;
  1604. this->len = fld.len;
  1605. }
  1606. }
  1607. return *this;
  1608. }
  1609.  
  1610. unsigned int BitField::getLength() const {
  1611. return this->len;
  1612. }
  1613.  
  1614. bool BitField::isEmpty() const {
  1615. return this->len == 0;
  1616. }
  1617.  
  1618. bool BitField::isZero() const {
  1619. bool res = true;
  1620. for (unsigned int pos = 0; pos < this->len; pos++) {
  1621. if (getBit(pos) == true) {
  1622. res = false;
  1623. break;
  1624. }
  1625. }
  1626. return res;
  1627. }
  1628.  
  1629. bool BitField::isOne() const {
  1630. bool res = false;
  1631. if (this->len != 0 && getBit(0) == true) {
  1632. res = true;
  1633. for (unsigned int pos = 1; pos < this->len; pos++) {
  1634. if (getBit(pos) == true) {
  1635. res = false;
  1636. break;
  1637. }
  1638. }
  1639. }
  1640. return res;
  1641. }
  1642.  
  1643. bool BitField::isPowerOf2() const {
  1644. unsigned int cnt = 0;
  1645. for (unsigned int pos = 0; pos < this->len; pos++) {
  1646. if (getBit(pos) == true) {
  1647. cnt++;
  1648. if (cnt > 1) break;
  1649. }
  1650. }
  1651. return cnt == 1;
  1652. }
  1653.  
  1654. bool BitField::getBit(const unsigned int& pos) const {
  1655. unsigned int abs_pos = this->beg + pos;
  1656. unsigned int buf_len = this->buf_sz << 3;
  1657. if (abs_pos >= buf_len) abs_pos -= buf_len;
  1658. return ((this->buf[abs_pos >> 3] >> (abs_pos & (8 - 1))) & 1) == 1;
  1659. }
  1660.  
  1661. bool BitField::getLSBit() const {
  1662. return getBit(0);
  1663. }
  1664.  
  1665. bool BitField::getMSBit() const {
  1666. return getBit(this->len - 1);
  1667. }
  1668.  
  1669. unsigned char BitField::getByte(const unsigned int& ls_pos) const {
  1670. unsigned char res = 0;
  1671. for (unsigned int pos = 0; pos < 8 && ls_pos + pos < this->len; pos++)
  1672. res |= (getBit(ls_pos + pos) == true ? 1 : 0) << pos;
  1673. return res;
  1674. }
  1675.  
  1676. unsigned char BitField::getLSByte() const {
  1677. return getByte(0);
  1678. }
  1679.  
  1680. unsigned long BitField::getLong(const unsigned int& ls_pos) const {
  1681. unsigned long res = 0;
  1682. for (unsigned int pos = 0; pos < 32 && ls_pos + pos < this->len; pos++)
  1683. res |= (getBit(ls_pos + pos) == true ? 1 : 0) << pos;
  1684. return res;
  1685. }
  1686.  
  1687. unsigned long BitField::getLSLong() const {
  1688. return getLong(0);
  1689. }
  1690.  
  1691. void BitField::setBit(const unsigned int& pos, const bool& bit) {
  1692. unsigned int abs_pos = this->beg + pos;
  1693. unsigned int buf_len = this->buf_sz << 3;
  1694. if (abs_pos >= buf_len) abs_pos -= buf_len;
  1695. if (bit) this->buf[abs_pos >> 3] |= 1 << (abs_pos & (8 - 1));
  1696. else this->buf[abs_pos >> 3] &= ~(1 << (abs_pos & (8 - 1)));
  1697. }
  1698.  
  1699. void BitField::pushMS(const bool& bit) {
  1700. extendIfNecessary(1);
  1701. setBit(this->len - 1, bit);
  1702. }
  1703.  
  1704. template <class X> void BitField::pushMS(const X& x) {
  1705. for (unsigned int pos = 0; pos < (sizeof(X) << 3); pos++)
  1706. pushMS(((x >> pos) & 1) == 1);
  1707. }
  1708.  
  1709. void BitField::pushLS(const bool& bit) {
  1710. extendIfNecessary(-1);
  1711. setBit(0, bit);
  1712. }
  1713.  
  1714. template <class X> void BitField::pushLS(const X& x) {
  1715. for (unsigned int pos = 0; pos < (sizeof(X) << 3); pos++)
  1716. pushLS(((x >> ((sizeof(X) << 3) - 1 - pos)) & 1) == 1);
  1717. }
  1718.  
  1719. void BitField::setLong(const unsigned long& num) {
  1720. clear();
  1721. extendIfNecessary(32);
  1722. *(unsigned int*)this->buf = num;
  1723. trim();
  1724. }
  1725.  
  1726. void BitField::shift(const int& num) {
  1727. if (num < 0) {
  1728. extendIfNecessary(num);
  1729. for (unsigned int pos = 0; pos < -num; pos++)
  1730. setBit(pos, false);
  1731. }
  1732. else if (num > 0) {
  1733. unsigned int act_num;
  1734. if (num <= this->len) act_num = num;
  1735. else act_num = this->len;
  1736. this->beg += act_num;
  1737. unsigned int buf_len = this->buf_sz << 3;
  1738. if (this->beg >= buf_len) this->beg -= buf_len;
  1739. this->len -= act_num;
  1740. }
  1741. }
  1742.  
  1743. void BitField::trim() {
  1744. while (this->len > 1 && getMSBit() == false) this->len--;
  1745. }
  1746.  
  1747. void BitField::clear() {
  1748. this->beg = 0;
  1749. this->len = 0;
  1750. }
  1751.  
  1752. int BitField::compare(const BitField& fld) const {
  1753. int res = 0;
  1754. if (&fld != this) {
  1755. for (unsigned int next_pos = this->len < fld.len ? fld.len : this->len; next_pos > 0; next_pos--) {
  1756. unsigned int pos = next_pos - 1;
  1757. bool bit1 = pos < this->len ? getBit(pos) : false;
  1758. bool bit2 = pos < fld.len ? fld.getBit(pos) : false;
  1759. if (bit1 == false && bit2 == true) {
  1760. res = -1;
  1761. break;
  1762. }
  1763. else if (bit1 == true && bit2 == false) {
  1764. res = 1;
  1765. break;
  1766. }
  1767. }
  1768. }
  1769. return res;
  1770. }
  1771.  
  1772. string BitField::toString() const {
  1773. string res = "";
  1774. for (unsigned int pos = 0; pos < this->len; pos++)
  1775. res += getBit(pos) == true ? '1' : '0';
  1776. return res;
  1777. }
  1778.  
  1779. BitField BitField::getSubfield(const unsigned int& ls_pos, const unsigned int& len) const {
  1780. BitField res;
  1781. for (unsigned int pos = 0; pos < len; pos++)
  1782. res.pushMS(getBit(ls_pos + pos));
  1783. return res;
  1784. }
  1785.  
  1786. void BitField::extendIfNecessary(const int& len) {
  1787. unsigned int abs_len = len < 0 ? -len : len;
  1788. unsigned int need_sz = ((((this->len + abs_len + (8 - 1)) >> 3) + (4 - 1)) >> 2) << 2;
  1789. if (need_sz > this->buf_sz) {
  1790. unsigned int new_buf_sz = need_sz << 1;
  1791. unsigned char* new_buf = new unsigned char[new_buf_sz];
  1792. unsigned int new_beg = 0;
  1793. if (this->len != 0) {
  1794. unsigned int fld_beg = this->beg >> 3;
  1795. unsigned int fld_end = (this->beg + this->len + (8 - 1)) >> 3;
  1796. if (fld_end <= this->buf_sz) {
  1797. unsigned int fld_sz = fld_end - fld_beg;
  1798. memcpy(new_buf + fld_beg, this->buf + fld_beg, fld_sz);
  1799. new_beg = this->beg;
  1800. }
  1801. else {
  1802. unsigned int low_sz = this->buf_sz - fld_beg;
  1803. unsigned int new_low_beg = new_buf_sz - low_sz;
  1804. memcpy(new_buf + new_low_beg, this->buf + fld_beg, low_sz);
  1805. unsigned int high_sz = fld_end - this->buf_sz;
  1806. memcpy(new_buf, this->buf, high_sz);
  1807. unsigned int buf_len = this->buf_sz << 3;
  1808. unsigned int low_len = buf_len - this->beg;
  1809. unsigned int new_buf_len = new_buf_sz << 3;
  1810. new_beg = new_buf_len - low_len;
  1811. }
  1812. delete[] this->buf;
  1813. }
  1814. this->buf_sz = new_buf_sz;
  1815. this->buf = new_buf;
  1816. this->beg = new_beg;
  1817. }
  1818. if (len < 0) {
  1819. this->beg += len;
  1820. int buf_len = this->buf_sz << 3;
  1821. if (this->beg < 0) this->beg += buf_len;
  1822. }
  1823. this->len += abs_len;
  1824. }
  1825.  
  1826. OctetStringByteInputStream::OctetStringByteInputStream(const shared_ptr<OctetString>& os) : os(os), i(0) {}
  1827.  
  1828. unsigned char OctetStringByteInputStream::getByte() {
  1829. return this->os->at(this->i++);
  1830. }
  1831.  
  1832. bool OctetStringByteInputStream::isEOF() {
  1833. return this->i >= this->os->getSize();
  1834. }
  1835.  
  1836. OctetStringByteOutputStream::OctetStringByteOutputStream() : os(new PrimitiveExArray<unsigned char>) {}
  1837.  
  1838. void OctetStringByteOutputStream::putByte(const unsigned char& byte) {
  1839. this->os->push(byte);
  1840. }
  1841.  
  1842. void OctetStringByteOutputStream::flush() {}
  1843.  
  1844. shared_ptr<OctetString> OctetStringByteOutputStream::getResult() {
  1845. return this->os;
  1846. }
  1847.  
  1848. StringByteInputStream::StringByteInputStream(const string& str) : str(str), pos(0) {}
  1849.  
  1850. unsigned char StringByteInputStream::getByte() {
  1851. return this->str.at(this->pos++);
  1852. }
  1853.  
  1854. bool StringByteInputStream::isEOF() {
  1855. return this->pos >= this->str.length();
  1856. }
  1857.  
  1858. StringByteOutputStream::StringByteOutputStream() {}
  1859.  
  1860. void StringByteOutputStream::putByte(const unsigned char& byte) {
  1861. this->str += (char)byte;
  1862. }
  1863.  
  1864. void StringByteOutputStream::flush() {}
  1865.  
  1866. string StringByteOutputStream::getResult() {
  1867. return this->str;
  1868. }
  1869.  
  1870. BitInputStreamConnector::BitInputStreamConnector(const shared_ptr<vector<shared_ptr<BitInputStream> > >& ins) : ins(ins), i(0) {}
  1871.  
  1872. bool BitInputStreamConnector::getBit() {
  1873. bool res = this->ins->at(this->i)->getBit();
  1874. if (this->ins->at(this->i)->isEOF()) this->i++;
  1875. return res;
  1876. }
  1877.  
  1878. bool BitInputStreamConnector::isEOF() {
  1879. return this->i >= this->ins->size();
  1880. }
  1881.  
  1882. template <class X>
  1883. PrimitiveBitInputStream<X>::PrimitiveBitInputStream(const X& x) : x(x), pos(0) {}
  1884.  
  1885. template <class X>
  1886. bool PrimitiveBitInputStream<X>::getBit() {
  1887. bool res = ((this->x >> ((sizeof(X) << 3) - 1 - this->pos)) & 1) == 1;
  1888. this->pos++;
  1889. return res;
  1890. }
  1891.  
  1892. template <class X>
  1893. bool PrimitiveBitInputStream<X>::isEOF() {
  1894. return this->pos >= (sizeof(X) << 3);
  1895. }
  1896.  
  1897. template <class X>
  1898. Pool<X>::Ptr::Ptr(Pool* pool) : pool(pool) {
  1899. this->x_cnt = this->pool->get();
  1900. if (this->x_cnt.second) (*this->x_cnt.second)++;
  1901. }
  1902.  
  1903. template <class X>
  1904. Pool<X>::Ptr::Ptr(const Ptr& ptr) {
  1905. this->pool = ptr.pool;
  1906. this->x_cnt = ptr.x_cnt;
  1907. if (this->x_cnt.second) (*this->x_cnt.second)++;
  1908. }
  1909.  
  1910. template <class X>
  1911. Pool<X>::Ptr::~Ptr() {
  1912. release();
  1913. }
  1914.  
  1915. template <class X>
  1916. typename Pool<X>::Ptr& Pool<X>::Ptr::operator =(const Ptr& ptr) {
  1917. if (&ptr != this) {
  1918. release();
  1919. this->x_cnt = ptr.x_cnt;
  1920. if (this->x_cnt.second) (*this->x_cnt.second)++;
  1921. }
  1922. return *this;
  1923. }
  1924.  
  1925. template <class X>
  1926. X& Pool<X>::Ptr::operator *() const {
  1927. return *this->x_cnt.first;
  1928. }
  1929.  
  1930. template <class X>
  1931. X* Pool<X>::Ptr::operator ->() const {
  1932. return this->x_cnt.first;
  1933. }
  1934.  
  1935. template <class X>
  1936. X* Pool<X>::Ptr::get() const {
  1937. return this->x_cnt.first;
  1938. }
  1939.  
  1940. template <class X>
  1941. void Pool<X>::Ptr::release() {
  1942. if (this->x_cnt.second) {
  1943. (*this->x_cnt.second)--;
  1944. if (*this->x_cnt.second == 0)
  1945. pool->putBack(this->x_cnt);
  1946. }
  1947. }
  1948.  
  1949. template <class X>
  1950. Pool<X>::Pool() {}
  1951.  
  1952. template <class X>
  1953. Pool<X>::~Pool() {
  1954. for (unsigned int i = 0; i < this->xa.getSize(); i++) {
  1955. delete this->xa.at(i).first;
  1956. delete this->xa.at(i).second;
  1957. }
  1958. }
  1959.  
  1960. template <class X>
  1961. pair<X*, unsigned int*> Pool<X>::get() {
  1962. if (this->xa.isEmpty()) this->xa.push(make_pair(new X, new unsigned int(0)));
  1963. pair<X*, unsigned int*> res = this->xa.last();
  1964. this->xa.pop();
  1965. return res;
  1966. }
  1967.  
  1968. template <class X>
  1969. void Pool<X>::putBack(const pair<X*, unsigned int*>& x_cnt) {
  1970. this->xa.push(x_cnt);
  1971. }
  1972.  
  1973. template <class X>
  1974. PrimitiveExArray<X>::PrimitiveExArray(const unsigned int& sz) : buf(nullptr), buf_sz(0), sz(0) {
  1975. resize(sz);
  1976. }
  1977.  
  1978. template <class X>
  1979. PrimitiveExArray<X>::PrimitiveExArray(const PrimitiveExArray& a) : buf(nullptr), buf_sz(0), sz(0) {
  1980. if (a.sz != 0) {
  1981. if (this->buf) delete[] this->buf;
  1982. this->buf_sz = a.buf_sz;
  1983. this->buf = new X[this->buf_sz];
  1984. this->sz = a.sz;
  1985. memcpy(this->buf, a.buf, sizeof(X) * this->sz);
  1986. }
  1987. }
  1988.  
  1989. template <class X>
  1990. PrimitiveExArray<X>::~PrimitiveExArray() {
  1991. if (this->buf) delete[] this->buf;
  1992. }
  1993.  
  1994. template <class X>
  1995. PrimitiveExArray<X>& PrimitiveExArray<X>::operator =(const PrimitiveExArray& a) {
  1996. if (&a != this && a.sz != 0) {
  1997. if (this->buf) delete[] this->buf;
  1998. this->buf_sz = a.buf_sz;
  1999. this->buf = new X[this->buf_sz];
  2000. this->sz = a.sz;
  2001. memcpy(this->buf, a.buf, sizeof(X) * this->sz);
  2002. }
  2003. return *this;
  2004. }
  2005.  
  2006. template <class X>
  2007. X& PrimitiveExArray<X>::operator [](const unsigned int& i) {
  2008. return this->buf[i];
  2009. }
  2010.  
  2011. template <class X>
  2012. X& PrimitiveExArray<X>::at(const unsigned int& i) {
  2013. return this->buf[i];
  2014. }
  2015.  
  2016. template <class X>
  2017. X& PrimitiveExArray<X>::last() {
  2018. return this->buf[this->sz - 1];
  2019. }
  2020.  
  2021. template <class X>
  2022. unsigned int PrimitiveExArray<X>::getSize() const {
  2023. return this->sz;
  2024. }
  2025.  
  2026. template <class X>
  2027. bool PrimitiveExArray<X>::isEmpty() const {
  2028. return this->sz == 0;
  2029. }
  2030.  
  2031. template <class X>
  2032. void PrimitiveExArray<X>::push(const X& x) {
  2033. resize(this->sz + 1);
  2034. this->buf[this->sz - 1] = x;
  2035. }
  2036.  
  2037. template <class X>
  2038. void PrimitiveExArray<X>::pop() {
  2039. this->sz--;
  2040. }
  2041.  
  2042. template <class X>
  2043. void PrimitiveExArray<X>::clear() {
  2044. this->sz = 0;
  2045. }
  2046.  
  2047. template <class X>
  2048. void PrimitiveExArray<X>::resize(const unsigned int& sz) {
  2049. if (sz > this->buf_sz) {
  2050. unsigned int new_buf_sz = sz << 1;
  2051. X* new_buf = new X[new_buf_sz];
  2052. if (this->buf_sz != 0) {
  2053. memcpy(new_buf, this->buf, sizeof(X) * this->sz);
  2054. delete[] this->buf;
  2055. }
  2056. this->buf = new_buf;
  2057. this->buf_sz = new_buf_sz;
  2058. }
  2059. this->sz = sz;
  2060. }
  2061.  
  2062. template <class X>
  2063. ClassObjectExArray<X>::ClassObjectExArray(const unsigned int& sz) : buf(nullptr), buf_sz(0), sz(0) {
  2064. resize(sz);
  2065. }
  2066.  
  2067. template <class X>
  2068. ClassObjectExArray<X>::ClassObjectExArray(const ClassObjectExArray& a) : buf(nullptr), buf_sz(0), sz(0) {
  2069. if (a.sz != 0) {
  2070. if (this->buf) delete[] this->buf;
  2071. this->buf_sz = a.buf_sz;
  2072. this->buf = new X[this->buf_sz];
  2073. this->sz = a.sz;
  2074. copy(a.buf, a.buf + a.sz, this->buf);
  2075. }
  2076. }
  2077.  
  2078. template <class X>
  2079. ClassObjectExArray<X>& ClassObjectExArray<X>::operator =(const ClassObjectExArray& a) {
  2080. if (&a != this && a.sz != 0) {
  2081. if (this->buf) delete[] this->buf;
  2082. this->buf_sz = a.buf_sz;
  2083. this->buf = new X[this->buf_sz];
  2084. this->sz = a.sz;
  2085. copy(a.buf, a.buf + a.sz, this->buf);
  2086. }
  2087. return *this;
  2088. }
  2089.  
  2090. template <class X>
  2091. ClassObjectExArray<X>::~ClassObjectExArray() {
  2092. if (this->buf) delete[] this->buf;
  2093. }
  2094.  
  2095. template <class X>
  2096. X& ClassObjectExArray<X>::operator [](const unsigned int& i) {
  2097. return this->buf[i];
  2098. }
  2099.  
  2100. template <class X>
  2101. X& ClassObjectExArray<X>::at(const unsigned int& i) {
  2102. return this->buf[i];
  2103. }
  2104.  
  2105. template <class X>
  2106. X& ClassObjectExArray<X>::last() {
  2107. return this->buf[this->sz - 1];
  2108. }
  2109.  
  2110. template <class X>
  2111. unsigned int ClassObjectExArray<X>::getSize() const {
  2112. return this->sz;
  2113. }
  2114.  
  2115. template <class X>
  2116. bool ClassObjectExArray<X>::isEmpty() const {
  2117. return this->sz == 0;
  2118. }
  2119.  
  2120. template <class X>
  2121. void ClassObjectExArray<X>::push(const X& x) {
  2122. resize(this->sz + 1);
  2123. this->buf[this->sz - 1] = x;
  2124. }
  2125.  
  2126. template <class X>
  2127. void ClassObjectExArray<X>::pop() {
  2128. this->buf[this->sz - 1] = X();
  2129. this->sz--;
  2130. }
  2131.  
  2132. template <class X>
  2133. void ClassObjectExArray<X>::clear() {
  2134. for (unsigned int i = 0; i < this->sz; i++) this->buf[i] = X();
  2135. this->sz = 0;
  2136. }
  2137.  
  2138. template <class X>
  2139. void ClassObjectExArray<X>::resize(const unsigned int& sz) {
  2140. if (sz > this->buf_sz) {
  2141. unsigned int new_buf_sz = sz << 1;
  2142. X* new_buf = new X[new_buf_sz];
  2143. if (this->buf_sz != 0) {
  2144. copy(this->buf, this->buf + this->sz, new_buf);
  2145. delete[] this->buf;
  2146. }
  2147. this->buf = new_buf;
  2148. this->buf_sz = new_buf_sz;
  2149. }
  2150. else if (sz < this->sz) for (unsigned int i = sz; i < this->sz; i++) this->buf[i] = X();
  2151. this->sz = sz;
  2152. }
  2153.  
  2154. template <class X> X rotateLeft(const X& x, const unsigned int& n, const unsigned int& w) {
  2155. return (x << n) | (x >> (w - n));
  2156. }
  2157.  
  2158. ////////////////////////////////////////////////////////////////////////////////
  2159.  
  2160. class Receiver;
  2161. class Sender;
  2162.  
  2163. class Receiver {
  2164. public:
  2165. string name;
  2166. Receiver(const string& name);
  2167. void createKeys(const unsigned int& len);
  2168. RSA::Key getPublicKey() const;
  2169. void receivedCipherText(const Sender& sen, const shared_ptr<OctetString>& cip_text);
  2170. void decryptReceivedCipherText() const;
  2171. protected:
  2172. pair<RSA::Key, RSA::Key> pub_pri_keys;
  2173. shared_ptr<OctetString> rec_cip_text;
  2174. };
  2175.  
  2176. class Sender {
  2177. public:
  2178. string name;
  2179. Sender(const string& name);
  2180. void getPublicKeyFrom(const Receiver& rec);
  2181. void encryptMessage(const string& msg);
  2182. void sendCipherTextTo(Receiver& rec) const;
  2183. protected:
  2184. RSA::Key rec_pub_key;
  2185. shared_ptr<OctetString> cip_text;
  2186. };
  2187.  
  2188. Receiver::Receiver(const string& name) : name(name) {}
  2189.  
  2190. void Receiver::createKeys(const unsigned int& len) {
  2191. this->pub_pri_keys = RSA::generateKeys(len);
  2192.  
  2193. cout << this->name << "「" << "鍵のペアを作ります" << "」" << endl;
  2194. cout << this->name << "「" << "公開鍵=(n=" << this->pub_pri_keys.first.n.toString(16) << ", e=" << this->pub_pri_keys.first.e.toString(16) << ")" << "」" << endl;
  2195. cout << this->name << "「" << "秘密鍵=(n=" << this->pub_pri_keys.second.n.toString(16) << ", e=" << this->pub_pri_keys.second.e.toString(16) << ")" << "」" << endl;
  2196. cout << endl;
  2197. }
  2198.  
  2199. void Receiver::receivedCipherText(const Sender& sen, const shared_ptr<OctetString>& cip_text) {
  2200. cout << this->name << "「" << sen.name << "から暗号文を受信しました" << "」" << endl;
  2201.  
  2202. this->rec_cip_text = cip_text;
  2203. cout << this->name << "「" << "暗号文=";
  2204. for (unsigned int i = 0; i < this->rec_cip_text->getSize(); i++) {
  2205. cout << hex << setw(2) << setfill('0') << (unsigned int)this->rec_cip_text->at(i);
  2206. }
  2207. cout << "」" << endl;
  2208.  
  2209. cout << endl;
  2210. }
  2211.  
  2212. void Receiver::decryptReceivedCipherText() const {
  2213. cout << this->name << "「" << "暗号文を復号化します" << "」" << endl;
  2214. cout << this->name << "「" << "使用する鍵=(n=" << this->pub_pri_keys.second.n.toString(16) << ", e=" << this->pub_pri_keys.second.e.toString(16) << ")" << "」" << endl;
  2215.  
  2216. shared_ptr<EA> de_rsa(new RSA(this->pub_pri_keys.second));
  2217. shared_ptr<ByteInputStream> cip_in(new OctetStringByteInputStream(this->rec_cip_text));
  2218. shared_ptr<StringByteOutputStream> msg_out(new StringByteOutputStream());
  2219. de_rsa->decrypt(cip_in, msg_out);
  2220. string msg = msg_out->getResult();
  2221.  
  2222. cout << this->name << "「" << "メッセージ=" << msg << "」" << endl;
  2223. cout << endl;
  2224. }
  2225.  
  2226. RSA::Key Receiver::getPublicKey() const {
  2227. return this->pub_pri_keys.first;
  2228. }
  2229.  
  2230. Sender::Sender(const string& name) : name(name) {}
  2231.  
  2232. void Sender::getPublicKeyFrom(const Receiver& rec) {
  2233. cout << this->name << "「" << rec.name << "の公開鍵を取得します" << "」" << endl;
  2234.  
  2235. this->rec_pub_key = rec.getPublicKey();
  2236.  
  2237. cout << endl;
  2238. }
  2239.  
  2240. void Sender::encryptMessage(const string& msg) {
  2241. cout << this->name << "「" << "メッセージを暗号化します" << "」" << endl;
  2242. cout << this->name << "「" << "メッセージ=" << msg << "」" << endl;
  2243. cout << this->name << "「" << "使用する鍵=(n=" << this->rec_pub_key.n.toString(16) << ", e=" << this->rec_pub_key.e.toString(16) << ")" << "」" << endl;
  2244.  
  2245. shared_ptr<EA> en_rsa(new RSA(this->rec_pub_key));
  2246. shared_ptr<ByteInputStream> msg_in(new StringByteInputStream(msg));
  2247. shared_ptr<OctetStringByteOutputStream> cip_out(new OctetStringByteOutputStream());
  2248. en_rsa->encrypt(msg_in, cip_out);
  2249. this->cip_text = cip_out->getResult();
  2250.  
  2251. cout << this->name << "「" << "暗号文=";
  2252. for (unsigned int i = 0; i < this->cip_text->getSize(); i++) {
  2253. cout << hex << setw(2) << setfill('0') << (unsigned int)this->cip_text->at(i);
  2254. }
  2255. cout << "」" << endl;
  2256. cout << endl;
  2257. }
  2258.  
  2259. void Sender::sendCipherTextTo(Receiver& rec) const {
  2260. cout << this->name << "「" << rec.name << "に暗号文を送信します" << "」" << endl;
  2261. cout << endl;
  2262.  
  2263. rec.receivedCipherText(*this, this->cip_text);
  2264. }
  2265.  
  2266. int main() {
  2267. try {
  2268. Receiver rec("太郎");
  2269. Sender sen("次郎");
  2270. rec.createKeys(512);
  2271. sen.getPublicKeyFrom(rec);
  2272. sen.encryptMessage("テスト");
  2273. sen.sendCipherTextTo(rec);
  2274. rec.decryptReceivedCipherText();
  2275. }
  2276. catch (const string& str) {
  2277. cerr << str << endl;
  2278. return 1;
  2279. }
  2280. return 0;
  2281. }
  2282.  
Success #stdin #stdout 2.6s 27976KB
stdin
Standard input is empty
stdout
太郎「鍵のペアを作ります」
太郎「公開鍵=(n=842ff26d6f96c15782a4ea463774faaa4a895b8f3e631bc0490b4c8e3ffe11f9c133fae912e81a63e6576bca4add88fe9395137999f94a3da3f074d077b7928d, e=d4b95f1f1f2ceff5ea7ba70d45d9e50f)」
太郎「秘密鍵=(n=842ff26d6f96c15782a4ea463774faaa4a895b8f3e631bc0490b4c8e3ffe11f9c133fae912e81a63e6576bca4add88fe9395137999f94a3da3f074d077b7928d, e=30119a0157e86ea67bf7a3dc83d7f5992e96bda2f999f9d84f505e1650313bf3efa1b3d01aef19146cf33ebad002435f2131217a627ed7d689f5b552ec83289d)」

次郎「太郎の公開鍵を取得します」

次郎「メッセージを暗号化します」
次郎「メッセージ=テスト」
次郎「使用する鍵=(n=842ff26d6f96c15782a4ea463774faaa4a895b8f3e631bc0490b4c8e3ffe11f9c133fae912e81a63e6576bca4add88fe9395137999f94a3da3f074d077b7928d, e=d4b95f1f1f2ceff5ea7ba70d45d9e50f)」
次郎「暗号文=827ccee52289c8ff04bdbf1a4ef8f19d968509709f1454f822ec53e0eedcac7ae3f2e8c8cdb683ee0814db59c4690dbb192e83b102c16dcf8d83bd101b660e91」

次郎「太郎に暗号文を送信します」

太郎「次郎から暗号文を受信しました」
太郎「暗号文=827ccee52289c8ff04bdbf1a4ef8f19d968509709f1454f822ec53e0eedcac7ae3f2e8c8cdb683ee0814db59c4690dbb192e83b102c16dcf8d83bd101b660e91」

太郎「暗号文を復号化します」
太郎「使用する鍵=(n=842ff26d6f96c15782a4ea463774faaa4a895b8f3e631bc0490b4c8e3ffe11f9c133fae912e81a63e6576bca4add88fe9395137999f94a3da3f074d077b7928d, e=30119a0157e86ea67bf7a3dc83d7f5992e96bda2f999f9d84f505e1650313bf3efa1b3d01aef19146cf33ebad002435f2131217a627ed7d689f5b552ec83289d)」
太郎「メッセージ=テスト」