view dcrypt/crypto/padding/PKCS7.d @ 0:0e08791a1418

Initial import.
author Thomas Dixon <reikon@reikon.us>
date Sun, 10 Aug 2008 14:20:17 -0400
parents
children cd376996cdb3
line wrap: on
line source

/**
 * This file is part of the dcrypt project.
 *
 * Copyright: Copyright (C) dcrypt contributors 2008. All rights reserved.
 * License:   MIT
 * Authors:   Thomas Dixon
 */

module dcrypt.crypto.padding.PKCS7;

import dcrypt.crypto.BlockCipherPadding; 

/**
 * This class implements the padding scheme described in PKCS7
 * from RSA Security. Ex. [... 0x03, 0x03, 0x03]
 */
class PKCS7 : BlockCipherPadding {
    char[] name() {
        return "PKCS7";   
    }
    
    /* Assumes input_ is a multiple of the underlying
     * block cipher's block size.
     */
    uint padBlock(void[] input_, uint inOff) {
        ubyte[] input = cast(ubyte[]) input_;

        ubyte len = (input.length - inOff);
        
        input[inOff..input.length] = len;

        return len;
    }
    
    uint padLength(void[] input_) {
        ubyte[] input = cast(ubyte[]) input_;
        
        ubyte len = input[input.length-1];
         
        if (len > input.length || len == 0)
            throw new InvalidPaddingError(name()~": Incorrect padding.");
        
        uint limit = input.length;
        for (int i = 0; i < len; i++)
            if (input[--limit] != len)
                throw new InvalidPaddingError(
                        name()~": Pad value does not match pad length.");
        return len;
    }
}