logo
down
shadow

winzipaes is slow to decrypt a 10 MB file on Android


winzipaes is slow to decrypt a 10 MB file on Android

By : Jiri
Date : November 19 2020, 01:01 AM
Hope this helps Yes, there are ways to speed this up as the source code of winzipaes uses a rather inefficient way of decrypting: it decrypt each block by calculating the IV and initializing the cipher (for CTR mode decryption). This could mean that the key gets reinitialized too often. Furthermore, handling data in blocks of 16 bytes is not very efficient either. This is mainly due to the fact that the AES-CTR as performed by WinZip uses a little endian counter instead of a big endian counter (as standardized).
The decryption also seems to include calculation of a HMAC-SHA1 over the ciphertext, which will add significant overhead as well. If you only require confidentiality of stored text then you may skip that step, although a MAC does have significant security advantages, providing cryptographically secure integrity as well as authenticity.
code :
/**
 * Adapter for bouncy castle crypto implementation (decryption).
 *
 * @author olaf@merkert.de
 * @author owlstead
 */
public class AESDecrypterOwlstead extends AESCryptoBase implements AESDecrypter {


    private final boolean verify;

    public AESDecrypterOwlstead(boolean verify) {
        this.verify = verify;
    }

    // TODO consider keySize (but: we probably need to adapt the key size for the zip file as well)
    public void init( String pwStr, int keySize, byte[] salt, byte[] pwVerification ) throws ZipException {
        byte[] pwBytes = pwStr.getBytes();

        super.saltBytes = salt;

        PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
        generator.init( pwBytes, salt, ITERATION_COUNT );

        cipherParameters = generator.generateDerivedParameters(KEY_SIZE_BIT*2 + 16);
        byte[] keyBytes = ((KeyParameter)cipherParameters).getKey();

        this.cryptoKeyBytes = new byte[ KEY_SIZE_BYTE ];
        System.arraycopy( keyBytes, 0, cryptoKeyBytes, 0, KEY_SIZE_BYTE );

        this.authenticationCodeBytes = new byte[ KEY_SIZE_BYTE ];
        System.arraycopy( keyBytes, KEY_SIZE_BYTE, authenticationCodeBytes, 0, KEY_SIZE_BYTE );

        // based on SALT + PASSWORD (password is probably correct)
        this.pwVerificationBytes = new byte[ 2 ];
        System.arraycopy( keyBytes, KEY_SIZE_BYTE*2, this.pwVerificationBytes, 0, 2 );

        if( !ByteArrayHelper.isEqual( this.pwVerificationBytes, pwVerification ) ) {
            throw new ZipException("wrong password - " + ByteArrayHelper.toString(this.pwVerificationBytes) + "/ " + ByteArrayHelper.toString(pwVerification));
        }

        cipherParameters = new KeyParameter(cryptoKeyBytes);

        // checksum added to the end of the encrypted data, update on each encryption call

        if (this.verify) {
            this.mac = new HMac( new SHA1Digest() );
            this.mac.init( new KeyParameter(authenticationCodeBytes) );
        }

        this.aesCipher = new SICZIPBlockCipher(new AESFastEngine());
        this.blockSize = aesCipher.getBlockSize();

        // incremented on each 16 byte block and used as encryption NONCE (ivBytes)

        // warning: non-CTR; little endian IV and starting with 1 instead of 0

        nonce = 1;

        byte[] ivBytes = ByteArrayHelper.toByteArray( nonce, 16 );

        ParametersWithIV ivParams = new ParametersWithIV(cipherParameters, ivBytes);
        aesCipher.init( false, ivParams );
    }

    // --------------------------------------------------------------------------

    protected CipherParameters cipherParameters;

    protected SICZIPBlockCipher aesCipher;

    protected HMac mac;


    @Override
    public void decrypt(byte[] in, int length) {
        if (verify) {
            mac.update(in, 0, length);
        }
        aesCipher.processBytes(in, 0, length, in, 0);
    }

    public byte[] getFinalAuthentication() {
        if (!verify) {
            return null;
        }
        byte[] macBytes = new byte[ mac.getMacSize() ];
        mac.doFinal( macBytes, 0 );
        byte[] macBytes10 = new byte[10];
        System.arraycopy( macBytes, 0, macBytes10, 0, 10 );
        return macBytes10;
    }
}
/**
 * Implements the Segmented Integer Counter (SIC) mode on top of a simple
 * block cipher. This mode is also known as CTR mode. This CTR mode
 * was altered to comply with the ZIP little endian counter and
 * different starting point.
 */
public class SICZIPBlockCipher
    extends StreamBlockCipher
    implements SkippingStreamCipher
{
    private final BlockCipher     cipher;
    private final int             blockSize;

    private byte[]          IV;
    private byte[]          counter;
    private byte[]          counterOut;
    private int             byteCount;

    /**
     * Basic constructor.
     *
     * @param c the block cipher to be used.
     */
    public SICZIPBlockCipher(BlockCipher c)
    {
        super(c);

        this.cipher = c;
        this.blockSize = cipher.getBlockSize();
        this.IV = new byte[blockSize];
        this.counter = new byte[blockSize];
        this.counterOut = new byte[blockSize];
        this.byteCount = 0;
    }

    public void init(
        boolean             forEncryption, //ignored by this CTR mode
        CipherParameters    params)
        throws IllegalArgumentException
    {
        if (params instanceof ParametersWithIV)
        {
            ParametersWithIV ivParam = (ParametersWithIV)params;
            byte[] iv = ivParam.getIV();
            System.arraycopy(iv, 0, IV, 0, IV.length);

            // if null it's an IV changed only.
            if (ivParam.getParameters() != null)
            {
                cipher.init(true, ivParam.getParameters());
            }

            reset();
        }
        else
        {
            throw new IllegalArgumentException("SICZIP mode requires ParametersWithIV");
        }
    }

    public String getAlgorithmName()
    {
        return cipher.getAlgorithmName() + "/SICZIP";
    }

    public int getBlockSize()
    {
        return cipher.getBlockSize();
    }

    public int processBlock(byte[] in, int inOff, byte[] out, int outOff)
          throws DataLengthException, IllegalStateException
    {
        processBytes(in, inOff, blockSize, out, outOff);

        return blockSize;
    }

    protected byte calculateByte(byte in)
          throws DataLengthException, IllegalStateException
    {
        if (byteCount == 0)
        {
            cipher.processBlock(counter, 0, counterOut, 0);

            return (byte)(counterOut[byteCount++] ^ in);
        }

        byte rv = (byte)(counterOut[byteCount++] ^ in);

        if (byteCount == counter.length)
        {
            byteCount = 0;

            incrementCounter();
        }

        return rv;
    }

    private void incrementCounter()
    {
        // increment counter by 1.
        for (int i = 0; i < counter.length && ++counter[i] == 0; i++)
        {
            ; // do nothing - pre-increment and test for 0 in counter does the job.
        }
    }

    private void decrementCounter()
    {
        // TODO test - owlstead too lazy to test

        if (counter[counter.length - 1] == 0)
        {
            boolean nonZero = false;

            for (int i = 0; i < counter.length; i++)
            {
                if (counter[i] != 0)
                {
                    nonZero = true;
                }
            }

            if (!nonZero)
            {
                throw new IllegalStateException("attempt to reduce counter past zero.");
            }
        }

        // decrement counter by 1.
        for (int i = 0; i < counter.length && --counter[i] == -1; i++)
        {
            ;
        }
    }

    private void adjustCounter(long n)
    {
        if (n >= 0)
        {
            long numBlocks = (n + byteCount) / blockSize;

            for (long i = 0; i != numBlocks; i++)
            {
                incrementCounter();
            }

            byteCount = (int)((n + byteCount) - (blockSize * numBlocks));
        }
        else
        {
            long numBlocks = (-n - byteCount) / blockSize;

            for (long i = 0; i != numBlocks; i++)
            {
                decrementCounter();
            }

            int gap = (int)(byteCount + n + (blockSize * numBlocks));

            if (gap >= 0)
            {
                byteCount = 0;
            }
            else
            {
                decrementCounter();
                byteCount =  blockSize + gap;
            }
        }
    }

    public void reset()
    {
        System.arraycopy(IV, 0, counter, 0, counter.length);
        cipher.reset();
        this.byteCount = 0;
    }

    public long skip(long numberOfBytes)
    {
        adjustCounter(numberOfBytes);

        cipher.processBlock(counter, 0, counterOut, 0);

        return numberOfBytes;
    }

    public long seekTo(long position)
    {
        reset();

        return skip(position);
    }

    public long getPosition()
    {
        byte[] res = new byte[IV.length];

        System.arraycopy(counter, 0, res, 0, res.length);

        for (int i = 0; i < res.length; i++)
        {
            int v = (res[i] - IV[i]);

            if (v < 0)
            {
               res[i + 1]--;
               v += 256;
            }

            res[i] = (byte)v;
        }

        // TODO still broken - owlstead too lazy to fix for zip
        return Pack.bigEndianToLong(res, res.length - 8) * blockSize + byteCount;
    }
}


Share : facebook icon twitter icon
Decrypt a file in php which is encrypted in android

Decrypt a file in php which is encrypted in android


By : Shera
Date : March 29 2020, 07:55 AM
will help you So, it seems like you are going to have to use the mcrypt extension. The mcrypt extension supports TRIPLEDES.
Installation
Android- Is there a way to decrypt the apk file in MODE_PRIVATE

Android- Is there a way to decrypt the apk file in MODE_PRIVATE


By : Jhones Pereira
Date : March 29 2020, 07:55 AM
like below fixes the issue It looks like you are mixing things up. MODE_PRIVATE or in detail Context.MODE_PRIVATE is used if you want to create a file in the app's data directory.
Using MODE_PRIVATE doesn't make use of encryption at all, it simply sets the file access permissions so that only the app itself can access the file.
code :
FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
How do i decrypt a file in Android with AES?

How do i decrypt a file in Android with AES?


By : alvaro
Date : March 29 2020, 07:55 AM
With these it helps I have a file (mp3) that i Encrypt, my intention is then to download this file to an android device and decrypt it, but during decryption i get an IOException: , Here is the code:
code :
public class MainActivity extends Activity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);

          Button encryptButton = (Button) findViewById(R.id.button1);
          Button DecryptButton = (Button) findViewById(R.id.button2);
          encryptButton.setOnClickListener(new OnClickListener() {

                 @Override
                 public void onClick(View v) {
                       // TODO Auto-generated method stub
                       try {
                              encrypt();
                       } catch (InvalidKeyException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                       } catch (NoSuchAlgorithmException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                       } catch (NoSuchPaddingException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                       } catch (IOException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                       }
                 }
          });

          DecryptButton.setOnClickListener(new OnClickListener() {

                 @Override
                 public void onClick(View v) {
                       // TODO Auto-generated method stub
                       try {
                              decrypt();
                       } catch (InvalidKeyException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                       } catch (NoSuchAlgorithmException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                       } catch (NoSuchPaddingException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                       } catch (IOException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                       }
                 }
          });

   }

   /**
    * Here is Both function for encrypt and decrypt file in Sdcard folder. we
    * can not lock folder but we can encrypt file using AES in Android, it may
    * help you.
    *
    * @throws IOException
    * @throws NoSuchAlgorithmException
    * @throws NoSuchPaddingException
    * @throws InvalidKeyException
    */

   static void encrypt() throws IOException, NoSuchAlgorithmException,
                 NoSuchPaddingException, InvalidKeyException {
          // Here you read the cleartext.
          File extStore = Environment.getExternalStorageDirectory();
          FileInputStream fis = new FileInputStream(extStore + "/sampleFile");
          // This stream write the encrypted text. This stream will be wrapped by
          // another stream.
          FileOutputStream fos = new FileOutputStream(extStore + "/encrypted");

          // Length is 16 byte
          SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),
                       "AES");
          // Create cipher
          Cipher cipher = Cipher.getInstance("AES");
          cipher.init(Cipher.ENCRYPT_MODE, sks);
          // Wrap the output stream
          CipherOutputStream cos = new CipherOutputStream(fos, cipher);
          // Write bytes
          int b;
          byte[] d = new byte[8];
          while ((b = fis.read(d)) != -1) {
                 cos.write(d, 0, b);
          }
          // Flush and close streams.
          cos.flush();
          cos.close();
          fis.close();
   }

   static void decrypt() throws IOException, NoSuchAlgorithmException,
                 NoSuchPaddingException, InvalidKeyException {

          File extStore = Environment.getExternalStorageDirectory();
          FileInputStream fis = new FileInputStream(extStore + "/encrypted");

          FileOutputStream fos = new FileOutputStream(extStore + "/decrypted");
          SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),
                       "AES");
          Cipher cipher = Cipher.getInstance("AES");
          cipher.init(Cipher.DECRYPT_MODE, sks);
          CipherInputStream cis = new CipherInputStream(fis, cipher);
          int b;
          byte[] d = new byte[8];
          while ((b = cis.read(d)) != -1) {
                 fos.write(d, 0, b);
          }
          fos.flush();
          fos.close();
          cis.close();
   }

} 
How to encrypt file in c# and decrypt it on android and IOS

How to encrypt file in c# and decrypt it on android and IOS


By : Lola
Date : March 29 2020, 07:55 AM
help you fix your problem For cross encryption and decryption you can use XOR.Its pretty simple.
for IOS:
code :
+(NSString *) EncryptOrDecrypt:(NSString *)string {

NSString *key=@"Your_Key";

// Create data object from the string
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];

// Get pointer to data to obfuscate
char *dataPtr = (char *) [data bytes];

// Get pointer to key data
char *keyData = (char *) [[key dataUsingEncoding:NSUTF8StringEncoding] bytes];

// Points to each char in sequence in the key
char *keyPtr = keyData;
int keyIndex = 0;

// For each character in data, xor with current value in key
for (int x = 0; x < [data length]; x++)
{
    // Replace current character in data with
    // current character xor'd with current key value.
    // Bump each pointer to the next character
    *dataPtr = *dataPtr ^ *keyPtr;
    dataPtr++;
    keyPtr++;

    // If at end of key data, reset count and
    // set key pointer back to start of key value
    if (++keyIndex == [key length])
        keyIndex = 0, keyPtr = keyData;
}

return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
public static String EncryptOrDecrypt(String input) {
    char[] key = {'K', 'E', 'Y'}; //Your key in char array
    StringBuilder output = new StringBuilder();

    for(int i = 0; i < input.length(); i++) {
        output.append((char) (input.charAt(i) ^ key[i % key.length]));
    }

    return output.toString();
}
string EncryptOrDecrypt(string text, string key)//Your Key as parameter
{
var result = new StringBuilder();

for (int c = 0; c < text.Length; c++)
    result.Append((char)((uint)text[c] ^ (uint)key[c % key.Length]));

return result.ToString();
How to encrypt and decrypt file in Android?

How to encrypt and decrypt file in Android?


By : shakwat shamim
Date : March 29 2020, 07:55 AM
this one helps. Use a CipherOutputStream or CipherInputStream with a Cipher and your FileInputStream / FileOutputStream.
I would suggest something like Cipher.getInstance("AES/CBC/PKCS5Padding") for creating the Cipher class. CBC mode is secure and does not have the vulnerabilities of ECB mode for non-random plaintexts. It should be present in any generic cryptographic library, ensuring high compatibility.
Related Posts Related Posts :
  • Passing HttpServletResponse in Spring Boot controller method
  • Failed to load libraries: [netty_tcnative_linux_arm_32, netty_tcnative_linux_arm_32_fedora, netty_tcnative_arm_32, netty
  • How to build a small documents storage?
  • Getting pixel position of a text in an image
  • How do I get a list of Methods called from a Class in Eclipse IDE?
  • Convert string to day of week (not exact date)
  • Unable to understand how rounding is working for decimal digits (Java)
  • How to avoid java.lang.NoSuchMethodError: org.apache.poi.util.IOUtils.copy(Ljava/io/InputStream;Ljava/io/OutputStream;)
  • JTable Renderer not working with RowSorter?
  • From java.util.concurrent.Future<T> to play.libs.F.Promise<T>: How to do that in Java?
  • jUnit tests work in Eclipse, but fail in ant - java.lang.RuntimeException: Stub
  • How do i add a tooltip to existing gwt Textbox?
  • actor replying to non-actor
  • Google Cloud Messaging - server connection
  • Which classes are unmodifiable and cannot be intrumented and is there a way to bypass it?
  • Java & Jersey 1.17: Custom default response headers
  • Java rounding error
  • Setting custom RejectedExecutionHandler for ThreadPoolExecutor after executing some tasks?
  • Arquillian test class variables lose value
  • java.util.ConcurrentModificationException while inserting in ArrayList
  • How to write generic Java API without method Overloading
  • Java Serialization / Deserialization of an ArrayList works only on first program execution
  • Conway's Game of Life's rules dont apply properly
  • call a java method when Click on a html button without using javascript
  • Why does SSLSocketFactory.createSocket returns a Socket instead of SSLSocket?
  • How to schedule a task in Tomcat
  • compare two pdf files (approach) using java
  • What is the use of allowCoreThreadTimeout( ) in ThreadPoolExecutor?
  • Describe the Strategy Design Pattern in Java?
  • MongoDB too many open connections
  • Issue with generate JAXB classes with value constructors
  • Moving from one frame to another in java swing
  • Get a thread by Id
  • how to open front camera and back camera at same time?
  • Messed up with Java Declaration
  • Extracting chart in EXcel as image using java
  • How to get latitude and longitude in Android phone?
  • Do GC pauses and kill -STOP produce the same behavior?
  • Android HTML.ImageGetter Images resized
  • The way to instantiate map<String, List<String>> in Java
  • Java Making objects move while buttons held
  • Androidx Navigation View - `setNavigationItemSelectedListener` Doesn't Work
  • after compiling code JFrame does not appear
  • Netbeans project, JFrames ran from the main JFrame close all JFrames in project
  • Square Retrofit Client: How to enable/disable followRedirects? How to intercept redirect URL?
  • Java Circular Reference - Can’t Compile
  • Mouse click on specific time JAVA
  • android 4 onCreateDialog return type incompatible when overriding
  • Java Implementation of Oracle's DBMS_UTILITY.GET_HASH_VALUE Function
  • javac cannot be run, and furthermore does not seem installed
  • Function to obtain a thread given its ID
  • Java File path to Executable has spaces
  • Minimum Oracle Java VM heap memory setting?
  • Elegant way to create one of a large number of classes
  • Java fx binding styles
  • Summing weights based on string in large file
  • Android ListView setOnItemClickListener not working
  • How is the Java Bootstrap Classloader loaded?
  • Check object is blank
  • Add image between text in JEditorPane
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org