Cipher.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package com.security.cipher.sm;
  2. import java.math.BigInteger;
  3. import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
  4. import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
  5. import org.bouncycastle.crypto.params.ECPublicKeyParameters;
  6. import org.bouncycastle.math.ec.ECPoint;
  7. public class Cipher
  8. {
  9. private int ct;
  10. private ECPoint p2;
  11. private SM3Digest sm3keybase;
  12. private SM3Digest sm3c3;
  13. private byte key[];
  14. private byte keyOff;
  15. public Cipher()
  16. {
  17. this.ct = 1;
  18. this.key = new byte[32];
  19. this.keyOff = 0;
  20. }
  21. private void Reset()
  22. {
  23. this.sm3keybase = new SM3Digest();
  24. this.sm3c3 = new SM3Digest();
  25. byte p[] = Util.byteConvert32Bytes(p2.getX().toBigInteger());
  26. this.sm3keybase.update(p, 0, p.length);
  27. this.sm3c3.update(p, 0, p.length);
  28. p = Util.byteConvert32Bytes(p2.getY().toBigInteger());
  29. this.sm3keybase.update(p, 0, p.length);
  30. this.ct = 1;
  31. NextKey();
  32. }
  33. private void NextKey()
  34. {
  35. SM3Digest sm3keycur = new SM3Digest(this.sm3keybase);
  36. sm3keycur.update((byte) (ct >> 24 & 0xff));
  37. sm3keycur.update((byte) (ct >> 16 & 0xff));
  38. sm3keycur.update((byte) (ct >> 8 & 0xff));
  39. sm3keycur.update((byte) (ct & 0xff));
  40. sm3keycur.doFinal(key, 0);
  41. this.keyOff = 0;
  42. this.ct++;
  43. }
  44. public ECPoint Init_enc(SM2 sm2, ECPoint userKey)
  45. {
  46. AsymmetricCipherKeyPair key = sm2.ecc_key_pair_generator.generateKeyPair();
  47. ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters) key.getPrivate();
  48. ECPublicKeyParameters ecpub = (ECPublicKeyParameters) key.getPublic();
  49. BigInteger k = ecpriv.getD();
  50. ECPoint c1 = ecpub.getQ();
  51. this.p2 = userKey.multiply(k);
  52. Reset();
  53. return c1;
  54. }
  55. public void Encrypt(byte data[])
  56. {
  57. this.sm3c3.update(data, 0, data.length);
  58. for (int i = 0; i < data.length; i++)
  59. {
  60. if (keyOff == key.length)
  61. {
  62. NextKey();
  63. }
  64. data[i] ^= key[keyOff++];
  65. }
  66. }
  67. public void Init_dec(BigInteger userD, ECPoint c1)
  68. {
  69. this.p2 = c1.multiply(userD);
  70. Reset();
  71. }
  72. public void Decrypt(byte data[])
  73. {
  74. for (int i = 0; i < data.length; i++)
  75. {
  76. if (keyOff == key.length)
  77. {
  78. NextKey();
  79. }
  80. data[i] ^= key[keyOff++];
  81. }
  82. this.sm3c3.update(data, 0, data.length);
  83. }
  84. public void Dofinal(byte c3[])
  85. {
  86. byte p[] = Util.byteConvert32Bytes(p2.getY().toBigInteger());
  87. this.sm3c3.update(p, 0, p.length);
  88. this.sm3c3.doFinal(c3, 0);
  89. Reset();
  90. }
  91. }