Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.bouncycastle.crypto.encodings;
  
  
this does your basic PKCS 1 v1.5 padding - whether or not you should be using this depends on your application - see PKCS1 Version 2 for details.
 
 public class PKCS1Encoding
     implements AsymmetricBlockCipher
 {
    
some providers fail to include the leading zero in PKCS1 encoded blocks. If you need to work with one of these set the system property org.bouncycastle.pkcs1.strict to false.

The system property is checked during construction of the encoding object, it is set to true by default.

 
     public static final String STRICT_LENGTH_ENABLED_PROPERTY = "org.bouncycastle.pkcs1.strict";
     
     private static final int HEADER_LENGTH = 10;
 
     private SecureRandom            random;
     private AsymmetricBlockCipher   engine;
     private boolean                 forEncryption;
     private boolean                 forPrivateKey;
     private boolean                 useStrictLength;
     private int                     pLen = -1;
     private byte[]                  fallback = null;

    
Basic constructor.

Parameters:
cipher
 
     public PKCS1Encoding(
         AsymmetricBlockCipher   cipher)
     {
         this. = cipher;
         this. = useStrict();
     }   

    
Constructor for decryption with a fixed plaintext length.

Parameters:
cipher The cipher to use for cryptographic operation.
pLen Length of the expected plaintext.
 
     public PKCS1Encoding(
         AsymmetricBlockCipher   cipher,
         int pLen)
     {
         this. = cipher;
         this. = useStrict();
         this. = pLen;
     }

Constructor for decryption with a fixed plaintext length and a fallback value that is returned, if the padding is incorrect.

Parameters:
cipher The cipher to use for cryptographic operation.
fallback The fallback value, we don't do an arraycopy here.
 
 	public PKCS1Encoding(
     	AsymmetricBlockCipher   cipher,
         byte[] fallback)
     {
     	this. = cipher;
     	this. = useStrict();
     	this. = fallback;
     	this. = fallback.length;
     }
         
 
     
     //
     // for J2ME compatibility
     //
     private boolean useStrict()
     {
         // required if security manager has been installed.
         String strict = (String)AccessController.doPrivileged(new PrivilegedAction()
         {
             public Object run()
             {
                 return System.getProperty();
             }
         });
        return strict == null || strict.equals("true");
    }
    {
        return ;
    }
    public void init(
        boolean             forEncryption,
        CipherParameters    param)
    {
        AsymmetricKeyParameter  kParam;
        if (param instanceof ParametersWithRandom)
        {
            ParametersWithRandom    rParam = (ParametersWithRandom)param;
            this. = rParam.getRandom();
            kParam = (AsymmetricKeyParameter)rParam.getParameters();
        }
        else
        {
            this. = new SecureRandom();
            kParam = (AsymmetricKeyParameter)param;
        }
        .init(forEncryptionparam);
        this. = kParam.isPrivate();
        this. = forEncryption;
    }
    public int getInputBlockSize()
    {
        int     baseBlockSize = .getInputBlockSize();
        if ()
        {
            return baseBlockSize - ;
        }
        else
        {
            return baseBlockSize;
        }
    }
    public int getOutputBlockSize()
    {
        int     baseBlockSize = .getOutputBlockSize();
        if ()
        {
            return baseBlockSize;
        }
        else
        {
            return baseBlockSize - ;
        }
    }
    public byte[] processBlock(
        byte[]  in,
        int     inOff,
        int     inLen)
        throws InvalidCipherTextException
    {
        if ()
        {
            return encodeBlock(ininOffinLen);
        }
        else
        {
            return decodeBlock(ininOffinLen);
        }
    }
    private byte[] encodeBlock(
        byte[]  in,
        int     inOff,
        int     inLen)
        throws InvalidCipherTextException
    {
        if (inLen > getInputBlockSize())
        {
            throw new IllegalArgumentException("input data too large");
        }
        
        byte[]  block = new byte[.getInputBlockSize()];
        if ()
        {
            block[0] = 0x01;                        // type code 1
            for (int i = 1; i != block.length - inLen - 1; i++)
            {
                block[i] = (byte)0xFF;
            }
        }
        else
        {
            .nextBytes(block);                // random fill
            block[0] = 0x02;                        // type code 2
            //
            // a zero byte marks the end of the padding, so all
            // the pad bytes must be non-zero.
            //
            for (int i = 1; i != block.length - inLen - 1; i++)
            {
                while (block[i] == 0)
                {
                    block[i] = (byte).nextInt();
                }
            }
        }
        block[block.length - inLen - 1] = 0x00;       // mark the end of the padding
        System.arraycopy(ininOffblockblock.length - inLeninLen);
        return .processBlock(block, 0, block.length);
    }
    
    
Checks if the argument is a correctly PKCS#1.5 encoded Plaintext for encryption.

Parameters:
encoded The Plaintext.
pLen Expected length of the plaintext.
Returns:
Either 0, if the encoding is correct, or -1, if it is incorrect.
	private static int checkPkcs1Encoding(byte[] encodedint pLen) {
		int correct = 0;
		/*
		 * Check if the first two bytes are 0 2
		 */
		correct |= (encoded[0] ^ 2);
		/*
		 * Now the padding check, check for no 0 byte in the padding
		 */
		int plen = encoded.length - (
				  pLen /* Lenght of the PMS */
				+  1 /* Final 0-byte before PMS */
		);
		for (int i = 1; i < pleni++) {
			int tmp = encoded[i];
			tmp |= tmp >> 1;
			tmp |= tmp >> 2;
			tmp |= tmp >> 4;
			correct |= (tmp & 1) - 1;
		}
		/*
		 * Make sure the padding ends with a 0 byte.
		 */
		correct |= encoded[encoded.length - (pLen +1)];
		/*
		 * Return 0 or 1, depending on the result.
		 */
		correct |= correct >> 1;
		correct |= correct >> 2;
		correct |= correct >> 4;
		return ~((correct & 1) - 1);
	}
    

    
Decode PKCS#1.5 encoding, and return a random value if the padding is not correct.

Parameters:
in The encrypted block.
inOff Offset in the encrypted block.
inLen Length of the encrypted block. //@param pLen Length of the desired output.
Returns:
The plaintext without padding, or a random value if the padding was incorrect.
Throws:
org.bouncycastle.crypto.InvalidCipherTextException
    private byte[] decodeBlockOrRandom(byte[] inint inOffint inLen)
        throws InvalidCipherTextException
    {
        if (!)
        {
            throw new InvalidCipherTextException("sorry, this method is only for decryption, not for signing");
        }
        byte[] block = .processBlock(ininOffinLen);
        byte[] random = null;
        if (this. == null)
        {
            random = new byte[this.];
            this..nextBytes(random);
        }
        else
        {
            random = ;
        }
		/*
		 * TODO: This is a potential dangerous side channel. However, you can
		 * fix this by changing the RSA engine in a way, that it will always
		 * return blocks of the same length and prepend them with 0 bytes if
		 * needed.
		 */
        if (block.length < getOutputBlockSize())
        {
            throw new InvalidCipherTextException("block truncated");
        }
		/*
		 * TODO: Potential side channel. Fix it by making the engine always
		 * return blocks of the correct length.
		 */
        if ( && block.length != .getOutputBlockSize())
        {
            throw new InvalidCipherTextException("block incorrect size");
        }
		/*
		 * Check the padding.
		 */
        int correct = PKCS1Encoding.checkPkcs1Encoding(blockthis.);
		/*
		 * Now, to a constant time constant memory copy of the decrypted value
		 * or the random value, depending on the validity of the padding.
		 */
        byte[] result = new byte[this.];
        for (int i = 0; i < this.i++)
        {
            result[i] = (byte)((block[i + (block.length - )] & (~correct)) | (random[i] & correct));
        }
        return result;
    }

    

Throws:
org.bouncycastle.crypto.InvalidCipherTextException if the decrypted block is not in PKCS1 format.
    private byte[] decodeBlock(
        byte[]  in,
        int     inOff,
        int     inLen)
        throws InvalidCipherTextException
    {
        /*
         * If the length of the expected plaintext is known, we use a constant-time decryption.
         * If the decryption fails, we return a random value.
         */
		if (this. != -1)
        {
    		return this.decodeBlockOrRandom(ininOffinLen);
    	}
    	
        byte[] block = .processBlock(ininOffinLen);
        if (block.length < getOutputBlockSize())
        {
            throw new InvalidCipherTextException("block truncated");
        }
        byte type = block[0];
        if ()
        {
            if (type != 2)
            {
                throw new InvalidCipherTextException("unknown block type");
            }
        }
        else
        {
            if (type != 1)
            {
                throw new InvalidCipherTextException("unknown block type");
            }
        }
        if ( && block.length != .getOutputBlockSize())
        {
            throw new InvalidCipherTextException("block incorrect size");
        }
        
        //
        // find and extract the message block.
        //
        int start;
        
        for (start = 1; start != block.lengthstart++)
        {
            byte pad = block[start];
            
            if (pad == 0)
            {
                break;
            }
            if (type == 1 && pad != (byte)0xff)
            {
                throw new InvalidCipherTextException("block padding incorrect");
            }
        }
        start++;           // data should start at the next byte
        if (start > block.length || start < )
        {
            throw new InvalidCipherTextException("no data in block");
        }
        byte[]  result = new byte[block.length - start];
        System.arraycopy(blockstartresult, 0, result.length);
        return result;
    }
New to GrepCode? Check out our FAQ X