RSACipherImpl.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /* RSACipherImpl.java --
  2. Copyright (C) 2005, 2006 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package gnu.javax.crypto;
  32. import gnu.classpath.debug.Component;
  33. import gnu.classpath.debug.SystemLogger;
  34. import gnu.java.security.sig.rsa.EME_PKCS1_V1_5;
  35. import gnu.java.security.util.ByteArray;
  36. import java.math.BigInteger;
  37. import java.security.AlgorithmParameters;
  38. import java.security.InvalidKeyException;
  39. import java.security.Key;
  40. import java.security.NoSuchAlgorithmException;
  41. import java.security.SecureRandom;
  42. import java.security.interfaces.RSAKey;
  43. import java.security.interfaces.RSAPrivateCrtKey;
  44. import java.security.interfaces.RSAPrivateKey;
  45. import java.security.interfaces.RSAPublicKey;
  46. import java.security.spec.AlgorithmParameterSpec;
  47. import javax.crypto.BadPaddingException;
  48. import javax.crypto.Cipher;
  49. import javax.crypto.CipherSpi;
  50. import javax.crypto.IllegalBlockSizeException;
  51. import javax.crypto.NoSuchPaddingException;
  52. import javax.crypto.ShortBufferException;
  53. public class RSACipherImpl
  54. extends CipherSpi
  55. {
  56. private static final SystemLogger logger = SystemLogger.SYSTEM;
  57. private static final byte[] EMPTY = new byte[0];
  58. private int opmode = -1;
  59. private RSAPrivateKey decipherKey = null;
  60. private RSAPublicKey blindingKey = null;
  61. private RSAPublicKey encipherKey = null;
  62. private SecureRandom random = null;
  63. private byte[] dataBuffer = null;
  64. private int pos = 0;
  65. protected void engineSetMode(String mode) throws NoSuchAlgorithmException
  66. {
  67. throw new NoSuchAlgorithmException("only one mode available");
  68. }
  69. protected void engineSetPadding(String pad) throws NoSuchPaddingException
  70. {
  71. throw new NoSuchPaddingException("only one padding available");
  72. }
  73. protected int engineGetBlockSize()
  74. {
  75. return 1;
  76. }
  77. protected int engineGetOutputSize(int inputLen)
  78. {
  79. int outputLen = 0;
  80. if (decipherKey != null)
  81. outputLen = (decipherKey.getModulus().bitLength() + 7) / 8;
  82. else if (encipherKey != null)
  83. outputLen = (encipherKey.getModulus().bitLength() + 7) / 8;
  84. else
  85. throw new IllegalStateException("not initialized");
  86. if (inputLen > outputLen)
  87. throw new IllegalArgumentException("not configured to encode " + inputLen
  88. + "bytes; at most " + outputLen);
  89. return outputLen;
  90. }
  91. protected int engineGetKeySize(final Key key) throws InvalidKeyException
  92. {
  93. if (! (key instanceof RSAKey))
  94. throw new InvalidKeyException("not an RSA key");
  95. return ((RSAKey) key).getModulus().bitLength();
  96. }
  97. protected byte[] engineGetIV()
  98. {
  99. return null;
  100. }
  101. protected AlgorithmParameters engineGetParameters()
  102. {
  103. return null;
  104. }
  105. protected void engineInit(int opmode, Key key, SecureRandom random)
  106. throws InvalidKeyException
  107. {
  108. int outputLen = 0;
  109. if (opmode == Cipher.ENCRYPT_MODE)
  110. {
  111. if (! (key instanceof RSAPublicKey))
  112. throw new InvalidKeyException("expecting a RSAPublicKey");
  113. encipherKey = (RSAPublicKey) key;
  114. decipherKey = null;
  115. blindingKey = null;
  116. outputLen = (encipherKey.getModulus().bitLength() + 7) / 8;
  117. }
  118. else if (opmode == Cipher.DECRYPT_MODE)
  119. {
  120. if (key instanceof RSAPrivateKey)
  121. {
  122. decipherKey = (RSAPrivateKey) key;
  123. encipherKey = null;
  124. blindingKey = null;
  125. outputLen = (decipherKey.getModulus().bitLength() + 7) / 8;
  126. }
  127. else if (key instanceof RSAPublicKey)
  128. {
  129. if (decipherKey == null)
  130. throw new IllegalStateException("must configure decryption key first");
  131. if (! decipherKey.getModulus().equals(((RSAPublicKey) key).getModulus()))
  132. throw new InvalidKeyException("blinding key is not compatible");
  133. blindingKey = (RSAPublicKey) key;
  134. return;
  135. }
  136. else
  137. throw new InvalidKeyException(
  138. "expecting either an RSAPrivateKey or an RSAPublicKey (for blinding)");
  139. }
  140. else
  141. throw new IllegalArgumentException("only encryption and decryption supported");
  142. this.random = random;
  143. this.opmode = opmode;
  144. pos = 0;
  145. dataBuffer = new byte[outputLen];
  146. }
  147. protected void engineInit(int opmode, Key key, AlgorithmParameterSpec spec,
  148. SecureRandom random) throws InvalidKeyException
  149. {
  150. engineInit(opmode, key, random);
  151. }
  152. protected void engineInit(int opmode, Key key, AlgorithmParameters params,
  153. SecureRandom random) throws InvalidKeyException
  154. {
  155. engineInit(opmode, key, random);
  156. }
  157. protected byte[] engineUpdate(byte[] in, int offset, int length)
  158. {
  159. if (opmode != Cipher.ENCRYPT_MODE && opmode != Cipher.DECRYPT_MODE)
  160. throw new IllegalStateException("not initialized");
  161. System.arraycopy(in, offset, dataBuffer, pos, length);
  162. pos += length;
  163. return EMPTY;
  164. }
  165. protected int engineUpdate(byte[] in, int offset, int length, byte[] out,
  166. int outOffset)
  167. {
  168. engineUpdate(in, offset, length);
  169. return 0;
  170. }
  171. protected byte[] engineDoFinal(byte[] in, int offset, int length)
  172. throws IllegalBlockSizeException, BadPaddingException
  173. {
  174. engineUpdate(in, offset, length);
  175. if (opmode == Cipher.DECRYPT_MODE)
  176. {
  177. BigInteger enc = new BigInteger (1, dataBuffer);
  178. byte[] dec = rsaDecrypt (enc);
  179. logger.log (Component.CRYPTO, "RSA: decryption produced\n{0}",
  180. new ByteArray (dec));
  181. EME_PKCS1_V1_5 pkcs = EME_PKCS1_V1_5.getInstance(decipherKey);
  182. byte[] result = pkcs.decode(dec);
  183. return result;
  184. }
  185. else
  186. {
  187. offset = dataBuffer.length - pos;
  188. if (offset < 3)
  189. throw new IllegalBlockSizeException("input is too large to encrypt");
  190. EME_PKCS1_V1_5 pkcs = EME_PKCS1_V1_5.getInstance(encipherKey);
  191. if (random == null)
  192. random = new SecureRandom();
  193. byte[] em = new byte[pos];
  194. System.arraycopy(dataBuffer, 0, em, 0, pos);
  195. byte[] dec = pkcs.encode(em, random);
  196. logger.log (Component.CRYPTO, "RSA: produced padded plaintext\n{0}",
  197. new ByteArray (dec));
  198. BigInteger x = new BigInteger (1, dec);
  199. BigInteger y = x.modPow (encipherKey.getPublicExponent (),
  200. encipherKey.getModulus ());
  201. byte[] enc = y.toByteArray ();
  202. if (enc[0] == 0x00)
  203. {
  204. byte[] tmp = new byte[enc.length - 1];
  205. System.arraycopy(enc, 1, tmp, 0, tmp.length);
  206. enc = tmp;
  207. }
  208. pos = 0;
  209. return enc;
  210. }
  211. }
  212. protected int engineDoFinal(byte[] out, int offset)
  213. throws ShortBufferException, IllegalBlockSizeException,
  214. BadPaddingException
  215. {
  216. byte[] result = engineDoFinal(EMPTY, 0, 0);
  217. if (out.length - offset < result.length)
  218. throw new ShortBufferException("need " + result.length + ", have "
  219. + (out.length - offset));
  220. System.arraycopy(result, 0, out, offset, result.length);
  221. return result.length;
  222. }
  223. protected int engineDoFinal(final byte[] input, final int offset,
  224. final int length, final byte[] output,
  225. final int outputOffset)
  226. throws ShortBufferException, IllegalBlockSizeException,
  227. BadPaddingException
  228. {
  229. byte[] result = engineDoFinal(input, offset, length);
  230. if (output.length - outputOffset < result.length)
  231. throw new ShortBufferException("need " + result.length + ", have "
  232. + (output.length - outputOffset));
  233. System.arraycopy(result, 0, output, outputOffset, result.length);
  234. return result.length;
  235. }
  236. /**
  237. * Decrypts the ciphertext, employing RSA blinding if possible.
  238. */
  239. private byte[] rsaDecrypt(BigInteger enc)
  240. {
  241. if (random == null)
  242. random = new SecureRandom();
  243. BigInteger n = decipherKey.getModulus();
  244. BigInteger r = null;
  245. BigInteger pubExp = null;
  246. if (blindingKey != null)
  247. pubExp = blindingKey.getPublicExponent();
  248. if (pubExp != null && (decipherKey instanceof RSAPrivateCrtKey))
  249. pubExp = ((RSAPrivateCrtKey) decipherKey).getPublicExponent();
  250. if (pubExp != null)
  251. {
  252. r = new BigInteger(n.bitLength() - 1, random);
  253. enc = r.modPow(pubExp, n).multiply(enc).mod(n);
  254. }
  255. BigInteger dec = enc.modPow(decipherKey.getPrivateExponent(), n);
  256. if (pubExp != null)
  257. {
  258. dec = dec.multiply (r.modInverse (n)).mod (n);
  259. }
  260. byte[] decb = dec.toByteArray();
  261. if (decb[0] != 0x00)
  262. {
  263. byte[] b = new byte[decb.length + 1];
  264. System.arraycopy(decb, 0, b, 1, decb.length);
  265. decb = b;
  266. }
  267. return decb;
  268. }
  269. }