protected internal static Cipher InitCipherForBlock(Cipher cipher, int block, IEncryptionInfoBuilder builder, ISecretKey skey, int encryptMode) { EncryptionVerifier ver = builder.GetVerifier(); HashAlgorithm hashAlgo = ver.HashAlgorithm; byte[] blockKey = new byte[4]; LittleEndian.PutUInt(blockKey, 0, block); MessageDigest hashAlg = CryptoFunctions.GetMessageDigest(hashAlgo); hashAlg.Update(skey.GetEncoded()); byte[] encKey = hashAlg.Digest(blockKey); EncryptionHeader header = builder.GetHeader(); int keyBits = header.KeySize; encKey = CryptoFunctions.GetBlock0(encKey, keyBits / 8); if (keyBits == 40) { encKey = CryptoFunctions.GetBlock0(encKey, 16); } ISecretKey key = new SecretKeySpec(encKey, skey.GetAlgorithm()); if (cipher == null) { cipher = CryptoFunctions.GetCipher(key, header.CipherAlgorithm, null, null, encryptMode); } else { cipher.Init(encryptMode, key); } return(cipher); }
public override bool VerifyPassword(String password) { EncryptionVerifier ver = builder.GetVerifier(); ISecretKey skey = GenerateSecretKey(password, ver); try { Cipher cipher = InitCipherForBlock(null, 0, builder, skey, Cipher.DECRYPT_MODE); byte[] encryptedVerifier = ver.EncryptedVerifier; byte[] verifier = new byte[encryptedVerifier.Length]; cipher.Update(encryptedVerifier, 0, encryptedVerifier.Length, verifier); SetVerifier(verifier); byte[] encryptedVerifierHash = ver.EncryptedVerifierHash; byte[] verifierHash = cipher.DoFinal(encryptedVerifierHash); HashAlgorithm hashAlgo = ver.HashAlgorithm; MessageDigest hashAlg = CryptoFunctions.GetMessageDigest(hashAlgo); byte[] calcVerifierHash = hashAlg.Digest(verifier); if (Arrays.Equals(calcVerifierHash, verifierHash)) { SetSecretKey(skey); return(true); } } catch (Exception e) { throw new EncryptedDocumentException(e); } return(false); }
/** * Fills the fields of verifier and header with the calculated hashes based * on the password and a random salt * * see [MS-OFFCRYPTO] - 2.3.4.7 ECMA-376 Document Encryption Key Generation */ public override void ConfirmPassword(String password, byte[] keySpec, byte[] keySalt, byte[] verifier, byte[] verifierSalt, byte[] integritySalt) { StandardEncryptionVerifier ver = builder.GetVerifier(); ver.SetSalt(verifierSalt); ISecretKey secretKey = StandardDecryptor.GenerateSecretKey(password, ver, GetKeySizeInBytes()); SetSecretKey(secretKey); Cipher cipher = GetCipher(secretKey, null); try { byte[] encryptedVerifier = cipher.DoFinal(verifier); MessageDigest hashAlgo = CryptoFunctions.GetMessageDigest(ver.HashAlgorithm); byte[] calcVerifierHash = hashAlgo.Digest(verifier); // 2.3.3 EncryptionVerifier ... // An array of bytes that Contains the encrypted form of the // hash of the randomly generated Verifier value. The length of the array MUST be the size of // the encryption block size multiplied by the number of blocks needed to encrypt the hash of the // Verifier. If the encryption algorithm is RC4, the length MUST be 20 bytes. If the encryption // algorithm is AES, the length MUST be 32 bytes. After decrypting the EncryptedVerifierHash // field, only the first VerifierHashSize bytes MUST be used. int encVerHashSize = ver.CipherAlgorithm.encryptedVerifierHashLength; byte[] encryptedVerifierHash = cipher.DoFinal(Arrays.CopyOf(calcVerifierHash, encVerHashSize)); ver.SetEncryptedVerifier(encryptedVerifier); ver.SetEncryptedVerifierHash(encryptedVerifierHash); } catch (Exception e) { throw new EncryptedDocumentException("Password Confirmation failed", e); } }
public static List <Entry> ReadArchive(byte[] MasterKey) { Stream FileInputStream = File.OpenRead(Settings.Files.ArchivePath); byte[] IV = new byte[Settings.AES.IVBytes]; byte[] Salt = new byte[Settings.AES.SaltBytes]; FileInputStream.Read(IV, 0, IV.Length); FileInputStream.Read(Salt, 0, Salt.Length); byte[] Key = CryptoFunctions.DeriveKey(MasterKey, Salt, Settings.AES.KeyBytes, Settings.AES.AESPBKDF2Iterations); SingleUseAESKey singleUseKey = new SingleUseAESKey(Key, Salt, IV); Stream AESStream = Crypto.AESStream.CreateDecryptionStream(FileInputStream, singleUseKey); EncodingStream DecoderStream = new EncodingStream(AESStream); int EntriesCount = DecoderStream.ReadHeader(); List <Entry> Entries = new List <Entry>(EntriesCount); for (int i = 0; i < EntriesCount; i++) { string Title = DecoderStream.ReadNextString(); string Text = DecoderStream.ReadNextString(); DateTime LastChange = Convert.ToDateTime(DecoderStream.ReadNextString()); Entries.Add(new Entry(Title, Text, LastChange)); } DecoderStream.Close(); AESStream.Close(); FileInputStream.Close(); return(Entries); }
/// <summary> /// 패킷을 보낼 수 있도록 가공한다. (zlib 압축 데이터 여기서 생성) /// </summary> /// <param name="key">Encryption key</param> /// <param name="hmacKey">HMAC generation key</param> /// <param name="prefix">The 6 bytes between the packet size and the IV</param> public void CompressAndAssemble(byte[] key, byte[] hmacKey, byte[] prefix, int count) { // 버퍼를 복구할 수 있도록. _buffer_before_assemble = _buffer; byte[] data = Compression.Compress(_buffer); byte[] Op = BitConverter.GetBytes((short)Opcode); byte[] Len = BitConverter.GetBytes((int)data.Length + 4); // 버퍼 + 압축내용 Array.Reverse(Op); Array.Reverse(Len); byte[] TempData; TempData = BytesUtil.ConcatBytes(Op, Len); TempData = BytesUtil.ConcatBytes(TempData, BitConverter.GetBytes((bool)true)); // 압축임 TempData = BytesUtil.ConcatBytes(TempData, BitConverter.GetBytes((int)_buffer.Length)); // 실제 크기 _buffer = BytesUtil.ConcatBytes(TempData, data); byte[] IV = CryptoGenerators.GenerateIV(); byte[] dataToAssemble = BytesUtil.ConcatBytes( BytesUtil.ConcatBytes(prefix, BitConverter.GetBytes(count)), BytesUtil.ConcatBytes(IV, CryptoFunctions.EncryptPacket(_buffer, key, IV))); _buffer = CryptoFunctions.ClearPacket(dataToAssemble, hmacKey); }
protected internal static ISecretKey GenerateSecretKey(String password, EncryptionVerifier ver) { if (password.Length > 255) { password = password.Substring(0, 255); } HashAlgorithm hashAlgo = ver.HashAlgorithm; MessageDigest hashAlg = CryptoFunctions.GetMessageDigest(hashAlgo); byte[] hash = hashAlg.Digest(StringUtil.GetToUnicodeLE(password)); byte[] salt = ver.Salt; hashAlg.Reset(); for (int i = 0; i < 16; i++) { hashAlg.Update(hash, 0, 5); hashAlg.Update(salt); } hash = new byte[5]; Array.Copy(hashAlg.Digest(), 0, hash, 0, 5); ISecretKey skey = new SecretKeySpec(hash, ver.CipherAlgorithm.jceId); return(skey); }
/// <summary> /// protect a spreadsheet with a password (not encrypted, just sets protect flags and the password.) /// </summary> /// <param name="password">password to set;Pass <code>null</code> to remove all protection</param> /// <param name="shouldProtectObjects">shouldProtectObjects are protected</param> /// <param name="shouldProtectScenarios">shouldProtectScenarios are protected</param> public void ProtectSheet(String password, bool shouldProtectObjects, bool shouldProtectScenarios) { if (password == null) { _passwordRecord = null; _protectRecord = null; _objectProtectRecord = null; _scenarioProtectRecord = null; return; } ProtectRecord prec = this.Protect; PasswordRecord pass = this.Password; prec.Protect = true; pass.Password = (short)CryptoFunctions.CreateXorVerifier1(password); if (_objectProtectRecord == null && shouldProtectObjects) { ObjectProtectRecord rec = CreateObjectProtect(); rec.Protect = (true); _objectProtectRecord = rec; } if (_scenarioProtectRecord == null && shouldProtectScenarios) { ScenarioProtectRecord srec = CreateScenarioProtect(); srec.Protect = (true); _scenarioProtectRecord = srec; } }
protected internal static byte[] hashInput(IEncryptionInfoBuilder builder, byte[] pwHash, byte[] blockKey, byte[] inputKey, int cipherMode) { EncryptionVerifier ver = builder.GetVerifier(); AgileDecryptor dec = (AgileDecryptor)builder.GetDecryptor(); int keySize = dec.GetKeySizeInBytes(); int blockSize = dec.GetBlockSizeInBytes(); HashAlgorithm hashAlgo = ver.HashAlgorithm; byte[] salt = ver.Salt; byte[] intermedKey = CryptoFunctions.GenerateKey(pwHash, hashAlgo, blockKey, keySize); ISecretKey skey = new SecretKeySpec(intermedKey, ver.CipherAlgorithm.jceId); byte[] iv = CryptoFunctions.GenerateIv(hashAlgo, salt, null, blockSize); Cipher cipher = CryptoFunctions.GetCipher(skey, ver.CipherAlgorithm, ver.ChainingMode, iv, cipherMode); byte[] hashFinal; try { inputKey = CryptoFunctions.GetBlock0(inputKey, GetNextBlockSize(inputKey.Length, blockSize)); hashFinal = cipher.DoFinal(inputKey); return(hashFinal); } catch (Exception e) { throw new EncryptedDocumentException(e); } }
public async Task <ActionResult> VerifyLogin([FromBody] AuthUserResource resource) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState.GetErrorMessages())); } var user = _mapper.Map <AuthUserResource, User>(resource); var result = await _userService.FirstOrDefaultAsync(user.Login, user.Password); if (result == null) { return(BadRequest("Erro ao tentar realizar o login.")); } var token = CryptoFunctions.GenerateToken(_configuration, user); return(Ok(new { error = false, result = new { token, user = new { user.Id, user.Login } } })); } catch (Exception ex) { var message = "Erro ao tentar realizar o login."; return(BadRequest(new { error = true, result = new { message } })); } }
public override void ConfirmPassword(String password, byte[] keySpec, byte[] keySalt, byte[] verifier, byte[] verifierSalt, byte[] integritySalt) { BinaryRC4EncryptionVerifier ver = builder.GetVerifier(); ver.SetSalt(verifierSalt); ISecretKey skey = BinaryRC4Decryptor.GenerateSecretKey(password, ver); SetSecretKey(skey); try { Cipher cipher = BinaryRC4Decryptor.InitCipherForBlock(null, 0, builder, skey, Cipher.ENCRYPT_MODE); byte[] encryptedVerifier = new byte[16]; cipher.Update(verifier, 0, 16, encryptedVerifier); ver.EncryptedVerifier = (encryptedVerifier); HashAlgorithm hashAlgo = ver.HashAlgorithm; MessageDigest hashAlg = CryptoFunctions.GetMessageDigest(hashAlgo); byte[] calcVerifierHash = hashAlg.Digest(verifier); byte[] encryptedVerifierHash = cipher.DoFinal(calcVerifierHash); ver.EncryptedVerifierHash = (encryptedVerifierHash); } catch (Exception e) { throw new EncryptedDocumentException("Password Confirmation failed", e); } }
public override bool VerifyPassword(String password) { EncryptionVerifier ver = builder.GetVerifier(); ISecretKey skey = GenerateSecretKey(password, ver, GetKeySizeInBytes()); Cipher cipher = GetCipher(skey); try { byte[] encryptedVerifier = ver.EncryptedVerifier; byte[] verifier = cipher.DoFinal(encryptedVerifier); SetVerifier(verifier); MessageDigest sha1 = CryptoFunctions.GetMessageDigest(ver.HashAlgorithm); byte[] calcVerifierHash = sha1.Digest(verifier); byte[] encryptedVerifierHash = ver.EncryptedVerifierHash; byte[] decryptedVerifierHash = cipher.DoFinal(encryptedVerifierHash); // see 2.3.4.9 Password Verification (Standard Encryption) // ... The number of bytes used by the encrypted Verifier hash MUST be 32 ... // TODO: check and Trim/pad the hashes to 32 byte[] verifierHash = Arrays.CopyOf(decryptedVerifierHash, calcVerifierHash.Length); if (Arrays.Equals(calcVerifierHash, verifierHash)) { SetSecretKey(skey); return(true); } else { return(false); } } catch (Exception e) { throw new EncryptedDocumentException(e); } }
public static void WriteArchive(List <Entry> entries, byte[] MasterKey) { byte[] IV = CryptoFunctions.GenerateCryptoSecureBytes(Settings.AES.IVBytes); byte[] Salt = CryptoFunctions.GenerateCryptoSecureBytes(Settings.AES.SaltBytes); byte[] Key = CryptoFunctions.DeriveKey(MasterKey, Salt, Settings.AES.KeyBytes, Settings.AES.AESPBKDF2Iterations); SingleUseAESKey singleUseKey = new SingleUseAESKey(Key, Salt, IV); Stream FileOutputStream = new FileStream(Settings.Files.ArchivePath, (FileMode)FileAccess.Write); Stream AESStream = Crypto.AESStream.CreateEncryptionStream(FileOutputStream, singleUseKey); EncodingStream EncoderStream = new EncodingStream(AESStream); FileOutputStream.Write(IV, 0, IV.Length); FileOutputStream.Write(Salt, 0, Salt.Length); EncoderStream.WriteHeader(entries.Count); foreach (Entry e in entries) { EncoderStream.WriteString(e.Title); EncoderStream.WriteString(e.Text); EncoderStream.WriteString(e.LastChange.ToString()); } EncoderStream.Close(); AESStream.Close(); FileOutputStream.Close(); }
public static bool ValidatePassword(CT_SheetProtection xobj, String password, String prefix) { if (password == null) { return(false); } string xorHashVal = xobj.password; string algoName = xobj.algorithmName; string hashVal = xobj.hashValue; string saltVal = xobj.saltValue; string spinCount = xobj.spinCount; if (xorHashVal != null) { int hash1 = Int32.Parse(xorHashVal, NumberStyles.HexNumber); int hash2 = CryptoFunctions.CreateXorVerifier1(password); return(hash1 == hash2); } else { if (hashVal == null || algoName == null || saltVal == null || spinCount == null) { return(false); } byte[] hash1 = Convert.FromBase64String(hashVal); HashAlgorithm hashAlgo = HashAlgorithm.FromString(algoName); byte[] salt = Convert.FromBase64String(saltVal); int spinCnt = Int32.Parse(spinCount); byte[] hash2 = CryptoFunctions.HashPassword(password, hashAlgo, salt, spinCnt, false); return(Arrays.Equals(hash1, hash2)); } }
public static void SetPassword(CT_SheetProtection xobj, String password, HashAlgorithm hashAlgo, String prefix) { if (password == null) { xobj.password = null; xobj.algorithmName = null; xobj.hashValue = null; xobj.saltValue = null; xobj.spinCount = null; return; } if (hashAlgo == null) { int hash = CryptoFunctions.CreateXorVerifier1(password); xobj.password = String.Format("{0:X4}", hash).ToUpper(); } else { SecureRandom random = new SecureRandom(); byte[] salt = random.GenerateSeed(16); int spinCount = 100000; byte[] hash = CryptoFunctions.HashPassword(password, hashAlgo, salt, spinCount, false); xobj.algorithmName = hashAlgo.jceId; xobj.hashValue = Convert.ToBase64String(hash); xobj.saltValue = Convert.ToBase64String(salt); xobj.spinCount = "" + spinCount; } }
public override void ConfirmPassword(String password, byte[] keySpec, byte[] keySalt, byte[] verifier, byte[] verifierSalt, byte[] integritySalt) { Debug.Assert(verifier != null && verifierSalt != null); CryptoAPIEncryptionVerifier ver = builder.GetVerifier(); ver.SetSalt(verifierSalt); ISecretKey skey = CryptoAPIDecryptor.GenerateSecretKey(password, ver); SetSecretKey(skey); try { Cipher cipher = InitCipherForBlock(null, 0); byte[] encryptedVerifier = new byte[verifier.Length]; cipher.Update(verifier, 0, verifier.Length, encryptedVerifier); ver.SetEncryptedVerifier(encryptedVerifier); HashAlgorithm hashAlgo = ver.HashAlgorithm; MessageDigest hashAlg = CryptoFunctions.GetMessageDigest(hashAlgo); byte[] calcVerifierHash = hashAlg.Digest(verifier); byte[] encryptedVerifierHash = cipher.DoFinal(calcVerifierHash); ver.SetEncryptedVerifierHash(encryptedVerifierHash); } catch (Exception e) { throw new EncryptedDocumentException("Password Confirmation failed", e); } }
protected internal static Cipher InitCipherForBlock(Cipher existing, int block, bool lastChunk, IEncryptionInfoBuilder builder, ISecretKey skey, int encryptionMode) { EncryptionHeader header = builder.GetHeader(); if (existing == null || lastChunk) { String pAdding = (lastChunk ? "PKCS5PAdding" : "NoPAdding"); existing = CryptoFunctions.GetCipher(skey, header.CipherAlgorithm, header.ChainingMode, header.KeySalt, encryptionMode, pAdding); } byte[] blockKey = new byte[4]; LittleEndian.PutInt(blockKey, 0, block); byte[] iv = CryptoFunctions.GenerateIv(header.HashAlgorithm, header.KeySalt, blockKey, header.BlockSize); AlgorithmParameterSpec aps; if (header.CipherAlgorithm == CipherAlgorithm.rc2) { aps = new RC2ParameterSpec(skey.GetEncoded().Length * 8, iv); } else { aps = new IvParameterSpec(iv); } existing.Init(encryptionMode, skey, aps); return(existing); }
public static string GetPrivateRootUserUploadDirectory( this IWebHostEnvironment hostingEnvironment, Guid?userId = null) { string userFolder = CryptoFunctions.MD5Hash(userId.ToString()).ToLower(); return(Path.Combine(hostingEnvironment.GetPrivateRoot(), Constants.UploadFolderName, Constants.UsersFolderName, userFolder)); }
private ZipEntrySource fileToSource(FileInfo tmpFile, CipherAlgorithm cipherAlgorithm, byte[] keyBytes, byte[] ivBytes) { SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, cipherAlgorithm.jceId); Cipher ciDec = CryptoFunctions.GetCipher(skeySpec, cipherAlgorithm, ChainingMode.cbc, ivBytes, Cipher.DECRYPT_MODE, "PKCS5PAdding"); ZipFile zf = new ZipFile(tmpFile.FullName); return(new AesZipFileZipEntrySource(zf, ciDec)); }
private Cipher GetCipher(ISecretKey key) { EncryptionHeader em = builder.GetHeader(); ChainingMode cm = em.ChainingMode; Debug.Assert(cm == ChainingMode.ecb); return(CryptoFunctions.GetCipher(key, em.CipherAlgorithm, cm, null, Cipher.DECRYPT_MODE)); }
/** * instead of a password, it's also possible to decrypt via certificate. * Warning: this code is experimental and hasn't been validated * * @see <a href="http://social.msdn.microsoft.com/Forums/en-US/cc9092bb-0c82-4b5b-ae21-abf643bdb37c/agile-encryption-with-certificates">Agile encryption with certificates</a> * * @param keyPair * @param x509 * @return true, when the data can be successfully decrypted with the given private key * @throws GeneralSecurityException */ public bool VerifyPassword(KeyPair keyPair, X509Certificate x509) { AgileEncryptionVerifier ver = (AgileEncryptionVerifier)builder.GetVerifier(); AgileEncryptionHeader header = (AgileEncryptionHeader)builder.GetHeader(); HashAlgorithm hashAlgo = header.HashAlgorithm; CipherAlgorithm cipherAlgo = header.CipherAlgorithm; int blockSize = header.BlockSize; AgileCertificateEntry ace = null; foreach (AgileCertificateEntry aceEntry in ver.GetCertificates()) { if (x509.Equals(aceEntry.x509)) { ace = aceEntry; break; } } if (ace == null) { return(false); } Cipher cipher = Cipher.GetInstance("RSA"); cipher.Init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); byte[] keyspec = cipher.DoFinal(ace.encryptedKey); SecretKeySpec secretKey = new SecretKeySpec(keyspec, ver.CipherAlgorithm.jceId); Mac x509Hmac = CryptoFunctions.GetMac(hashAlgo); x509Hmac.Init(secretKey); byte[] certVerifier = x509Hmac.DoFinal(ace.x509.GetEncoded()); byte[] vec = CryptoFunctions.GenerateIv(hashAlgo, header.KeySalt, kIntegrityKeyBlock, blockSize); cipher = GetCipher(secretKey, cipherAlgo, ver.ChainingMode, vec, Cipher.DECRYPT_MODE); byte[] hmacKey = cipher.DoFinal(header.GetEncryptedHmacKey()); hmacKey = GetBlock0(hmacKey, hashAlgo.hashSize); vec = CryptoFunctions.GenerateIv(hashAlgo, header.KeySalt, kIntegrityValueBlock, blockSize); cipher = GetCipher(secretKey, cipherAlgo, ver.ChainingMode, vec, Cipher.DECRYPT_MODE); byte[] hmacValue = cipher.DoFinal(header.GetEncryptedHmacValue()); hmacValue = GetBlock0(hmacValue, hashAlgo.hashSize); if (Arrays.Equals(ace.certVerifier, certVerifier)) { SetSecretKey(secretKey); SetIntegrityHmacKey(hmacKey); SetIntegrityHmacValue(hmacValue); return(true); } else { return(false); } }
public void Decrypt(byte[] key) { _buffer = CryptoFunctions.DecryptPacket(_buffer, key); if (_buffer.Length > 12) { if (_buffer[11] == 0x78 && _buffer[12] == 0x01) { _buffer = Compression.UncompressPacket(_buffer); } } }
protected static byte[] FillAndXor(byte[] hash, byte FillByte) { byte[] buff = new byte[64]; Arrays.Fill(buff, FillByte); for (int i = 0; i < hash.Length; i++) { buff[i] = (byte)(buff[i] ^ hash[i]); } MessageDigest sha1 = CryptoFunctions.GetMessageDigest(HashAlgorithm.sha1); return(sha1.Digest(buff)); }
protected internal static ISecretKey GenerateSecretKey(String password, EncryptionVerifier ver) { if (password.Length > 255) { password = password.Substring(0, 255); } HashAlgorithm hashAlgo = ver.HashAlgorithm; MessageDigest hashAlg = CryptoFunctions.GetMessageDigest(hashAlgo); hashAlg.Update(ver.Salt); byte[] hash = hashAlg.Digest(StringUtil.GetToUnicodeLE(password)); ISecretKey skey = new SecretKeySpec(hash, ver.CipherAlgorithm.jceId); return(skey); }
/** * Validates the password, i.e. * calculates the hash of the given password and Compares it against the stored hash * * @param xobj the xmlbeans object which Contains the password attributes * @param password the password, if null the method will always return false, * even if there's no password Set * @param prefix the prefix of the password attributes, may be null * * @return true, if the hashes match */ public static bool ValidatePassword(XmlNode xobj, String password, String prefix) { // TODO: is "velvetSweatshop" the default password? if (password == null) { return(false); } XPathNavigator cur = xobj.CreateNavigator(); cur.MoveToAttribute("password", prefix); String xorHashVal = cur.Value; cur.MoveToAttribute("algorithmName", prefix); String algoName = cur.Value; cur.MoveToAttribute("hashValue", prefix); String hashVal = cur.Value; cur.MoveToAttribute("saltValue", prefix); String saltVal = cur.Value; cur.MoveToAttribute("spinCount", prefix); String spinCount = cur.Value; //cur.Dispose(); if (xorHashVal != null) { int hash1 = Int32.Parse(xorHashVal, NumberStyles.HexNumber); int hash2 = CryptoFunctions.CreateXorVerifier1(password); return(hash1 == hash2); } else { if (hashVal == null || algoName == null || saltVal == null || spinCount == null) { return(false); } byte[] hash1 = Convert.FromBase64String(hashVal); HashAlgorithm hashAlgo = HashAlgorithm.FromString(algoName); byte[] salt = Convert.FromBase64String(saltVal); int spinCnt = Int32.Parse(spinCount); byte[] hash2 = CryptoFunctions.HashPassword(password, hashAlgo, salt, spinCnt, false); return(Arrays.Equals(hash1, hash2)); } }
/** * Sign (encrypt) the digest with the private key. * Currently only rsa is supported. * * @param digest the hashed input * @return the encrypted hash */ public byte[] signDigest(byte[] digest) { Cipher cipher = CryptoFunctions.GetCipher(signatureConfig.GetKey(), CipherAlgorithm.rsa , ChainingMode.ecb, null, Cipher.ENCRYPT_MODE, "PKCS1PAdding"); //try { // MemoryStream digestInfoValueBuf = new MemoryStream(); // digestInfoValueBuf.Write(signatureConfig.GetHashMagic()); // digestInfoValueBuf.Write(digest); // byte[] digestInfoValue = digestInfoValueBuf.ToArray(); // byte[] signatureValue = cipher.DoFinal(digestInfoValue); // return signatureValue; //} catch (Exception e) { // throw new EncryptedDocumentException(e); //} throw new NotImplementedException(); }
public void TestXorEncryption1() { // Xor-Password: abc // 2.5.343 XORObfuscation // key = 20810 // verifier = 52250 int verifier = CryptoFunctions.CreateXorVerifier1("abc"); int key = CryptoFunctions.CreateXorKey1("abc"); Assert.AreEqual(20810, key); Assert.AreEqual(52250, verifier); byte[] xorArrAct = CryptoFunctions.CreateXorArray1("abc"); byte[] xorArrExp = HexRead.ReadFromString("AC-CC-A4-AB-D6-BA-C3-BA-D6-A3-2B-45-D3-79-29-BB"); //assertThat(xorArrExp, EqualTo(xorArrAct)); Assert.That(xorArrExp, Is.EqualTo(xorArrAct)); }
/** * Generate an HMAC, as specified in [RFC2104], of the encrypted form of the data (message), * which the DataIntegrity element will verify by using the Salt generated in step 2 as the key. * Note that the entire EncryptedPackage stream (1), including the StreamSize field, MUST be * used as the message. * * Encrypt the HMAC as in step 3 by using a blockKey byte array consisting of the following bytes: * 0xa0, 0x67, 0x7f, 0x02, 0xb2, 0x2c, 0x84, and 0x33. **/ protected void UpdateIntegrityHMAC(FileInfo tmpFile, int oleStreamSize) { // as the integrity hmac needs to contain the StreamSize, // it's not possible to calculate it on-the-fly while buffering // TODO: add stream size parameter to GetDataStream() AgileEncryptionVerifier ver = builder.GetVerifier(); HashAlgorithm hashAlgo = ver.HashAlgorithm; Mac integrityMD = CryptoFunctions.GetMac(hashAlgo); integrityMD.Init(new SecretKeySpec(integritySalt, hashAlgo.jceHmacId)); byte[] buf = new byte[1024]; LittleEndian.PutLong(buf, 0, oleStreamSize); integrityMD.Update(buf, 0, LittleEndian.LONG_SIZE); FileStream fis = tmpFile.Create(); try { int readBytes; while ((readBytes = fis.Read(buf, 0, buf.Length)) > 0) { integrityMD.Update(buf, 0, readBytes); } } finally { fis.Close(); } byte[] hmacValue = integrityMD.DoFinal(); AgileEncryptionHeader header = builder.GetHeader(); int blockSize = header.BlockSize; byte[] iv = CryptoFunctions.GenerateIv(header.HashAlgorithm, header.KeySalt, AgileDecryptor.kIntegrityValueBlock, blockSize); Cipher cipher = CryptoFunctions.GetCipher(GetSecretKey(), header.CipherAlgorithm, header.ChainingMode, iv, Cipher.ENCRYPT_MODE); byte[] hmacValueFilled = GetBlock0(hmacValue, AgileDecryptor.GetNextBlockSize(hmacValue.Length, blockSize)); byte[] encryptedHmacValue = cipher.DoFinal(hmacValueFilled); header.SetEncryptedHmacValue(encryptedHmacValue); }
protected internal static Cipher InitCipherForBlock(Cipher cipher, int block, IEncryptionInfoBuilder builder, ISecretKey skey, int encryptMode) { EncryptionVerifier ver = builder.GetVerifier(); HashAlgorithm hashAlgo = ver.HashAlgorithm; byte[] blockKey = new byte[4]; LittleEndian.PutUInt(blockKey, 0, block); byte[] encKey = CryptoFunctions.GenerateKey(skey.GetEncoded(), hashAlgo, blockKey, 16); ISecretKey key = new SecretKeySpec(encKey, skey.GetAlgorithm()); if (cipher == null) { EncryptionHeader em = builder.GetHeader(); cipher = CryptoFunctions.GetCipher(key, em.CipherAlgorithm, null, null, encryptMode); } else { cipher.Init(encryptMode, key); } return(cipher); }
private void CopyToFile(InputStream is1, FileInfo tmpFile, CipherAlgorithm cipherAlgorithm, byte[] keyBytes, byte[] ivBytes) { SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, cipherAlgorithm.jceId); Cipher ciEnc = CryptoFunctions.GetCipher(skeySpec, cipherAlgorithm, ChainingMode.cbc, ivBytes, Cipher.ENCRYPT_MODE, "PKCS5PAdding"); ZipInputStream zis = new ZipInputStream(is1); //FileOutputStream fos = new FileOutputStream(tmpFile); //ZipOutputStream zos = new ZipOutputStream(fos); //ZipEntry ze; //while ((ze = zis.NextEntry) != null) //{ // // the cipher output stream pads the data, therefore we can't reuse the ZipEntry with Set sizes // // as those will be validated upon close() // ZipEntry zeNew = new ZipEntry(ze.Name); // zeNew.Comment = (/*setter*/ze.Comment); // zeNew.Extra = (/*setter*/ze.Extra); // zeNew.Time = (/*setter*/ze.Time); // // zeNew.Method=(/*setter*/ze.Method); // zos.PutNextEntry(zeNew); // FilterOutputStream fos2 = new FilterOutputStream(zos) // { // // don't close underlying ZipOutputStream // public void close() { } //}; //CipherOutputStream cos = new CipherOutputStream(fos2, ciEnc); // IOUtils.Copy(zis, cos); // cos.Close(); // fos2.Close(); // zos.CloseEntry(); // zis.CloseEntry(); //} //zos.Close(); //fos.Close(); //zis.Close(); throw new NotImplementedException(); }
public BaseResponseModel Register(RegisterRequestModel reqModel) { var response = new BaseResponseModel(); if (Data.UserData.GetUserByEmail(reqModel.Email) == null) { var newUser = AccountMaps.MapRegiserRequestModelToUser(reqModel); newUser = CryptoFunctions.CreateCryptoForPassword(newUser); var saveduser = Data.UserData.CreateNewUser(newUser); if (saveduser != null) { response.Success = true; return(response); } response.NoSuccessReason = "Failed To Create Account"; } if (response.NoSuccessReason.Length <= 0) { response.NoSuccessReason = "Email Already Taken"; } response.Success = false; return(response); }