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.

StandardDecryptor.java 6.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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.standard;
  16. import static org.apache.poi.poifs.crypt.CryptoFunctions.hashPassword;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.security.GeneralSecurityException;
  20. import java.security.MessageDigest;
  21. import java.util.Arrays;
  22. import javax.crypto.Cipher;
  23. import javax.crypto.CipherInputStream;
  24. import javax.crypto.SecretKey;
  25. import javax.crypto.spec.SecretKeySpec;
  26. import org.apache.poi.EncryptedDocumentException;
  27. import org.apache.poi.poifs.crypt.ChainingMode;
  28. import org.apache.poi.poifs.crypt.CryptoFunctions;
  29. import org.apache.poi.poifs.crypt.Decryptor;
  30. import org.apache.poi.poifs.crypt.EncryptionHeader;
  31. import org.apache.poi.poifs.crypt.EncryptionVerifier;
  32. import org.apache.poi.poifs.crypt.HashAlgorithm;
  33. import org.apache.poi.poifs.filesystem.DirectoryNode;
  34. import org.apache.poi.poifs.filesystem.DocumentInputStream;
  35. import org.apache.commons.io.input.BoundedInputStream;
  36. import org.apache.poi.util.LittleEndian;
  37. /**
  38. */
  39. public class StandardDecryptor extends Decryptor {
  40. private long _length = -1;
  41. protected StandardDecryptor() {}
  42. protected StandardDecryptor(StandardDecryptor other) {
  43. super(other);
  44. _length = other._length;
  45. }
  46. @Override
  47. public boolean verifyPassword(String password) {
  48. EncryptionVerifier ver = getEncryptionInfo().getVerifier();
  49. SecretKey skey = generateSecretKey(password, ver, getKeySizeInBytes());
  50. Cipher cipher = getCipher(skey);
  51. try {
  52. byte[] encryptedVerifier = ver.getEncryptedVerifier();
  53. byte[] verifier = cipher.doFinal(encryptedVerifier);
  54. setVerifier(verifier);
  55. MessageDigest sha1 = CryptoFunctions.getMessageDigest(ver.getHashAlgorithm());
  56. byte[] calcVerifierHash = sha1.digest(verifier);
  57. byte[] encryptedVerifierHash = ver.getEncryptedVerifierHash();
  58. byte[] decryptedVerifierHash = cipher.doFinal(encryptedVerifierHash);
  59. // see 2.3.4.9 Password Verification (Standard Encryption)
  60. // ... The number of bytes used by the encrypted Verifier hash MUST be 32 ...
  61. // TODO: check and trim/pad the hashes to 32
  62. byte[] verifierHash = Arrays.copyOf(decryptedVerifierHash, calcVerifierHash.length);
  63. if (Arrays.equals(calcVerifierHash, verifierHash)) {
  64. setSecretKey(skey);
  65. return true;
  66. } else {
  67. return false;
  68. }
  69. } catch (GeneralSecurityException e) {
  70. throw new EncryptedDocumentException(e);
  71. }
  72. }
  73. protected static SecretKey generateSecretKey(String password, EncryptionVerifier ver, int keySize) {
  74. HashAlgorithm hashAlgo = ver.getHashAlgorithm();
  75. byte[] pwHash = hashPassword(password, hashAlgo, ver.getSalt(), ver.getSpinCount());
  76. byte[] blockKey = new byte[4];
  77. LittleEndian.putInt(blockKey, 0, 0);
  78. byte[] finalHash = CryptoFunctions.generateKey(pwHash, hashAlgo, blockKey, hashAlgo.hashSize);
  79. byte[] x1 = fillAndXor(finalHash, (byte) 0x36);
  80. byte[] x2 = fillAndXor(finalHash, (byte) 0x5c);
  81. byte[] x3 = new byte[x1.length + x2.length];
  82. System.arraycopy(x1, 0, x3, 0, x1.length);
  83. System.arraycopy(x2, 0, x3, x1.length, x2.length);
  84. byte[] key = Arrays.copyOf(x3, keySize);
  85. return new SecretKeySpec(key, ver.getCipherAlgorithm().jceId);
  86. }
  87. protected static byte[] fillAndXor(byte[] hash, byte fillByte) {
  88. byte[] buff = new byte[64];
  89. Arrays.fill(buff, fillByte);
  90. for (int i=0; i<hash.length; i++) {
  91. buff[i] = (byte) (buff[i] ^ hash[i]);
  92. }
  93. MessageDigest sha1 = CryptoFunctions.getMessageDigest(HashAlgorithm.sha1);
  94. return sha1.digest(buff);
  95. }
  96. private Cipher getCipher(SecretKey key) {
  97. EncryptionHeader em = getEncryptionInfo().getHeader();
  98. ChainingMode cm = em.getChainingMode();
  99. assert(cm == ChainingMode.ecb);
  100. return CryptoFunctions.getCipher(key, em.getCipherAlgorithm(), cm, null, Cipher.DECRYPT_MODE);
  101. }
  102. @Override
  103. @SuppressWarnings({"resource", "squid:S2095"})
  104. public InputStream getDataStream(DirectoryNode dir) throws IOException {
  105. DocumentInputStream dis = dir.createDocumentInputStream(DEFAULT_POIFS_ENTRY);
  106. _length = dis.readLong();
  107. if(getSecretKey() == null) {
  108. verifyPassword(null);
  109. }
  110. // limit wrong calculated ole entries - (bug #57080)
  111. // standard encryption always uses aes encoding, so blockSize is always 16
  112. int blockSize = getEncryptionInfo().getHeader().getCipherAlgorithm().blockSize;
  113. long cipherLen = (_length/blockSize + 1) * blockSize;
  114. Cipher cipher = getCipher(getSecretKey());
  115. InputStream boundedDis = new BoundedInputStream(dis, cipherLen);
  116. return new BoundedInputStream(new CipherInputStream(boundedDis, cipher), _length);
  117. }
  118. /**
  119. * @return the length of the stream returned by {@link #getDataStream(DirectoryNode)}
  120. */
  121. @Override
  122. public long getLength(){
  123. if(_length == -1) {
  124. throw new IllegalStateException("Decryptor.getDataStream() was not called");
  125. }
  126. return _length;
  127. }
  128. @Override
  129. public StandardDecryptor copy() {
  130. return new StandardDecryptor(this);
  131. }
  132. }