Search in sources :

Example 1 with DataLengthException

use of com.github.zhenwei.core.crypto.DataLengthException in project LinLong-Java by zhenwei1108.

the class CramerShoupCoreEngine method convertInput.

public BigInteger convertInput(byte[] in, int inOff, int inLen) {
    if (inLen > (getInputBlockSize() + 1)) {
        throw new DataLengthException("input too large for Cramer Shoup cipher.");
    } else if (inLen == (getInputBlockSize() + 1) && forEncryption) {
        throw new DataLengthException("input too large for Cramer Shoup cipher.");
    }
    byte[] block;
    if (inOff != 0 || inLen != in.length) {
        block = new byte[inLen];
        System.arraycopy(in, inOff, block, 0, inLen);
    } else {
        block = in;
    }
    BigInteger res = new BigInteger(1, block);
    if (res.compareTo(key.getParameters().getP()) >= 0) {
        throw new DataLengthException("input too large for Cramer Shoup cipher.");
    }
    return res;
}
Also used : DataLengthException(com.github.zhenwei.core.crypto.DataLengthException) BigInteger(java.math.BigInteger)

Example 2 with DataLengthException

use of com.github.zhenwei.core.crypto.DataLengthException in project LinLong-Java by zhenwei1108.

the class ElGamalEngine method processBlock.

/**
 * Process a single block using the basic ElGamal algorithm.
 *
 * @param in    the input array.
 * @param inOff the offset into the input buffer where the data starts.
 * @param inLen the length of the data to be processed.
 * @return the result of the ElGamal process.
 * @throws DataLengthException the input block is too large.
 */
public byte[] processBlock(byte[] in, int inOff, int inLen) {
    if (key == null) {
        throw new IllegalStateException("ElGamal engine not initialised");
    }
    int maxLength = forEncryption ? (bitSize - 1 + 7) / 8 : getInputBlockSize();
    if (inLen > maxLength) {
        throw new DataLengthException("input too large for ElGamal cipher.\n");
    }
    BigInteger p = key.getParameters().getP();
    if (// decryption
    key instanceof ElGamalPrivateKeyParameters) {
        byte[] in1 = new byte[inLen / 2];
        byte[] in2 = new byte[inLen / 2];
        System.arraycopy(in, inOff, in1, 0, in1.length);
        System.arraycopy(in, inOff + in1.length, in2, 0, in2.length);
        BigInteger gamma = new BigInteger(1, in1);
        BigInteger phi = new BigInteger(1, in2);
        ElGamalPrivateKeyParameters priv = (ElGamalPrivateKeyParameters) key;
        // a shortcut, which generally relies on p being prime amongst other things.
        // if a problem with this shows up, check the p and g values!
        BigInteger m = gamma.modPow(p.subtract(ONE).subtract(priv.getX()), p).multiply(phi).mod(p);
        return BigIntegers.asUnsignedByteArray(m);
    } else // encryption
    {
        byte[] block;
        if (inOff != 0 || inLen != in.length) {
            block = new byte[inLen];
            System.arraycopy(in, inOff, block, 0, inLen);
        } else {
            block = in;
        }
        BigInteger input = new BigInteger(1, block);
        if (input.compareTo(p) >= 0) {
            throw new DataLengthException("input too large for ElGamal cipher.\n");
        }
        ElGamalPublicKeyParameters pub = (ElGamalPublicKeyParameters) key;
        int pBitLength = p.bitLength();
        BigInteger k = BigIntegers.createRandomBigInteger(pBitLength, random);
        while (k.equals(ZERO) || (k.compareTo(p.subtract(TWO)) > 0)) {
            k = BigIntegers.createRandomBigInteger(pBitLength, random);
        }
        BigInteger g = key.getParameters().getG();
        BigInteger gamma = g.modPow(k, p);
        BigInteger phi = input.multiply(pub.getY().modPow(k, p)).mod(p);
        byte[] out1 = gamma.toByteArray();
        byte[] out2 = phi.toByteArray();
        byte[] output = new byte[this.getOutputBlockSize()];
        if (out1.length > output.length / 2) {
            System.arraycopy(out1, 1, output, output.length / 2 - (out1.length - 1), out1.length - 1);
        } else {
            System.arraycopy(out1, 0, output, output.length / 2 - out1.length, out1.length);
        }
        if (out2.length > output.length / 2) {
            System.arraycopy(out2, 1, output, output.length - (out2.length - 1), out2.length - 1);
        } else {
            System.arraycopy(out2, 0, output, output.length - out2.length, out2.length);
        }
        return output;
    }
}
Also used : ElGamalPrivateKeyParameters(com.github.zhenwei.core.crypto.params.ElGamalPrivateKeyParameters) DataLengthException(com.github.zhenwei.core.crypto.DataLengthException) BigInteger(java.math.BigInteger) ElGamalPublicKeyParameters(com.github.zhenwei.core.crypto.params.ElGamalPublicKeyParameters)

Example 3 with DataLengthException

use of com.github.zhenwei.core.crypto.DataLengthException in project LinLong-Java by zhenwei1108.

the class NaccacheSternEngine method processBlock.

/**
 * Process a single Block using the Naccache-Stern algorithm.
 *
 * @see com.github.zhenwei.core.crypto.AsymmetricBlockCipher#processBlock(byte[], int, int)
 */
public byte[] processBlock(byte[] in, int inOff, int len) throws InvalidCipherTextException {
    if (key == null) {
        throw new IllegalStateException("NaccacheStern engine not initialised");
    }
    if (len > (getInputBlockSize() + 1)) {
        throw new DataLengthException("input too large for Naccache-Stern cipher.\n");
    }
    if (!forEncryption) {
        // At decryption make sure that we receive padded data blocks
        if (len < getInputBlockSize()) {
            throw new InvalidCipherTextException("BlockLength does not match modulus for Naccache-Stern cipher.\n");
        }
    }
    byte[] block;
    if (inOff != 0 || len != in.length) {
        block = new byte[len];
        System.arraycopy(in, inOff, block, 0, len);
    } else {
        block = in;
    }
    // transform input into BigInteger
    BigInteger input = new BigInteger(1, block);
    if (debug) {
        System.out.println("input as BigInteger: " + input);
    }
    byte[] output;
    if (forEncryption) {
        output = encrypt(input);
    } else {
        Vector plain = new Vector();
        NaccacheSternPrivateKeyParameters priv = (NaccacheSternPrivateKeyParameters) key;
        Vector primes = priv.getSmallPrimes();
        // Get Chinese Remainders of CipherText
        for (int i = 0; i < primes.size(); i++) {
            BigInteger exp = input.modPow(priv.getPhi_n().divide((BigInteger) primes.elementAt(i)), priv.getModulus());
            Vector al = lookup[i];
            if (lookup[i].size() != ((BigInteger) primes.elementAt(i)).intValue()) {
                if (debug) {
                    System.out.println("Prime is " + primes.elementAt(i) + ", lookup table has size " + al.size());
                }
                throw new InvalidCipherTextException("Error in lookup Array for " + ((BigInteger) primes.elementAt(i)).intValue() + ": Size mismatch. Expected ArrayList with length " + ((BigInteger) primes.elementAt(i)).intValue() + " but found ArrayList of length " + lookup[i].size());
            }
            int lookedup = al.indexOf(exp);
            if (lookedup == -1) {
                if (debug) {
                    System.out.println("Actual prime is " + primes.elementAt(i));
                    System.out.println("Decrypted value is " + exp);
                    System.out.println("LookupList for " + primes.elementAt(i) + " with size " + lookup[i].size() + " is: ");
                    for (int j = 0; j < lookup[i].size(); j++) {
                        System.out.println(lookup[i].elementAt(j));
                    }
                }
                throw new InvalidCipherTextException("Lookup failed");
            }
            plain.addElement(BigInteger.valueOf(lookedup));
        }
        BigInteger test = chineseRemainder(plain, primes);
        // Should not be used as an oracle, so reencrypt output to see
        // if it corresponds to input
        // this breaks probabilisic encryption, so disable it. Anyway, we do
        // use the first n primes for key generation, so it is pretty easy
        // to guess them. But as stated in the paper, this is not a security
        // breach. So we can just work with the correct sigma.
        // if (debug) {
        // System.out.println("Decryption is " + test);
        // }
        // if ((key.getG().modPow(test, key.getModulus())).equals(input)) {
        // output = test.toByteArray();
        // } else {
        // if(debug){
        // System.out.println("Engine seems to be used as an oracle,
        // returning null");
        // }
        // output = null;
        // }
        output = test.toByteArray();
    }
    return output;
}
Also used : InvalidCipherTextException(com.github.zhenwei.core.crypto.InvalidCipherTextException) DataLengthException(com.github.zhenwei.core.crypto.DataLengthException) BigInteger(java.math.BigInteger) NaccacheSternPrivateKeyParameters(com.github.zhenwei.core.crypto.params.NaccacheSternPrivateKeyParameters) Vector(java.util.Vector)

Example 4 with DataLengthException

use of com.github.zhenwei.core.crypto.DataLengthException in project LinLong-Java by zhenwei1108.

the class ECNRSigner method generateSignature.

// Section 7.2.5 ECSP-NR, pg 34
/**
 * generate a signature for the given message using the key we were initialised with.  Generally,
 * the order of the curve should be at least as long as the hash of the message of interest, and
 * with ECNR it *must* be at least as long.
 *
 * @param digest the digest to be signed.
 * @throws DataLengthException if the digest is longer than the key allows
 */
public BigInteger[] generateSignature(byte[] digest) {
    if (!this.forSigning) {
        throw new IllegalStateException("not initialised for signing");
    }
    BigInteger n = getOrder();
    BigInteger e = new BigInteger(1, digest);
    ECPrivateKeyParameters privKey = (ECPrivateKeyParameters) key;
    if (e.compareTo(n) >= 0) {
        throw new DataLengthException("input too large for ECNR key");
    }
    BigInteger r = null;
    BigInteger s = null;
    AsymmetricCipherKeyPair tempPair;
    do // generate r
    {
        // generate another, but very temporary, key pair using
        // the same EC parameters
        ECKeyPairGenerator keyGen = new ECKeyPairGenerator();
        keyGen.init(new ECKeyGenerationParameters(privKey.getParameters(), this.random));
        tempPair = keyGen.generateKeyPair();
        // BigInteger Vx = tempPair.getPublic().getW().getAffineX();
        // get temp's public key
        ECPublicKeyParameters V = (ECPublicKeyParameters) tempPair.getPublic();
        BigInteger Vx = V.getQ().getAffineXCoord().toBigInteger();
        r = Vx.add(e).mod(n);
    } while (r.equals(ECConstants.ZERO));
    // generate s
    // private key value
    BigInteger x = privKey.getD();
    // temp's private key value
    BigInteger u = ((ECPrivateKeyParameters) tempPair.getPrivate()).getD();
    s = u.subtract(r.multiply(x)).mod(n);
    BigInteger[] res = new BigInteger[2];
    res[0] = r;
    res[1] = s;
    return res;
}
Also used : ECKeyPairGenerator(com.github.zhenwei.core.crypto.generators.ECKeyPairGenerator) ECPrivateKeyParameters(com.github.zhenwei.core.crypto.params.ECPrivateKeyParameters) DataLengthException(com.github.zhenwei.core.crypto.DataLengthException) BigInteger(java.math.BigInteger) ECPublicKeyParameters(com.github.zhenwei.core.crypto.params.ECPublicKeyParameters) AsymmetricCipherKeyPair(com.github.zhenwei.core.crypto.AsymmetricCipherKeyPair) ECKeyGenerationParameters(com.github.zhenwei.core.crypto.params.ECKeyGenerationParameters)

Example 5 with DataLengthException

use of com.github.zhenwei.core.crypto.DataLengthException in project LinLong-Java by zhenwei1108.

the class OpenBSDBCrypt method decodeSaltString.

/*
   * decodes the bcrypt base 64 encoded SaltString
   *
   * @param         a 22 character Bcrypt base 64 encoded String
   * @return         the 16 byte salt
   * @exception     DataLengthException if the length
   *                 of parameter is not 22
   * @exception     InvalidArgumentException if the parameter
   *                 contains a value other than from Bcrypts base 64 encoding table
   */
private static byte[] decodeSaltString(String saltString) {
    char[] saltChars = saltString.toCharArray();
    ByteArrayOutputStream out = new ByteArrayOutputStream(16);
    byte b1, b2, b3, b4;
    if (// bcrypt salt must be 22 (16 bytes)
    saltChars.length != 22) {
        throw new DataLengthException("Invalid base64 salt length: " + saltChars.length + " , 22 required.");
    }
    // check String for invalid characters:
    for (int i = 0; i < saltChars.length; i++) {
        int value = saltChars[i];
        if (value > 122 || value < 46 || (value > 57 && value < 65)) {
            throw new IllegalArgumentException("Salt string contains invalid character: " + value);
        }
    }
    // Padding: add two '\u0000'
    char[] tmp = new char[22 + 2];
    System.arraycopy(saltChars, 0, tmp, 0, saltChars.length);
    saltChars = tmp;
    int len = saltChars.length;
    for (int i = 0; i < len; i += 4) {
        // suppress LGTM warnings index-out-of-bounds since the loop increments i by 4
        b1 = decodingTable[saltChars[i]];
        // lgtm [java/index-out-of-bounds]
        b2 = decodingTable[saltChars[i + 1]];
        // lgtm [java/index-out-of-bounds]
        b3 = decodingTable[saltChars[i + 2]];
        // lgtm [java/index-out-of-bounds]
        b4 = decodingTable[saltChars[i + 3]];
        out.write((b1 << 2) | (b2 >> 4));
        out.write((b2 << 4) | (b3 >> 2));
        out.write((b3 << 6) | b4);
    }
    byte[] saltBytes = out.toByteArray();
    // truncate:
    byte[] tmpSalt = new byte[16];
    System.arraycopy(saltBytes, 0, tmpSalt, 0, tmpSalt.length);
    saltBytes = tmpSalt;
    return saltBytes;
}
Also used : DataLengthException(com.github.zhenwei.core.crypto.DataLengthException) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Aggregations

DataLengthException (com.github.zhenwei.core.crypto.DataLengthException)19 OutputLengthException (com.github.zhenwei.core.crypto.OutputLengthException)6 BigInteger (java.math.BigInteger)6 BlockCipher (com.github.zhenwei.core.crypto.BlockCipher)3 BufferedBlockCipher (com.github.zhenwei.core.crypto.BufferedBlockCipher)3 InvalidCipherTextException (com.github.zhenwei.core.crypto.InvalidCipherTextException)3 ECPublicKeyParameters (com.github.zhenwei.core.crypto.params.ECPublicKeyParameters)2 DenseTernaryPolynomial (com.github.zhenwei.core.pqc.math.ntru.polynomial.DenseTernaryPolynomial)2 IntegerPolynomial (com.github.zhenwei.core.pqc.math.ntru.polynomial.IntegerPolynomial)2 Polynomial (com.github.zhenwei.core.pqc.math.ntru.polynomial.Polynomial)2 ProductFormPolynomial (com.github.zhenwei.core.pqc.math.ntru.polynomial.ProductFormPolynomial)2 SparseTernaryPolynomial (com.github.zhenwei.core.pqc.math.ntru.polynomial.SparseTernaryPolynomial)2 TernaryPolynomial (com.github.zhenwei.core.pqc.math.ntru.polynomial.TernaryPolynomial)2 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)2 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)1 DEROctetString (com.github.zhenwei.core.asn1.DEROctetString)1 DERSequence (com.github.zhenwei.core.asn1.DERSequence)1 DERTaggedObject (com.github.zhenwei.core.asn1.DERTaggedObject)1 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)1 AsymmetricCipherKeyPair (com.github.zhenwei.core.crypto.AsymmetricCipherKeyPair)1