You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

XOREncryptor.java 6.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.poifs.crypt.xor;
  16. import java.io.File;
  17. import java.io.IOException;
  18. import java.io.OutputStream;
  19. import java.security.GeneralSecurityException;
  20. import javax.crypto.Cipher;
  21. import javax.crypto.spec.SecretKeySpec;
  22. import com.zaxxer.sparsebits.SparseBitSet;
  23. import org.apache.poi.EncryptedDocumentException;
  24. import org.apache.poi.poifs.crypt.ChunkedCipherOutputStream;
  25. import org.apache.poi.poifs.crypt.CryptoFunctions;
  26. import org.apache.poi.poifs.crypt.Encryptor;
  27. import org.apache.poi.poifs.filesystem.DirectoryNode;
  28. import org.apache.poi.util.LittleEndian;
  29. public class XOREncryptor extends Encryptor {
  30. protected XOREncryptor() {}
  31. protected XOREncryptor(XOREncryptor other) {
  32. super(other);
  33. }
  34. @Override
  35. public void confirmPassword(String password) {
  36. int keyComp = CryptoFunctions.createXorKey1(password);
  37. int verifierComp = CryptoFunctions.createXorVerifier1(password);
  38. byte[] xorArray = CryptoFunctions.createXorArray1(password);
  39. byte[] shortBuf = new byte[2];
  40. XOREncryptionVerifier ver = (XOREncryptionVerifier)getEncryptionInfo().getVerifier();
  41. LittleEndian.putUShort(shortBuf, 0, keyComp);
  42. ver.setEncryptedKey(shortBuf);
  43. LittleEndian.putUShort(shortBuf, 0, verifierComp);
  44. ver.setEncryptedVerifier(shortBuf);
  45. setSecretKey(new SecretKeySpec(xorArray, "XOR"));
  46. }
  47. @Override
  48. public void confirmPassword(String password, byte[] keySpec,
  49. byte[] keySalt, byte[] verifier, byte[] verifierSalt,
  50. byte[] integritySalt) {
  51. confirmPassword(password);
  52. }
  53. @Override
  54. public OutputStream getDataStream(DirectoryNode dir)
  55. throws IOException, GeneralSecurityException {
  56. return new XORCipherOutputStream(dir);
  57. }
  58. @Override
  59. public XORCipherOutputStream getDataStream(OutputStream stream, int initialOffset)
  60. throws IOException, GeneralSecurityException {
  61. return new XORCipherOutputStream(stream, initialOffset);
  62. }
  63. protected int getKeySizeInBytes() {
  64. return -1;
  65. }
  66. @Override
  67. public void setChunkSize(int chunkSize) {
  68. // chunkSize is irrelevant
  69. }
  70. @Override
  71. public XOREncryptor copy() {
  72. return new XOREncryptor(this);
  73. }
  74. private class XORCipherOutputStream extends ChunkedCipherOutputStream {
  75. private int recordStart;
  76. private int recordEnd;
  77. public XORCipherOutputStream(OutputStream stream, int initialPos) throws IOException, GeneralSecurityException {
  78. super(stream, -1);
  79. }
  80. public XORCipherOutputStream(DirectoryNode dir) throws IOException, GeneralSecurityException {
  81. super(dir, -1);
  82. }
  83. @Override
  84. protected Cipher initCipherForBlock(Cipher cipher, int block, boolean lastChunk)
  85. throws GeneralSecurityException {
  86. return XORDecryptor.initCipherForBlock(cipher, block, getEncryptionInfo(), getSecretKey(), Cipher.ENCRYPT_MODE);
  87. }
  88. @Override
  89. protected void calculateChecksum(File file, int i) {
  90. }
  91. @Override
  92. protected void createEncryptionInfoEntry(DirectoryNode dir, File tmpFile) {
  93. throw new EncryptedDocumentException("createEncryptionInfoEntry not supported");
  94. }
  95. @Override
  96. public void setNextRecordSize(int recordSize, boolean isPlain) {
  97. if (recordEnd > 0 && !isPlain) {
  98. // encrypt last record
  99. invokeCipher((int)getPos(), true);
  100. }
  101. recordStart = (int)getTotalPos()+4;
  102. recordEnd = recordStart+recordSize;
  103. }
  104. @Override
  105. public void flush() throws IOException {
  106. setNextRecordSize(0, true);
  107. super.flush();
  108. }
  109. @Override
  110. protected int invokeCipher(int posInChunk, boolean doFinal) {
  111. if (posInChunk == 0) {
  112. return 0;
  113. }
  114. final int start = Math.max(posInChunk-(recordEnd-recordStart), 0);
  115. final SparseBitSet plainBytes = getPlainByteFlags();
  116. final byte[] xorArray = getEncryptionInfo().getEncryptor().getSecretKey().getEncoded();
  117. final byte[] chunk = getChunk();
  118. final byte[] plain = (plainBytes.isEmpty()) ? null : chunk.clone();
  119. /*
  120. * From: http://social.msdn.microsoft.com/Forums/en-US/3dadbed3-0e68-4f11-8b43-3a2328d9ebd5
  121. *
  122. * The initial value for XorArrayIndex is as follows:
  123. * XorArrayIndex = (FileOffset + Data.Length) % 16
  124. *
  125. * The FileOffset variable in this context is the stream offset into the Workbook stream at
  126. * the time we are about to write each of the bytes of the record data.
  127. * This (the value) is then incremented after each byte is written.
  128. */
  129. // ... also need to handle invocation in case of a filled chunk
  130. int xorArrayIndex = recordEnd+(start-recordStart);
  131. for (int i=start; i < posInChunk; i++) {
  132. byte value = chunk[i];
  133. value ^= xorArray[(xorArrayIndex++) & 0x0F];
  134. value = rotateLeft(value, 8-3);
  135. chunk[i] = value;
  136. }
  137. if (plain != null) {
  138. int i = plainBytes.nextSetBit(start);
  139. while (i >= 0 && i < posInChunk) {
  140. chunk[i] = plain[i];
  141. i = plainBytes.nextSetBit(i + 1);
  142. }
  143. }
  144. return posInChunk;
  145. }
  146. private byte rotateLeft(byte bits, int shift) {
  147. return (byte)(((bits & 0xff) << shift) | ((bits & 0xff) >>> (8 - shift)));
  148. }
  149. }
  150. }