private void runVector(StreamCipher hc, String fileName, PeekableLineReader r, String vectorName) throws IOException { // System.out.println(fileName + " => " + vectorName); String hexKey = readBlock(r); String hexIV = readBlock(r); CipherParameters cp = new KeyParameter(Hex.decode(hexKey)); cp = new ParametersWithIV(cp, Hex.decode(hexIV)); hc.init(true, cp); byte[] input = new byte[64]; byte[] output = new byte[64]; byte[] digest = new byte[64]; int pos = 0; for (; ; ) { String line1 = r.peekLine().trim(); int equalsPos = line1.indexOf('='); String lead = line1.substring(0, equalsPos - 1); String hexData = readBlock(r); byte[] data = Hex.decode(hexData); if (lead.equals("xor-digest")) { if (!Arrays.areEqual(data, digest)) { fail("Failed in " + fileName + " for test vector: " + vectorName + " at " + lead); // System.out.println(fileName + " => " + vectorName + " failed at " + // lead); return; } break; } int posA = lead.indexOf('['); int posB = lead.indexOf(".."); int posC = lead.indexOf(']'); int start = Integer.parseInt(lead.substring(posA + 1, posB)); int end = Integer.parseInt(lead.substring(posB + 2, posC)); if (start % 64 != 0 || (end - start != 63)) { throw new IllegalStateException(vectorName + ": " + lead + " not on 64 byte boundaries"); } while (pos < end) { hc.processBytes(input, 0, input.length, output, 0); xor(digest, output); pos += 64; } if (!Arrays.areEqual(data, output)) { fail("Failed in " + fileName + " for test vector: " + vectorName + " at " + lead); // System.out.println(fileName + " => " + vectorName + " failed at " + lead); // return; } } }
private static ECField convertField(FiniteField field) { if (ECAlgorithms.isFpField(field)) { return new ECFieldFp(field.getCharacteristic()); } else // if (ECAlgorithms.isF2mField(curveField)) { Polynomial poly = ((PolynomialExtensionField) field).getMinimalPolynomial(); int[] exponents = poly.getExponentsPresent(); int[] ks = Arrays.reverse(Arrays.copyOfRange(exponents, 1, exponents.length - 1)); return new ECFieldF2m(poly.getDegree(), ks); } }
public BulkData( byte[] chunkData, int[] chunkX, int[] chunkZ, boolean skylight, short[] bitmap, short[] add) { this.chunkData = ByteUtils.clone(chunkData); this.chunkX = Arrays.copyOf(chunkX, chunkX.length); this.chunkZ = Arrays.copyOf(chunkZ, chunkZ.length); this.skylight = skylight; this.bitmap = new short[bitmap.length]; System.arraycopy(bitmap, 0, this.bitmap, 0, bitmap.length); this.add = new short[add.length]; System.arraycopy(add, 0, this.add, 0, add.length); }
@BeforeClass public static void setUpBeforeClass() throws Exception { Log.info( Log.FAC_TEST, "Setting up NDNNetworkObjectTestRepo, prefix {0}", testHelper.getClassNamespace()); NDNHandle myhandle = NDNHandle.open(); try { ns = new ContentName[NUM_LINKS]; for (int i = 0; i < NUM_LINKS; ++i) { ns[i] = new ContentName(testHelper.getClassNamespace(), "Links", prefix + Integer.toString(i)); } Arrays.fill(publisherid1, (byte) 6); Arrays.fill(publisherid2, (byte) 3); pubID1 = new PublisherID(publisherid1, PublisherType.KEY); pubID2 = new PublisherID(publisherid2, PublisherType.ISSUER_KEY); las[0] = new LinkAuthenticator(pubID1); las[1] = null; las[2] = new LinkAuthenticator(pubID2, null, null, SignedInfo.ContentType.DATA, contenthash1); las[3] = new LinkAuthenticator(pubID1, null, NDNTime.now(), null, contenthash1); for (int j = 4; j < NUM_LINKS; ++j) { las[j] = new LinkAuthenticator(pubID2, null, NDNTime.now(), null, null); } lrs = new Link[NUM_LINKS]; for (int i = 0; i < lrs.length; ++i) { lrs[i] = new Link(ns[i], las[i]); } empty = new Collection(); small1 = new Collection(); small2 = new Collection(); for (int i = 0; i < 5; ++i) { small1.add(lrs[i]); small2.add(lrs[i + 5]); } big = new Collection(); for (int i = 0; i < NUM_LINKS; ++i) { big.add(lrs[i]); } Log.info( Log.FAC_TEST, "Finihed setting up NDNNetworkObjectTestRepo, prefix {0}", testHelper.getClassNamespace()); } finally { myhandle.close(); KeyManager.closeDefaultKeyManager(); } }
private void testGCMGeneric(byte[] K, byte[] N, byte[] A, byte[] P, byte[] C) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, NoSuchProviderException, IOException, InvalidParameterSpecException { Cipher eax = Cipher.getInstance("AES/GCM/NoPadding", "BC"); SecretKeySpec key = new SecretKeySpec(K, "AES"); // GCMParameterSpec mapped to AEADParameters and overrides default MAC // size GCMParameterSpec spec = new GCMParameterSpec(128, N); eax.init(Cipher.ENCRYPT_MODE, key, spec); eax.updateAAD(A); byte[] c = eax.doFinal(P); if (!areEqual(C, c)) { fail("JCE encrypt with additional data and GCMParameterSpec failed."); } eax = Cipher.getInstance("GCM", "BC"); eax.init(Cipher.DECRYPT_MODE, key, spec); eax.updateAAD(A); byte[] p = eax.doFinal(C); if (!areEqual(P, p)) { fail("JCE decrypt with additional data and GCMParameterSpec failed."); } AlgorithmParameters algParams = eax.getParameters(); byte[] encParams = algParams.getEncoded(); GCMParameters gcmParameters = GCMParameters.getInstance(encParams); if (!Arrays.areEqual(spec.getIV(), gcmParameters.getNonce()) || spec.getTLen() != gcmParameters.getIcvLen()) { fail("parameters mismatch"); } GCMParameterSpec gcmSpec = algParams.getParameterSpec(GCMParameterSpec.class); if (!Arrays.areEqual(gcmSpec.getIV(), gcmParameters.getNonce()) || gcmSpec.getTLen() != gcmParameters.getIcvLen() * 8) { fail("spec parameters mismatch"); } if (!Arrays.areEqual(eax.getIV(), gcmParameters.getNonce())) { fail("iv mismatch"); } }
public void performTest() throws Exception { for (int i = 0; i != cipherTests.length; i += 8) { testECB( Integer.parseInt(cipherTests[i]), Hex.decode(cipherTests[i + 1]), Hex.decode(cipherTests[i + 2]), Hex.decode(cipherTests[i + 3])); testCFB( Integer.parseInt(cipherTests[i + 4]), Hex.decode(cipherTests[i + 4 + 1]), Hex.decode(cipherTests[i + 4 + 2]), Hex.decode(cipherTests[i + 4 + 3])); oidTest(); } Mac mac = Mac.getInstance("GOST28147MAC", "BC"); mac.init( new SecretKeySpec( Hex.decode("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"), "GOST28147")); if (!Arrays.areEqual( Hex.decode("1b69996e"), mac.doFinal(Hex.decode("4e6f77206973207468652074696d6520666f7220616c6c20")))) { fail("mac test falied."); } }
/** * Calculates the MacTag (to be used for key confirmation), as defined by <a * href="http://csrc.nist.gov/publications/nistpubs/800-56A/SP800-56A_Revision1_Mar08-2007.pdf">NIST * SP 800-56A Revision 1</a>, Section 8.2 Unilateral Key Confirmation for Key Agreement Schemes. * * <p> * * <p> * * <pre> * MacTag = HMAC(MacKey, MacLen, MacData) * * MacKey = H(K || "JPAKE_KC") * * MacData = "KC_1_U" || participantId || partnerParticipantId || gx1 || gx2 || gx3 || gx4 * * Note that both participants use "KC_1_U" because the sender of the round 3 message * is always the initiator for key confirmation. * * HMAC = {@link HMac} used with the given {@link Digest} * H = The given {@link Digest}</li> * MacLen = length of MacTag * </pre> * * <p> */ public static BigInteger calculateMacTag( String participantId, String partnerParticipantId, BigInteger gx1, BigInteger gx2, BigInteger gx3, BigInteger gx4, BigInteger keyingMaterial, Digest digest) { byte[] macKey = calculateMacKey(keyingMaterial, digest); HMac mac = new HMac(digest); byte[] macOutput = new byte[mac.getMacSize()]; mac.init(new KeyParameter(macKey)); /* * MacData = "KC_1_U" || participantId_Alice || participantId_Bob || gx1 || gx2 || gx3 || gx4. */ updateMac(mac, "KC_1_U"); updateMac(mac, participantId); updateMac(mac, partnerParticipantId); updateMac(mac, gx1); updateMac(mac, gx2); updateMac(mac, gx3); updateMac(mac, gx4); mac.doFinal(macOutput, 0); Arrays.fill(macKey, (byte) 0); return new BigInteger(macOutput); }
/** * Reseed the DRBG. * * @param additionalInput additional input to be added to the DRBG in this step. */ public void reseed(byte[] additionalInput) { // 1. seed_material = 0x01 || V || entropy_input || additional_input. // // 2. seed = Hash_df (seed_material, seedlen). // // 3. V = seed. // // 4. C = Hash_df ((0x00 || V), seedlen). // // 5. reseed_counter = 1. // // 6. Return V, C, and reseed_counter for the new_working_state. // // Comment: Precede with a byte of all zeros. byte[] entropy = getEntropy(); byte[] seedMaterial = Arrays.concatenate(ONE, _V, entropy, additionalInput); byte[] seed = Utils.hash_df(_digest, seedMaterial, _seedLength); _V = seed; byte[] subV = new byte[_V.length + 1]; subV[0] = 0x00; System.arraycopy(_V, 0, subV, 1, _V.length); _C = Utils.hash_df(_digest, subV, _seedLength); _reseedCounter = 1; }
private void checkMessage( Signature sgr, PrivateKey sKey, PublicKey vKey, byte[] message, byte[] sig) throws InvalidKeyException, SignatureException { byte[] kData = BigIntegers.asUnsignedByteArray( new BigInteger( "700000017569056646655505781757157107570501575775705779575555657156756655")); SecureRandom k = new FixedSecureRandom(kData); sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); if (!Arrays.areEqual(sigBytes, sig)) { fail(new String(message) + " signature incorrect"); } sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail(new String(message) + " verification failed"); } }
/** * Create an iso7816Certificate structure from a body and its signature. * * @param body the Iso7816CertificateBody object containing the body. * @param signature the byte array containing the signature * @throws IOException if there is a problem parsing the data. */ public CVCertificate(CertificateBody body, byte[] signature) throws IOException { certificateBody = body; this.signature = Arrays.clone(signature); // patch remi valid |= bodyValid; valid |= signValid; }
private void verifyRSASignatures(CMSSignedData s, byte[] contentDigest) throws Exception { Store certStore = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder) certIt.next(); if (!signer.verify( new BcRSASignerInfoVerifierBuilder( new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider()) .build(cert))) { fail("signature verification failed"); } if (contentDigest != null) { if (!Arrays.areEqual(contentDigest, signer.getContentDigest())) { fail("digest verification failed"); } } } }
/** * Create an address * * @param type - COMMON or P2SH * @param address - digest of key (COMMON) or script (P2SH) * @throws ValidationException - thrown if digest length is not 20 bytes */ public Address(Type type, byte[] address) throws ValidationException { this.type = type; if (address.length != 20) { throw new ValidationException("invalid digest length for an address"); } this.bytes = Arrays.clone(address); }
/** * Returns true if we know the prefix has a child matching the given name component. * * @param childComponent name component to check for in the stored child names. * @return true if that child is in our list of known children */ public boolean hasChild(byte[] childComponent) { for (ContentName child : _children) { if (Arrays.areEqual(childComponent, child.component(0))) { return true; } } return false; }
boolean asn1Equals(ASN1Primitive o) { if (!(o instanceof DERGeneralString)) { return false; } DERGeneralString s = (DERGeneralString) o; return Arrays.areEqual(string, s.string); }
private void CTR_DRBG_Reseed_algorithm(byte[] additionalInput) { byte[] seedMaterial = Arrays.concatenate(getEntropy(), additionalInput); seedMaterial = Block_Cipher_df(seedMaterial, _seedLength); CTR_DRBG_Update(seedMaterial, _Key, _V); _reseedCounter = 1; }
@Test public void testPaddedVersions() throws Exception { ContentName name = ContentName.fromNative("/testme"); long v0 = 0x80FFFF; byte[] b0 = {VersioningProfile.VERSION_MARKER, (byte) 0x80, (byte) 0xFF, (byte) 0xFF}; ContentName vn0 = VersioningProfile.addVersion(name, v0); byte[] x0 = VersioningProfile.getLastVersionComponent(vn0); System.out.println("From long name : " + vn0.toString()); Assert.assertTrue(Arrays.areEqual(b0, x0)); // now do it as ccntime CCNTime t0 = CCNTime.fromBinaryTimeAsLong(v0); vn0 = VersioningProfile.addVersion(name, t0); x0 = VersioningProfile.getLastVersionComponent(vn0); System.out.println("From ccntime name: " + vn0.toString()); Assert.assertTrue(Arrays.areEqual(b0, x0)); }
public byte[] decodeCiphertext(short type, byte[] ciphertext, int offset, int len) throws IOException { int blockSize = decryptCipher.getBlockSize(); int macSize = readMac.getSize(); /* * TODO[TLS 1.1] Explicit IV implies minLen = blockSize + max(blockSize, macSize + 1), * and will need further changes to offset and plen variables below. */ int minLen = Math.max(blockSize, macSize + 1); if (len < minLen) { throw new TlsFatalAlert(AlertDescription.decode_error); } if (len % blockSize != 0) { throw new TlsFatalAlert(AlertDescription.decryption_failed); } for (int i = 0; i < len; i += blockSize) { decryptCipher.processBlock(ciphertext, offset + i, ciphertext, offset + i); } int plen = len; // If there's anything wrong with the padding, this will return zero int totalPad = checkPaddingConstantTime(ciphertext, offset, plen, blockSize, macSize); int macInputLen = plen - totalPad - macSize; byte[] decryptedMac = Arrays.copyOfRange(ciphertext, offset + macInputLen, offset + macInputLen + macSize); byte[] calculatedMac = readMac.calculateMacConstantTime( type, ciphertext, offset, macInputLen, plen - macSize, randomData); boolean badMac = !Arrays.constantTimeAreEqual(calculatedMac, decryptedMac); if (badMac || totalPad == 0) { throw new TlsFatalAlert(AlertDescription.bad_record_mac); } return Arrays.copyOfRange(ciphertext, offset, offset + macInputLen); }
/** Karazuba multiplication */ private BigIntPolynomial multRecursive(BigIntPolynomial poly2) { BigInteger[] a = coeffs; BigInteger[] b = poly2.coeffs; int n = poly2.coeffs.length; if (n <= 1) { BigInteger[] c = Arrays.clone(coeffs); for (int i = 0; i < coeffs.length; i++) { c[i] = c[i].multiply(poly2.coeffs[0]); } return new BigIntPolynomial(c); } else { int n1 = n / 2; BigIntPolynomial a1 = new BigIntPolynomial(Arrays.copyOf(a, n1)); BigIntPolynomial a2 = new BigIntPolynomial(Arrays.copyOfRange(a, n1, n)); BigIntPolynomial b1 = new BigIntPolynomial(Arrays.copyOf(b, n1)); BigIntPolynomial b2 = new BigIntPolynomial(Arrays.copyOfRange(b, n1, n)); BigIntPolynomial A = (BigIntPolynomial) a1.clone(); A.add(a2); BigIntPolynomial B = (BigIntPolynomial) b1.clone(); B.add(b2); BigIntPolynomial c1 = a1.multRecursive(b1); BigIntPolynomial c2 = a2.multRecursive(b2); BigIntPolynomial c3 = A.multRecursive(B); c3.sub(c1); c3.sub(c2); BigIntPolynomial c = new BigIntPolynomial(2 * n - 1); for (int i = 0; i < c1.coeffs.length; i++) { c.coeffs[i] = c1.coeffs[i]; } for (int i = 0; i < c3.coeffs.length; i++) { c.coeffs[n1 + i] = c.coeffs[n1 + i].add(c3.coeffs[i]); } for (int i = 0; i < c2.coeffs.length; i++) { c.coeffs[2 * n1 + i] = c.coeffs[2 * n1 + i].add(c2.coeffs[i]); } return c; } }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return Arrays.areEqual(bytes, ((Address) obj).bytes) && type == ((Address) obj).type; }
public void testBasic() throws Exception { SMIMECompressedGenerator cgen = new SMIMECompressedGenerator(); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); MimeBodyPart cbp = cgen.generate(msg, new ZlibCompressor()); SMIMECompressed sc = new SMIMECompressed(cbp); msg.writeTo(bOut); assertTrue(Arrays.areEqual(bOut.toByteArray(), sc.getContent(new ZlibExpanderProvider()))); }
protected int[] getCipherSuites() { return Arrays.concatenate( super.getCipherSuites(), new int[] { CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_ESTREAM_SALSA20_SHA1, CipherSuite.TLS_ECDHE_RSA_WITH_SALSA20_SHA1, CipherSuite.TLS_RSA_WITH_ESTREAM_SALSA20_SHA1, CipherSuite.TLS_RSA_WITH_SALSA20_SHA1, }); }
public static byte[] decodeB64UrlSafe(final byte[] data) { byte[] encode = Arrays.copyOf(data, data.length); for (int i = 0; i < encode.length; i++) { if (encode[i] == '-') { encode[i] = '+'; } else if (encode[i] == '_') { encode[i] = '/'; } } return Base64.decodeBase64(encode); }
/** * Subtracts another polynomial which can have a different number of coefficients. * * @param b another polynomial */ public void sub(BigIntPolynomial b) { if (b.coeffs.length > coeffs.length) { int N = coeffs.length; coeffs = Arrays.copyOf(coeffs, b.coeffs.length); for (int i = N; i < coeffs.length; i++) { coeffs[i] = Constants.BIGINT_ZERO; } } for (int i = 0; i < b.coeffs.length; i++) { coeffs[i] = coeffs[i].subtract(b.coeffs[i]); } }
ASN1Boolean(byte[] value) { if (value.length != 1) { throw new IllegalArgumentException("byte value should have 1 byte in it"); } if (value[0] == 0) { this.value = FALSE_VALUE; } else if ((value[0] & 0xff) == 0xff) { this.value = TRUE_VALUE; } else { this.value = Arrays.clone(value); } }
private void tryRsaPkcs15Sig( String algorithm, byte[] data, PrivateKey signingKey, PublicKey verifyKey, ASN1ObjectIdentifier sigOid, ASN1ObjectIdentifier hashOid) throws Exception { Signature sig; byte[] sigBytes; sig = Signature.getInstance(algorithm, "BC"); sig.initSign(signingKey); sig.update(data); sigBytes = sig.sign(); sig.initVerify(verifyKey); sig.update(data); if (!sig.verify(sigBytes)) { fail(algorithm + " verification failed"); } Cipher c = Cipher.getInstance("RSA/NONE/PKCS1Padding", "BC"); c.init(Cipher.DECRYPT_MODE, verifyKey); DigestInfo digInfo = DigestInfo.getInstance(c.doFinal(sigBytes)); isTrue("digest alg not match", digInfo.getAlgorithmId().getAlgorithm().equals(hashOid)); sig = Signature.getInstance(sigOid.getId(), "BC"); sig.initSign(signingKey); sig.update(data); isTrue("sig not matched", Arrays.areEqual(sigBytes, sig.sign())); sig.initVerify(verifyKey); sig.update(data); if (!sig.verify(sigBytes)) { fail(algorithm + " oid verification failed"); } }
private void CTR_DRBG_Instantiate_algorithm( byte[] entropy, byte[] nonce, byte[] personalisationString) { byte[] seedMaterial = Arrays.concatenate(entropy, nonce, personalisationString); byte[] seed = Block_Cipher_df(seedMaterial, _seedLength); int outlen = _engine.getBlockSize(); _Key = new byte[(_keySizeInBits + 7) / 8]; _V = new byte[outlen]; // _Key & _V are modified by this call CTR_DRBG_Update(seed, _Key, _V); _reseedCounter = 1; }
public void testAES256() throws Exception { MimeMessage message = loadMessage("test256.message"); SMIMEEnveloped env = new SMIMEEnveloped(message); RecipientInformationStore store = env.getRecipientInfos(); RecipientInformation recipInfo = store.get(new JceKeyTransRecipientId(loadCert("cert.pem"))); assertNotNull(recipInfo); byte[] content = recipInfo.getContent(new JceKeyTransEnvelopedRecipient(loadKey("key.pem"))); assertTrue(org.bouncycastle.util.Arrays.areEqual(testMessage, content)); }
public boolean verify(DigestCalculatorProvider calculatorProvider) throws CMSException { try { ContentInfo content = digestedData.getEncapContentInfo(); DigestCalculator calc = calculatorProvider.get(digestedData.getDigestAlgorithm()); OutputStream dOut = calc.getOutputStream(); dOut.write(((ASN1OctetString) content.getContent()).getOctets()); return Arrays.areEqual(digestedData.getDigest(), calc.getDigest()); } catch (OperatorCreationException e) { throw new CMSException("unable to create digest calculator: " + e.getMessage(), e); } catch (IOException e) { throw new CMSException("unable process content: " + e.getMessage(), e); } }
/** * Multiplies the polynomial by another, taking the indices mod N. Does not change this polynomial * but returns the result as a new polynomial.<br> * Both polynomials must have the same number of coefficients. * * @param poly2 the polynomial to multiply by * @return a new polynomial */ public BigIntPolynomial mult(BigIntPolynomial poly2) { int N = coeffs.length; if (poly2.coeffs.length != N) { throw new IllegalArgumentException("Number of coefficients must be the same"); } BigIntPolynomial c = multRecursive(poly2); if (c.coeffs.length > N) { for (int k = N; k < c.coeffs.length; k++) { c.coeffs[k - N] = c.coeffs[k - N].add(c.coeffs[k]); } c.coeffs = Arrays.copyOf(c.coeffs, N); } return c; }
public boolean equals(Object anObject) { if (anObject == this) { return true; } if (!(anObject instanceof ECFieldElement.F2m)) { return false; } ECFieldElement.F2m b = (ECFieldElement.F2m) anObject; return ((this.m == b.m) && (this.representation == b.representation) && Arrays.areEqual(this.ks, b.ks) && (this.x.equals(b.x))); }