List of usage examples for org.bouncycastle.crypto.signers DSASigner init
public void init(boolean forSigning, CipherParameters param)
From source file:dorkbox.util.crypto.CryptoDSA.java
License:Apache License
/** * The message will have the SHA1 hash calculated and used for the signature. * <p/>//from w ww . java2 s .c o m * Note: this is here just for keeping track of how this is done. This should NOT be used, and instead use ECC crypto. * <p/> * The returned signature is the {r,s} signature array. */ public static BigInteger[] generateSignature(DSAPrivateKeyParameters privateKey, SecureRandom secureRandom, byte[] message) { ParametersWithRandom param = new ParametersWithRandom(privateKey, secureRandom); DSASigner dsa = new DSASigner(); dsa.init(true, param); SHA1Digest sha1Digest = new SHA1Digest(); byte[] checksum = new byte[sha1Digest.getDigestSize()]; sha1Digest.update(message, 0, message.length); sha1Digest.doFinal(checksum, 0); return dsa.generateSignature(checksum); }
From source file:dorkbox.util.crypto.CryptoDSA.java
License:Apache License
/** * The message will have the SHA1 hash calculated and used for the signature. * <p/>/* ww w. j a v a2s . com*/ * Note: this is here just for keeping track of how this is done. This should NOT be used, and instead use ECC crypto. * * @param signature * is the {r,s} signature array. * * @return true if the signature is valid */ public static boolean verifySignature(DSAPublicKeyParameters publicKey, byte[] message, BigInteger[] signature) { SHA1Digest sha1Digest = new SHA1Digest(); byte[] checksum = new byte[sha1Digest.getDigestSize()]; sha1Digest.update(message, 0, message.length); sha1Digest.doFinal(checksum, 0); DSASigner dsa = new DSASigner(); dsa.init(false, publicKey); return dsa.verifySignature(checksum, signature[0], signature[1]); }
From source file:freenet.keys.InsertableClientSSK.java
License:GNU General Public License
public ClientSSKBlock encode(Bucket sourceData, boolean asMetadata, boolean dontCompress, short alreadyCompressedCodec, long sourceLength, RandomSource r, String compressordescriptor, boolean pre1254) throws SSKEncodeException, IOException, InvalidCompressionCodecException { byte[] compressedData; short compressionAlgo; try {/*w w w . j ava2 s . c o m*/ Compressed comp = Key.compress(sourceData, dontCompress, alreadyCompressedCodec, sourceLength, ClientSSKBlock.MAX_DECOMPRESSED_DATA_LENGTH, SSKBlock.DATA_LENGTH, true, compressordescriptor, pre1254); compressedData = comp.compressedData; compressionAlgo = comp.compressionAlgorithm; } catch (KeyEncodeException e) { throw new SSKEncodeException(e.getMessage(), e); } // Pad it MessageDigest md256 = SHA256.getMessageDigest(); try { byte[] data; // First pad it if (compressedData.length != SSKBlock.DATA_LENGTH) { // Hash the data if (compressedData.length != 0) md256.update(compressedData); byte[] digest = md256.digest(); MersenneTwister mt = new MersenneTwister(digest); data = Arrays.copyOf(compressedData, SSKBlock.DATA_LENGTH); if (compressedData.length > data.length) { throw new RuntimeException( "compressedData.length = " + compressedData.length + " but data.length=" + data.length); } Util.randomBytes(mt, data, compressedData.length, SSKBlock.DATA_LENGTH - compressedData.length); } else { data = compressedData; } // Implicit hash of data byte[] origDataHash = md256.digest(data); Rijndael aes; try { aes = new Rijndael(256, 256); } catch (UnsupportedCipherException e) { throw new Error("256/256 Rijndael not supported!"); } // Encrypt data. Data encryption key = H(plaintext data). aes.initialize(origDataHash); PCFBMode pcfb = PCFBMode.create(aes, origDataHash); pcfb.blockEncipher(data, 0, data.length); byte[] encryptedDataHash = md256.digest(data); // Create headers byte[] headers = new byte[SSKBlock.TOTAL_HEADERS_LENGTH]; // First two bytes = hash ID int x = 0; headers[x++] = (byte) (KeyBlock.HASH_SHA256 >> 8); headers[x++] = (byte) (KeyBlock.HASH_SHA256); // Then crypto ID headers[x++] = (byte) (Key.ALGO_AES_PCFB_256_SHA256 >> 8); headers[x++] = Key.ALGO_AES_PCFB_256_SHA256; // Then E(H(docname)) // Copy to headers System.arraycopy(ehDocname, 0, headers, x, ehDocname.length); x += ehDocname.length; // Now the encrypted headers byte[] encryptedHeaders = Arrays.copyOf(origDataHash, SSKBlock.ENCRYPTED_HEADERS_LENGTH); int y = origDataHash.length; short len = (short) compressedData.length; if (asMetadata) len |= 32768; encryptedHeaders[y++] = (byte) (len >> 8); encryptedHeaders[y++] = (byte) len; encryptedHeaders[y++] = (byte) (compressionAlgo >> 8); encryptedHeaders[y++] = (byte) compressionAlgo; if (encryptedHeaders.length != y) throw new IllegalStateException("Have more bytes to generate encoding SSK"); aes.initialize(cryptoKey); pcfb.reset(ehDocname); pcfb.blockEncipher(encryptedHeaders, 0, encryptedHeaders.length); System.arraycopy(encryptedHeaders, 0, headers, x, encryptedHeaders.length); x += encryptedHeaders.length; // Generate implicit overall hash. md256.update(headers, 0, x); md256.update(encryptedDataHash); byte[] overallHash = md256.digest(); // Now sign it DSASigner dsa = new DSASigner(new HMacDSAKCalculator(new SHA256Digest())); dsa.init(true, new DSAPrivateKeyParameters(privKey.getX(), Global.getDSAgroupBigAParameters())); BigInteger[] sig = dsa.generateSignature(Global.truncateHash(overallHash)); // Pack R and S into 32 bytes each, and copy to headers. // Then create and return the ClientSSKBlock. byte[] rBuf = truncate(sig[0].toByteArray(), SSKBlock.SIG_R_LENGTH); byte[] sBuf = truncate(sig[1].toByteArray(), SSKBlock.SIG_S_LENGTH); System.arraycopy(rBuf, 0, headers, x, rBuf.length); x += rBuf.length; System.arraycopy(sBuf, 0, headers, x, sBuf.length); x += sBuf.length; if (x != SSKBlock.TOTAL_HEADERS_LENGTH) throw new IllegalStateException("Too long"); try { return new ClientSSKBlock(data, headers, this, !logMINOR); } catch (SSKVerifyException e) { throw (AssertionError) new AssertionError("Impossible encoding error").initCause(e); } } finally { SHA256.returnMessageDigest(md256); } }
From source file:freenet.keys.SSKBlock.java
License:GNU General Public License
/** * Initialize, and verify data, headers against key. Provided * key must have a pubkey, or we throw.//from w w w. j av a2s. co m */ public SSKBlock(byte[] data, byte[] headers, NodeSSK nodeKey, boolean dontVerify) throws SSKVerifyException { if (headers.length != TOTAL_HEADERS_LENGTH) throw new IllegalArgumentException( "Headers.length=" + headers.length + " should be " + TOTAL_HEADERS_LENGTH); this.data = data; this.headers = headers; this.nodeKey = nodeKey; if (data.length != DATA_LENGTH) throw new SSKVerifyException("Data length wrong: " + data.length + " should be " + DATA_LENGTH); this.pubKey = nodeKey.getPubKey(); if (pubKey == null) throw new SSKVerifyException("PubKey was null from " + nodeKey); // Now verify it hashIdentifier = (short) (((headers[0] & 0xff) << 8) + (headers[1] & 0xff)); if (hashIdentifier != HASH_SHA256) throw new SSKVerifyException("Hash not SHA-256"); int x = 2; symCipherIdentifier = (short) (((headers[x] & 0xff) << 8) + (headers[x + 1] & 0xff)); x += 2; // Then E(H(docname)) byte[] ehDocname = new byte[E_H_DOCNAME_LENGTH]; System.arraycopy(headers, x, ehDocname, 0, ehDocname.length); x += E_H_DOCNAME_LENGTH; headersOffset = x; // is index to start of encrypted headers x += ENCRYPTED_HEADERS_LENGTH; // Extract the signature if (x + SIG_R_LENGTH + SIG_S_LENGTH > headers.length) throw new SSKVerifyException("Headers too short: " + headers.length + " should be at least " + x + SIG_R_LENGTH + SIG_S_LENGTH); // Compute the hash on the data if (!dontVerify || logMINOR) { // force verify on log minor byte[] bufR = new byte[SIG_R_LENGTH]; byte[] bufS = new byte[SIG_S_LENGTH]; System.arraycopy(headers, x, bufR, 0, SIG_R_LENGTH); x += SIG_R_LENGTH; System.arraycopy(headers, x, bufS, 0, SIG_S_LENGTH); x += SIG_S_LENGTH; MessageDigest md = null; byte[] overallHash; try { md = SHA256.getMessageDigest(); md.update(data); byte[] dataHash = md.digest(); // All headers up to and not including the signature md.update(headers, 0, headersOffset + ENCRYPTED_HEADERS_LENGTH); // Then the implicit data hash md.update(dataHash); // Makes the implicit overall hash overallHash = md.digest(); } finally { SHA256.returnMessageDigest(md); } // Now verify it BigInteger r = new BigInteger(1, bufR); BigInteger s = new BigInteger(1, bufS); DSASigner dsa = new DSASigner(); dsa.init(false, new DSAPublicKeyParameters(pubKey.getY(), Global.getDSAgroupBigAParameters())); // We probably don't need to try both here... // but that's what the legacy code was doing... // @see comments in Global before touching it if (!(dsa.verifySignature(Global.truncateHash(overallHash), r, s) || dsa.verifySignature(overallHash, r, s))) { if (dontVerify) Logger.error(this, "DSA verification failed with dontVerify!!!!"); throw new SSKVerifyException("Signature verification failed for node-level SSK"); } } // x isn't verified otherwise so no need to += SIG_R_LENGTH + SIG_S_LENGTH if (!Arrays.equals(ehDocname, nodeKey.encryptedHashedDocname)) throw new SSKVerifyException( "E(H(docname)) wrong - wrong key?? \nfrom headers: " + HexUtil.bytesToHex(ehDocname) + "\nfrom key: " + HexUtil.bytesToHex(nodeKey.encryptedHashedDocname)); hashCode = Fields.hashCode(data) ^ Fields.hashCode(headers) ^ nodeKey.hashCode() ^ pubKey.hashCode() ^ hashIdentifier; }
From source file:net.java.otr4j.crypto.DSAKeyPair.java
License:LGPL
/** * Sign data 'b' using DSA private key 'privateKey' and return signature components 'r' and 's'. * * @param b The data to be signed. * @return Signature components 'r' and 's'. */// w w w .j a v a 2 s .com @Nonnull public DSASignature signRS(final byte[] b) { assert !allZeroBytes( b) : "Expected non-zero bytes for b. This may indicate that a critical bug is present, or it may be a false warning."; final DSAParams dsaParams = privateKey.getParams(); final DSAParameters bcDSAParameters = new DSAParameters(dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); final DSAPrivateKeyParameters bcDSAPrivateKeyParms = new DSAPrivateKeyParameters(privateKey.getX(), bcDSAParameters); final DSASigner dsaSigner = new DSASigner(); dsaSigner.init(true, bcDSAPrivateKeyParms); final BigInteger q = dsaParams.getQ(); // Ian: Note that if you can get the standard DSA implementation you're // using to not hash its input, you should be able to pass it ((256-bit // value) mod q), (rather than truncating the 256-bit value) and all // should be well. // ref: Interop problems with libotr - DSA signature final BigInteger bmpi = new BigInteger(1, b); final BigInteger[] signature = dsaSigner.generateSignature(asUnsignedByteArray(bmpi.mod(q))); assert signature.length == 2 : "signRS result does not contain the expected 2 components: r and s"; return new DSASignature(signature[0], signature[1]); }
From source file:net.java.otr4j.crypto.DSAKeyPair.java
License:LGPL
/** * Verify a message using a signature represented as two MPI components: 'r' and 's'. * * @param b the message in bytes//from ww w . jav a 2 s . c om * @param pubKey the DSA public key * @param r the signature component 'r' * @param s the signature component 's' * @throws OtrCryptoException In case of illegal signature. */ public static void verifySignature(final byte[] b, final DSAPublicKey pubKey, final BigInteger r, final BigInteger s) throws OtrCryptoException { requireNonNull(b); assert !allZeroBytes( b) : "Expected non-zero bytes for b. This may indicate that a critical bug is present, or it may be a false warning."; final DSAParams dsaParams = pubKey.getParams(); final BigInteger q = dsaParams.getQ(); final DSAParameters bcDSAParams = new DSAParameters(dsaParams.getP(), q, dsaParams.getG()); final DSAPublicKeyParameters dsaPubParams; try { dsaPubParams = new DSAPublicKeyParameters(pubKey.getY(), bcDSAParams); } catch (final IllegalArgumentException e) { throw new OtrCryptoException("Illegal parameters provided for DSA public key parameters.", e); } // Ian: Note that if you can get the standard DSA implementation you're // using to not hash its input, you should be able to pass it ((256-bit // value) mod q), (rather than truncating the 256-bit value) and all // should be well. // ref: Interop problems with libotr - DSA signature final DSASigner dsaSigner = new DSASigner(); dsaSigner.init(false, dsaPubParams); final BigInteger bmpi = new BigInteger(1, b); if (!dsaSigner.verifySignature(asUnsignedByteArray(bmpi.mod(q)), r, s)) { throw new OtrCryptoException("DSA signature verification failed."); } }
From source file:net.java.otr4j.crypto.OtrCryptoEngineImpl.java
License:Apache License
@Override public byte[] sign(byte[] b, PrivateKey privatekey) throws OtrCryptoException { if (!(privatekey instanceof DSAPrivateKey)) throw new IllegalArgumentException(); DSAParams dsaParams = ((DSAPrivateKey) privatekey).getParams(); DSAParameters bcDSAParameters = new DSAParameters(dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); DSAPrivateKey dsaPrivateKey = (DSAPrivateKey) privatekey; DSAPrivateKeyParameters bcDSAPrivateKeyParms = new DSAPrivateKeyParameters(dsaPrivateKey.getX(), bcDSAParameters);// w ww. java 2 s . c o m DSASigner dsaSigner = new DSASigner(); dsaSigner.init(true, bcDSAPrivateKeyParms); BigInteger q = dsaParams.getQ(); // Ian: Note that if you can get the standard DSA implementation you're // using to not hash its input, you should be able to pass it ((256-bit // value) mod q), (rather than truncating the 256-bit value) and all // should be well. // ref: Interop problems with libotr - DSA signature BigInteger bmpi = new BigInteger(1, b); BigInteger[] rs = dsaSigner.generateSignature(BigIntegers.asUnsignedByteArray(bmpi.mod(q))); int siglen = q.bitLength() / 4; int rslen = siglen / 2; byte[] rb = BigIntegers.asUnsignedByteArray(rs[0]); byte[] sb = BigIntegers.asUnsignedByteArray(rs[1]); // Create the final signature array, padded with zeros if necessary. byte[] sig = new byte[siglen]; System.arraycopy(rb, 0, sig, rslen - rb.length, rb.length); System.arraycopy(sb, 0, sig, sig.length - sb.length, sb.length); return sig; }
From source file:net.java.otr4j.crypto.OtrCryptoEngineImpl.java
License:Apache License
private Boolean verify(byte[] b, PublicKey pubKey, BigInteger r, BigInteger s) throws OtrCryptoException { if (!(pubKey instanceof DSAPublicKey)) throw new IllegalArgumentException(); DSAParams dsaParams = ((DSAPublicKey) pubKey).getParams(); BigInteger q = dsaParams.getQ(); DSAParameters bcDSAParams = new DSAParameters(dsaParams.getP(), q, dsaParams.getG()); DSAPublicKey dsaPrivateKey = (DSAPublicKey) pubKey; DSAPublicKeyParameters dsaPrivParms = new DSAPublicKeyParameters(dsaPrivateKey.getY(), bcDSAParams); // Ian: Note that if you can get the standard DSA implementation you're // using to not hash its input, you should be able to pass it ((256-bit // value) mod q), (rather than truncating the 256-bit value) and all // should be well. // ref: Interop problems with libotr - DSA signature DSASigner dsaSigner = new DSASigner(); dsaSigner.init(false, dsaPrivParms); BigInteger bmpi = new BigInteger(1, b); Boolean result = dsaSigner.verifySignature(BigIntegers.asUnsignedByteArray(bmpi.mod(q)), r, s); return result; }
From source file:org.cryptacular.util.KeyPairUtil.java
License:Open Source License
/** * Determines whether the given DSA public and private keys form a proper key * pair by computing and verifying a digital signature with the keys. * * @param pubKey DSA public key.// ww w . j ava 2 s .co m * @param privKey DSA private key. * * @return True if the keys form a functioning keypair, false otherwise. * Errors during signature verification are treated as false. */ public static boolean isKeyPair(final DSAPublicKey pubKey, final DSAPrivateKey privKey) { final DSASigner signer = new DSASigner(); final DSAParameters params = new DSAParameters(privKey.getParams().getP(), privKey.getParams().getQ(), privKey.getParams().getG()); signer.init(true, new DSAPrivateKeyParameters(privKey.getX(), params)); final BigInteger[] sig = signer.generateSignature(SIGN_BYTES); signer.init(false, new DSAPublicKeyParameters(pubKey.getY(), params)); try { return signer.verifySignature(SIGN_BYTES, sig[0], sig[1]); } catch (Exception e) { return false; } }