List of usage examples for org.bouncycastle.crypto.digests SHA256Digest SHA256Digest
public SHA256Digest()
From source file:com.licel.jcardsim.crypto.SymmetricSignatureImpl.java
License:Apache License
public void init(Key theKey, byte theMode, byte[] bArray, short bOff, short bLen) throws CryptoException { if (theKey == null) { CryptoException.throwIt(CryptoException.UNINITIALIZED_KEY); }//from w ww. j ava 2s . c o m if (!theKey.isInitialized()) { CryptoException.throwIt(CryptoException.UNINITIALIZED_KEY); } if (!(theKey instanceof SymmetricKeyImpl)) { CryptoException.throwIt(CryptoException.ILLEGAL_VALUE); } CipherParameters cipherParams = null; BlockCipher cipher = ((SymmetricKeyImpl) theKey).getCipher(); if (bArray == null) { cipherParams = ((SymmetricKeyImpl) theKey).getParameters(); } else { if (bLen != cipher.getBlockSize()) { CryptoException.throwIt(CryptoException.ILLEGAL_VALUE); } cipherParams = new ParametersWithIV(((SymmetricKeyImpl) theKey).getParameters(), bArray, bOff, bLen); } switch (algorithm) { case ALG_DES_MAC4_NOPAD: engine = new CBCBlockCipherMac(cipher, 32, null); break; case ALG_DES_MAC8_NOPAD: engine = new CBCBlockCipherMac(cipher, 64, null); break; case ALG_DES_MAC4_ISO9797_M1: engine = new CBCBlockCipherMac(cipher, 32, new ZeroBytePadding()); break; case ALG_DES_MAC8_ISO9797_M1: engine = new CBCBlockCipherMac(cipher, 64, new ZeroBytePadding()); break; case ALG_DES_MAC4_ISO9797_M2: engine = new CBCBlockCipherMac(cipher, 32, new ISO7816d4Padding()); break; case ALG_DES_MAC8_ISO9797_M2: engine = new CBCBlockCipherMac(cipher, 64, new ISO7816d4Padding()); break; case ALG_DES_MAC8_ISO9797_1_M2_ALG3: engine = new ISO9797Alg3Mac(new DESEngine(), 64, new ISO7816d4Padding()); break; case ALG_DES_MAC4_PKCS5: engine = new CBCBlockCipherMac(cipher, 32, new PKCS7Padding()); break; case ALG_DES_MAC8_PKCS5: engine = new CBCBlockCipherMac(cipher, 64, new PKCS7Padding()); break; case ALG_AES_MAC_128_NOPAD: engine = new CBCBlockCipherMac(cipher, 128, null); break; case ALG_HMAC_SHA1: engine = new HMac(new SHA1Digest()); break; case ALG_HMAC_SHA_256: engine = new HMac(new SHA256Digest()); break; case ALG_HMAC_SHA_384: engine = new HMac(new SHA384Digest()); break; case ALG_HMAC_SHA_512: engine = new HMac(new SHA512Digest()); break; case ALG_HMAC_MD5: engine = new HMac(new MD5Digest()); break; case ALG_HMAC_RIPEMD160: engine = new HMac(new RIPEMD160Digest()); break; default: CryptoException.throwIt(CryptoException.NO_SUCH_ALGORITHM); break; } engine.init(cipherParams); isInitialized = true; }
From source file:com.nokia.xfolite.xforms.xpath.XFormsCoreFunctionLibrary.java
License:Open Source License
public static String digest_function(String s, String method, String encoding) { //#debug info System.out.println("Digest function invoked with params(" + s + "," + method + "," + encoding + ")"); Digest digest = null;//from ww w .ja v a2 s . c o m Encoder encoder = null; if (encoding.equals("base64")) { encoder = new Base64Encoder(); } else if (encoding.equals("hex")) { encoder = new HexEncoder(); } if (method.equals("SHA-1")) { digest = new SHA1Digest(); } else if (method.equals("SHA-256")) { digest = new SHA256Digest(); } else if (method.equals("SHA-512")) { digest = new SHA512Digest(); } else if (method.equals("MD5")) { digest = new MD5Digest(); } if (encoder == null) { throw new XPathException(XPathException.TYPE_ERR, "XForms function digest() only supports hex and base64 encoding."); } if (digest == null) { throw new XPathException(XPathException.TYPE_ERR, "XForms function digest() only supports MD5, SHA-1, SHA-256 and SHA-512 digests."); } int len = s.length(); for (int i = 0; i < len; i++) { digest.update((byte) s.charAt(i)); // FIXME: Better not use non-ASCII characters! } byte[] data = new byte[digest.getDigestSize()]; digest.doFinal(data, 0); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { encoder.encode(data, 0, data.length, bOut); } catch (IOException e) { throw new XPathException(XPathException.TYPE_ERR, "Exception when encoding digest: " + e); } byte[] out = bOut.toByteArray(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < out.length; i++) { sb.append((char) out[i]); // This works fine, neither hex nor base64 encodings produce } return sb.toString(); }
From source file:com.password.locker.crypto.SecureCryptoImpl.java
License:Open Source License
/** * SecureCrypto Constructor.//from w w w . j ava2 s . c o m * * @param password * password for the crypto keyspec. * * @throws InvalidAlgorithmParameterException * @throws InvalidKeyException * @throws NoSuchPaddingException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException */ public SecureCryptoImpl(final char[] password) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException { SHA256Digest digest = new SHA256Digest(); String s = Constants.PROPERTIES.getStringProperty(Constants.SALT_KEY, PasswordUtils.getSalt(digest)); salt = Hex.decode(s); if (salt.length != digest.getDigestSize()) { LOGGER.warn("Warning salt size is not the size of the Digest."); } //--------------------------------------------------- // Setup encryption. //--------------------------------------------------- PBEParametersGenerator pGen = new PKCS12ParametersGenerator(digest); pGen.init(PBEParametersGenerator.PKCS12PasswordToBytes(password), salt, ITERATIONS); ParametersWithIV params = (ParametersWithIV) pGen.generateDerivedParameters(KEY_LEN, IV_LEN); SecretKeySpec encKey = new SecretKeySpec(((KeyParameter) params.getParameters()).getKey(), "AES"); encryption = Cipher.getInstance(Constants.CRYPTO_ALGORITHM, new BouncyCastleProvider()); encryption.init(Cipher.ENCRYPT_MODE, encKey, new IvParameterSpec(params.getIV())); //--------------------------------------------------- // Setup decryption. //--------------------------------------------------- decryption = Cipher.getInstance(Constants.CRYPTO_SEC_KEY_SPEC, new BouncyCastleProvider()); PBEKeySpec keySpec = new PBEKeySpec(password, salt, ITERATIONS); SecretKeyFactory fact = SecretKeyFactory.getInstance(Constants.CRYPTO_SEC_KEY_SPEC, new BouncyCastleProvider()); try { decryption.init(Cipher.DECRYPT_MODE, fact.generateSecret(keySpec)); } catch (InvalidKeySpecException e) { ExceptionUtils.fatalError(SecureCryptoImpl.class, e); } Constants.PROPERTIES.addProperty(Constants.SALT_KEY, s); }
From source file:com.sos.CredentialStore.KeePass.pl.sind.keepass.hash.BcSHA256Hash.java
License:Apache License
public BcSHA256Hash() { super(); sha256 = new SHA256Digest(); }
From source file:com.sun.midp.crypto.SHA256.java
License:Open Source License
/** Create SHA digest object. */ SHA256() { impl = new SHA256Digest(); }
From source file:com.vvote.verifier.component.ballotGen.BallotGenerationVerifier.java
License:Open Source License
/** * Verifies the fiat shamir calculation/*w w w. ja v a2s .c o m*/ * * @return true if the fiat shamir calculation matches that which is * included in the ballot submit response message for the current * commit */ public boolean verifyFiatShamirCalculation() { logger.info( "Starting Verification of the Fiat Shamir signature which determines the ballots chosen for auditing by each PoD Printer"); final int ballotsToGenerate = this.getDataStore().getBallotGenerationConfig().getBallotsToGenerate(); final int ballotsToAudit = this.getDataStore().getBallotGenerationConfig().getBallotsToAudit(); List<String> serialNumbers = null; BallotAuditCommit auditCommit = null; boolean verified = true; String currentBoothId = null; for (CommitIdentifier identifier : this.getDataStore().getAuditData().keySet()) { logger.info("Verifying the Fiat-Shamir signature for commitment with identifier: {}", identifier); serialNumbers = new ArrayList<String>( this.getDataStore().getGeneratedCiphers().get(identifier).getCommittedBallotsSerialNumbers()); // need to sort the serial numbers to make sure they are in a // 'default' // state i.e. in order Collections.sort(serialNumbers, new BallotSerialNumberComparator()); // check generation size if (serialNumbers.size() != ballotsToGenerate) { logger.error( "The number of ballots generated ({}) doesn't match the number of ballots requested for generation ({})", serialNumbers.size(), ballotsToGenerate); resultsLogger.error( "The number of ballots generated ({}) doesn't match the number of ballots requested for generation ({})", serialNumbers.size(), ballotsToGenerate); return false; } auditCommit = this.getDataStore().getAuditData().get(identifier); currentBoothId = auditCommit.getMessage().getBoothID(); // verify sig is created properly: try { if (!verifySignatureMatches(identifier, auditCommit)) { verified = false; } } catch (NoSuchAlgorithmException | NoSuchProviderException | FileHashException e) { logger.error("The Fiat Shamir signature couldn't be calculated. Check the supplied data", e); resultsLogger.error("The Fiat Shamir signature couldn't be calculated. Check the supplied data", e); return false; } logger.info( "Fiat shamir signature was recalculated and matches what was included in the BallotSubmitResponse message for printer: {}", currentBoothId); logger.info( "Verifying that the ballots chosen for auditing were correctly chosen for commitment with identifier: {}", identifier); final byte[] fiatShamirSig = Utils.decodeBase64Data(auditCommit.getResponse().getFiatShamir()); // use fiat shamir sig as the seed for the deterministic random bit // generator FixedSecureRandom fixedSecureRandom = new FixedSecureRandom(fiatShamirSig); SP800SecureRandomBuilder randomBuilder = new SP800SecureRandomBuilder(fixedSecureRandom, false); randomBuilder.setPersonalizationString(auditCommit.getResponse().getPeerID().getBytes()); SP800SecureRandom sp800SecureRandom = randomBuilder.buildHash(new SHA256Digest(), null, false); Collections.shuffle(serialNumbers, sp800SecureRandom); ArrayList<String> serialNumbersToAudit = new ArrayList<String>(); for (int i = 0; i < ballotsToAudit; i++) { serialNumbersToAudit.add(serialNumbers.get(i)); } if (serialNumbersToAudit.size() != ballotsToAudit) { logger.error( "The number of serial numbers calculated for auditing does not match the number of serial numbers requested for auditing for commitment with identifier: {}", identifier); resultsLogger.error( "The number of serial numbers calculated for auditing does not match the number of serial numbers requested for auditing for commitment with identifier: {}", identifier); verified = false; } if (auditCommit.getRandomnessCommitmentSerialNumbers().size() != ballotsToAudit) { logger.error( "The number of serial numbers included in the audit file doesn't match the number of serial numbers requested for auditing for commitment with identifier: {}", identifier); resultsLogger.error( "The number of serial numbers included in the audit file doesn't match the number of serial numbers requested for auditing for commitment with identifier: {}", identifier); verified = false; } if (!auditCommit.getRandomnessCommitmentSerialNumbers().containsAll(serialNumbersToAudit)) { logger.error( "The serial numbers included in the audit file do not match the serial numbers requested for auditing calculated using the fiat shamir signature for commitment with identifier: {}", identifier); resultsLogger.error( "The serial numbers included in the audit file do not match the serial numbers requested for auditing calculated using the fiat shamir signature for commitment with identifier: {}", identifier); verified = false; } logger.debug( "Successfully verified that the serial numbers of ballots for auditing were correctly chosen using the Fiat shamir signature for commitment with identifier: {}", identifier); resultsLogger.info( "Serial numbers for auditing were checked successfully using the Fiat shamir signature for commitment with identifier: {}", identifier); } logger.debug( "Successfully verified the Fiat Shamir signatures were used to choose the required number of ballots for auditing"); resultsLogger.info( "Successfully verified the Fiat Shamir signatures were used to choose the required number of ballots for auditing"); return verified; }
From source file:com.vvote.verifierlibrary.utils.crypto.CryptoUtils.java
License:Open Source License
/** * Perform a verification on a hash commitment using bouncy castle. This * implementation uses the HashCommitter from bouncy castle and the * isRevealed function/*w w w .j a v a2 s . co m*/ * * @param commitment * @param witness * @param randomValue * @return whether the commitment check is successful * @throws CommitException */ private static boolean bouncyCastleVerifyHashCommitment(byte[] commitment, byte[] witness, byte[] randomValue) throws CommitException { logger.debug("Verifying hash commitment using Bouncy castle implementation"); // initialise a hash committer HashCommitter hashCommitter = new HashCommitter(new SHA256Digest(), new SecureRandom(witness)); MessageDigest md = null; try { logger.debug("Initialising message digest"); // initialise the message digest md = MessageDigest.getInstance(CryptoConstants.Commitments.COMMITMENT_HASH_ALGORITHM); // ensure the random value is the correct length if (randomValue.length > CryptoConstants.Commitments.RANDOM_VALUE_MAXIMUM_LENGTH) { logger.debug("Hashing random value to the correct length"); md.reset(); randomValue = md.digest(randomValue); } // initialise a new Commitment Commitment comm = new Commitment(witness, commitment); // check whether the given random value opens the commitment if (!hashCommitter.isRevealed(comm, randomValue)) { logger.error("Bouncy castle hash commitment verification failed"); return false; } } catch (NoSuchAlgorithmException e) { logger.error("Could not initialise the message digest with the specified algorithm: {}", CryptoConstants.Commitments.COMMITMENT_HASH_ALGORITHM, e); throw new CommitException("Could not initialise the message digest with the specified algorithm: " + CryptoConstants.Commitments.COMMITMENT_HASH_ALGORITHM, e); } return true; }
From source file:common.crypto.bouncycastle.CCryptoSHABC.java
License:Open Source License
@Override public void initialize(CryptoTypes.ESHAMode eMode) { switch (eMode) { case SHA1://from w ww . java 2 s. c o m m_digest = new SHA1Digest(); break; case SHA256: m_digest = new SHA256Digest(); break; case SHA512: m_digest = new SHA512Digest(); } }
From source file:COSE.MacCommon.java
private byte[] HMAC(CBORObject alg, byte[] rgbKey) throws CoseException { Digest digest;/*from w w w . j a v a 2 s. c o m*/ int cbitKey; int cbResult; switch (alg.AsInt32()) { case 4: // HMAC_SHA_256_64 cbitKey = 256; cbResult = 64 / 8; digest = new SHA256Digest(); break; case 5: // HMAC_SHA_256 cbitKey = 256; cbResult = 256 / 8; digest = new SHA256Digest(); break; case 6: // HMAC_SHA_384 cbitKey = 384; cbResult = 384 / 8; digest = new SHA384Digest(); break; case 7: // HMAC_SHA_512 cbitKey = 512; cbResult = 512 / 8; digest = new SHA512Digest(); break; default: throw new CoseException("Internal Error"); } if (rgbKey.length != cbitKey / 8) throw new CoseException("Key is incorrect size"); HMac hmac = new HMac(digest); KeyParameter key = new KeyParameter(rgbKey); byte[] toDigest = BuildContentBytes(); byte[] resBuf = new byte[hmac.getMacSize()]; hmac.init(key); hmac.update(toDigest, 0, toDigest.length); hmac.doFinal(resBuf, 0); byte[] returnVal = new byte[cbResult]; System.arraycopy(resBuf, 0, returnVal, 0, cbResult); return returnVal; }
From source file:COSE.Recipient.java
public byte[] decrypt(AlgorithmID algCEK, Recipient recip) throws CoseException, InvalidCipherTextException { AlgorithmID alg = AlgorithmID.FromCBOR(findAttribute(HeaderKeys.Algorithm)); byte[] rgbKey = null; if (recip != this) { for (Recipient r : recipientList) { if (recip == r) { rgbKey = r.decrypt(alg, recip); if (rgbKey == null) throw new CoseException("Internal error"); break; } else if (!r.recipientList.isEmpty()) { rgbKey = r.decrypt(alg, recip); if (rgbKey != null) break; }/*from w w w . ja v a2 s .com*/ } } switch (alg) { case Direct: // Direct if (privateKey.get(KeyKeys.KeyType.AsCBOR()) != KeyKeys.KeyType_Octet) throw new CoseException("Mismatch of algorithm and key"); return privateKey.get(KeyKeys.Octet_K.AsCBOR()).GetByteString(); case HKDF_HMAC_SHA_256: if (privateKey.get(KeyKeys.KeyType.AsCBOR()) != KeyKeys.KeyType_Octet) throw new CoseException("Needs to be an octet key"); return HKDF(privateKey.get(KeyKeys.Octet_K.AsCBOR()).GetByteString(), algCEK.getKeySize(), algCEK, new SHA256Digest()); case HKDF_HMAC_SHA_512: if (privateKey.get(KeyKeys.KeyType.AsCBOR()) != KeyKeys.KeyType_Octet) throw new CoseException("Needs to be an octet key"); return HKDF(privateKey.get(KeyKeys.Octet_K.AsCBOR()).GetByteString(), algCEK.getKeySize(), algCEK, new SHA512Digest()); case AES_KW_128: case AES_KW_192: case AES_KW_256: if (rgbKey == null) { if (privateKey.get(KeyKeys.KeyType.AsCBOR()) != KeyKeys.KeyType_Octet) throw new CoseException("Key and algorithm do not agree"); rgbKey = privateKey.get(KeyKeys.Octet_K.AsCBOR()).GetByteString(); } else if (privateKey != null) throw new CoseException("Key and algorithm do not agree"); return AES_KeyWrap_Decrypt(alg, rgbKey); case ECDH_ES_HKDF_256: case ECDH_SS_HKDF_256: if (privateKey.get(KeyKeys.KeyType.AsCBOR()) != KeyKeys.KeyType_EC2) throw new CoseException("Key and algorithm do not agree"); rgbKey = ECDH_GenerateSecret(privateKey); return HKDF(rgbKey, algCEK.getKeySize(), algCEK, new SHA256Digest()); case ECDH_ES_HKDF_512: case ECDH_SS_HKDF_512: if (privateKey.get(KeyKeys.KeyType.AsCBOR()) != KeyKeys.KeyType_EC2) throw new CoseException("Key and algorithm do not agree"); rgbKey = ECDH_GenerateSecret(privateKey); return HKDF(rgbKey, algCEK.getKeySize(), algCEK, new SHA512Digest()); case ECDH_ES_HKDF_256_AES_KW_128: case ECDH_SS_HKDF_256_AES_KW_128: if (privateKey.get(KeyKeys.KeyType.AsCBOR()) != KeyKeys.KeyType_EC2) throw new CoseException("Key and algorithm do not agree"); rgbKey = ECDH_GenerateSecret(privateKey); rgbKey = HKDF(rgbKey, 128, AlgorithmID.AES_KW_128, new SHA256Digest()); return AES_KeyWrap_Decrypt(AlgorithmID.AES_KW_128, rgbKey); case ECDH_ES_HKDF_256_AES_KW_192: case ECDH_SS_HKDF_256_AES_KW_192: if (privateKey.get(KeyKeys.KeyType.AsCBOR()) != KeyKeys.KeyType_EC2) throw new CoseException("Key and algorithm do not agree"); rgbKey = ECDH_GenerateSecret(privateKey); rgbKey = HKDF(rgbKey, 192, AlgorithmID.AES_KW_192, new SHA256Digest()); return AES_KeyWrap_Decrypt(AlgorithmID.AES_KW_192, rgbKey); case ECDH_ES_HKDF_256_AES_KW_256: case ECDH_SS_HKDF_256_AES_KW_256: if (privateKey.get(KeyKeys.KeyType.AsCBOR()) != KeyKeys.KeyType_EC2) throw new CoseException("Key and algorithm do not agree"); rgbKey = ECDH_GenerateSecret(privateKey); rgbKey = HKDF(rgbKey, 256, AlgorithmID.AES_KW_256, new SHA256Digest()); return AES_KeyWrap_Decrypt(AlgorithmID.AES_KW_256, rgbKey); default: throw new CoseException("Unsupported Recipent Algorithm"); } }