/// <summary> /// Set the key name in keyHandle according to identityName and params. /// </summary> /// protected static internal void setKeyName(TpmKeyHandle keyHandle, Name identityName, KeyParams paras) { Name.Component keyId; if (paras.getKeyIdType() == net.named_data.jndn.security.KeyIdType.USER_SPECIFIED) { keyId = paras.getKeyId(); } else if (paras.getKeyIdType() == net.named_data.jndn.security.KeyIdType.SHA256) { byte[] digest = net.named_data.jndn.util.Common.digestSha256(keyHandle.derivePublicKey() .buf()); keyId = new Name.Component(digest); } else if (paras.getKeyIdType() == net.named_data.jndn.security.KeyIdType.RANDOM) { if (paras.getKeyId().getValue().size() == 0) { throw new TpmBackEnd.Error( "setKeyName: The keyId is empty for type RANDOM"); } keyId = paras.getKeyId(); } else { throw new TpmBackEnd.Error("setKeyName: unrecognized params.getKeyIdType()"); } keyHandle.setKeyName(net.named_data.jndn.security.pib.PibKey.constructKeyName(identityName, keyId)); }
/// <summary> /// Initialize the Cipher MAC. /// <para>Uses the Key or IKM field, and optionally the IV field of the KeyParams class.</para> /// </summary> /// /// <param name="MacKey">A byte array containing the cipher Key. /// <para>Key size must be one of the <c>LegalKeySizes</c> of the underlying cipher.</para> /// </param> /// <param name="IV">A byte array containing the cipher Initialization Vector. /// <para>IV size must be the ciphers blocksize.</para></param> /// /// <exception cref="CryptoMacException">Thrown if an invalid Input size is chosen</exception> public void Initialize(byte[] MacKey, byte[] IV) { if (MacKey == null) { throw new CryptoMacException("CMAC:Initialize", "Key can not be null!", new ArgumentNullException()); } if (IV == null) { IV = new byte[m_blockSize]; } if (IV.Length != m_blockSize) { Array.Resize <byte>(ref IV, m_blockSize); } m_cipherKey = new KeyParams(MacKey, IV); m_cipherMode.Initialize(true, m_cipherKey); byte[] lu = new byte[m_blockSize]; byte[] tmpz = new byte[m_blockSize]; m_cipherMode.Transform(tmpz, 0, lu, 0); m_K1 = GenerateSubkey(lu); m_K2 = GenerateSubkey(m_K1); m_cipherMode.Initialize(true, m_cipherKey); m_isInitialized = true; }
/// <summary> /// Initialize the Cipher /// </summary> /// /// <param name="KeyParam">Cipher key container. /// <para>Uses the Key and IV fields of KeyParam. /// The <see cref="LegalKeySizes"/> property contains valid Key sizes. /// IV must be 8 bytes in size.</para> /// </param> /// /// <exception cref="System.ArgumentNullException">Thrown if a null key or iv is used</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown if an invalid key or iv size is used</exception> public void Initialize(KeyParams KeyParam) { if (KeyParam.IV == null) { throw new CryptoSymmetricException("Salsa20:Initialize", "Init parameters must include an IV!", new ArgumentException()); } if (KeyParam.IV.Length != 8) { throw new CryptoSymmetricException("Salsa20:Initialize", "Requires exactly 8 bytes of IV!", new ArgumentOutOfRangeException()); } Reset(); if (KeyParam.Key == null) { if (!_isInitialized) { throw new CryptoSymmetricException("ChaCha:Initialize", "Key can not be null for first initialisation!", new ArgumentException()); } SetKey(null, KeyParam.IV); } else { if (KeyParam.Key.Length != 16 && KeyParam.Key.Length != 32) { throw new CryptoSymmetricException("ChaCha:Initialize", "Key must be 16 or 32 bytes!", new ArgumentOutOfRangeException()); } SetKey(KeyParam.Key, KeyParam.IV); } _isInitialized = true; }
public static async Task SetValueSlow(this DOMInputElement inputElement, Browser browser, string val, bool clear = false) { inputElement.Focus(); await Task.Delay(100); inputElement.Click(); await Task.Delay(100); foreach (char c in val) { var param = new KeyParams(VirtualKeyCode.VK_E, c); if (c.ToString() == " ") { param = new KeyParams(VirtualKeyCode.SPACE, ' '); } browser.KeyDown(param); browser.KeyUp(param); await Task.Delay(100); } }
private void Dispose(bool Disposing) { if (!_isDisposed && Disposing) { try { if (_digestMac != null && _disposeEngine) { _digestMac.Dispose(); _digestMac = null; } if (_macKey != null) { _macKey.Dispose(); _macKey = null; } if (_Salt != null) { Array.Clear(_Salt, 0, _Salt.Length); _Salt = null; } } finally { _isDisposed = true; } } }
public static async Task SetValue(this DOMInputElement inputElement, Browser browser, string val, bool clear = false) { inputElement.Focus(); inputElement.Click(); if (clear) { for (int i = 0; i < 100; i++) //CLEAR { var param = new KeyParams(VirtualKeyCode.BACK, (char)8); browser.KeyDown(param); browser.KeyUp(param); await Task.Delay(2); } await Task.Delay(1); } foreach (char c in val) { var param = new KeyParams(VirtualKeyCode.VK_E, c); if (c.ToString() == " ") { param = new KeyParams(VirtualKeyCode.SPACE, ' '); } browser.KeyDown(param); browser.KeyUp(param); await Task.Delay(10); } }
/// <summary> /// Initialize the Cipher /// </summary> /// /// <param name="Encryption">True if cipher is used for encryption, false to decrypt</param> /// <param name="KeyParam">The KeyParams containing key and vector</param> /// /// <exception cref="CryptoSymmetricException">Thrown if a null Key or IV is used</exception> public void Initialize(bool Encryption, KeyParams KeyParam) { // recheck params Scope(); if (KeyParam.Key == null) { throw new CryptoSymmetricException("CTR:Initialize", "Key can not be null!", new ArgumentNullException()); } if (KeyParam.IV == null) { throw new CryptoSymmetricException("CTR:Initialize", "IV can not be null!", new ArgumentNullException()); } if (IsParallel && ParallelBlockSize < ParallelMinimumSize || ParallelBlockSize > ParallelMaximumSize) { throw new CryptoSymmetricException("CTR:Initialize", "The parallel block size is out of bounds!"); } if (IsParallel && ParallelBlockSize % ParallelMinimumSize != 0) { throw new CryptoSymmetricException("CTR:Initialize", "The parallel block size must be evenly aligned to the ParallelMinimumSize!"); } m_blockCipher.Initialize(true, KeyParam); m_ctrVector = KeyParam.IV; m_isEncryption = Encryption; m_isInitialized = true; }
protected void DefaultResultMap() { ResultMap = ResultMap ?? CreateParams( "message", typeof(string), "if success was false, the reason why", "success", typeof(bool), "true if command was successful"); }
/// <summary> /// Get the file extension key associated with a subkey /// </summary> /// /// <param name="KeyId">The id of the subkey</param> /// /// <returns>The keys extension array</returns> public byte[] GetExtensionKey(byte[] KeyId) { try { long keyPos; int index; // get the key data MemoryStream keyStream = GetKeyStream(); // get the keying materials starting offset within the key file keyPos = PackageKey.SubKeyOffset(keyStream, KeyId); if (keyPos == -1) { throw new CryptoProcessingException("PackageFactory:GetExtensionKey", "This package does not contain the key file!", new ArgumentException()); } // get the index index = PackageKey.IndexFromId(keyStream, KeyId); // key flagged PostOverwrite was used for decryption and was erased if (PackageKey.KeyHasPolicy(m_keyPackage.SubKeyPolicy[index], (long)PackageKeyStates.Erased)) { throw new CryptoProcessingException("PackageFactory:GetExtensionKey", "SubKey is erased. The subkey has a post erase policy and was previously used to decrypt the file.", new Exception()); } // get the keying material KeyParams keyParam = GetKeySet(keyStream, m_keyPackage.Description, keyPos); return(keyParam.ExtKey); } catch { throw; } }
/// <summary> /// Initialize the HMAC /// </summary> /// /// <param name="KeyParam">HMAC Key. /// <para>Uses the Key field of the <see cref="KeyParams"/> class, <c>Key</c> parameter. /// Key should be equal in size to the <see cref="DigestSize"/></para> /// </param> /// /// <exception cref="CryptoMacException">Thrown if the Key is null or less than digest size</exception> public void Initialize(KeyParams KeyParam) { if (KeyParam.Key == null) { throw new CryptoMacException("HMAC:Initialize", "Key can not be null!", new ArgumentNullException()); } _msgDigest.Reset(); int keyLength = KeyParam.Key.Length; // compress to digest size if (KeyParam.Key.Length > _blockSize) { _msgDigest.BlockUpdate(KeyParam.Key, 0, KeyParam.Key.Length); _msgDigest.DoFinal(_inputPad, 0); keyLength = _digestSize; } else { Array.Copy(KeyParam.Key, 0, _inputPad, 0, keyLength); } Array.Clear(_inputPad, keyLength, _blockSize - keyLength); Array.Copy(_inputPad, 0, _outputPad, 0, _blockSize); XOR(_inputPad, IPAD); XOR(_outputPad, OPAD); // initialise the digest _msgDigest.BlockUpdate(_inputPad, 0, _inputPad.Length); _isInitialized = true; }
/// <summary> /// Add an identity for the identityName. /// </summary> /// /// <param name="identityName">The name of the identity.</param> /// <param name="params"></param> /// <returns>The created PibIdentity instance.</returns> public PibIdentity addIdentity(Name identityName, KeyParams paras) { PibIdentity identity = keyChain_.createIdentityV2(identityName, paras); ILOG.J2CsMapping.Collections.Collections.Add(identityNames_, identityName); return(identity); }
private void DescriptionTest(CipherDescription Description) { AllocateRandom(ref _iv, 16); AllocateRandom(ref _key, 32); AllocateRandom(ref _plnText); KeyParams kp = new KeyParams(_key, _iv); MemoryStream mIn = new MemoryStream(_plnText); MemoryStream mOut = new MemoryStream(); MemoryStream mRes = new MemoryStream(); CipherStream cs = new CipherStream(Description); cs.Initialize(true, kp); cs.Write(mIn, mOut); mOut.Seek(0, SeekOrigin.Begin); cs.Initialize(false, kp); cs.Write(mOut, mRes); if (!Evaluate.AreEqual(mRes.ToArray(), _plnText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } }
/// <remarks> /// Encrypts the key package buffer /// </remarks> private void TransformBuffer(byte[] KeyData, byte[] Salt) { byte[] kvm = new byte[48]; // use salt to derive key and counter vector using (Keccak512 digest = new Keccak512(384)) kvm = digest.ComputeHash(Salt); byte[] key = new byte[32]; byte[] iv = new byte[16]; Buffer.BlockCopy(kvm, 0, key, 0, key.Length); Buffer.BlockCopy(kvm, key.Length, iv, 0, iv.Length); byte[] outData = new byte[KeyData.Length]; using (KeyParams keyparam = new KeyParams(key, iv)) { // 32 rounds of serpent using (CTR cipher = new CTR(new SHX())) { cipher.Initialize(true, keyparam); cipher.Transform(KeyData, outData); } } Buffer.BlockCopy(outData, 0, KeyData, 0, KeyData.Length); }
/// <summary> /// Initialize the Cipher /// </summary> /// /// <param name="Encryption">True if cipher is used for encryption, false to decrypt</param> /// <param name="KeyParam">The KeyParams containing the key and vector</param> /// /// <exception cref="CryptoSymmetricException">Thrown if a null Key or IV is used</exception> public void Initialize(bool Encryption, KeyParams KeyParam) { if (KeyParam.Key == null) { throw new CryptoSymmetricException("OFB:Initialize", "Key can not be null!", new ArgumentNullException()); } if (KeyParam.IV == null) { throw new CryptoSymmetricException("OFB:Initialize", "IV can not be null!", new ArgumentNullException()); } m_blockCipher.Initialize(true, KeyParam); byte[] iv = KeyParam.IV; if (iv.Length < m_ofbIv.Length) { // prepend the supplied IV with zeros per FIPS PUB 81 Array.Copy(iv, 0, m_ofbIv, m_ofbIv.Length - iv.Length, iv.Length); for (int i = 0; i < m_ofbIv.Length - iv.Length; i++) { m_ofbIv[i] = 0; } } else { Array.Copy(iv, 0, m_ofbIv, 0, m_ofbIv.Length); } m_isEncryption = Encryption; m_isInitialized = true; }
/// <summary> /// Initialize the Cipher /// </summary> /// /// <param name="Encryption">True if cipher is used for encryption, false to decrypt</param> /// <param name="KeyParam">KeyParams containing key and vector</param> /// /// <exception cref="CryptoSymmetricException">Thrown if a null Key or IV is used</exception> public void Initialize(bool Encryption, KeyParams KeyParam) { // recheck params Scope(); if (KeyParam.Key == null) { throw new CryptoSymmetricException("CFB:Initialize", "Key can not be null!", new ArgumentNullException()); } if (KeyParam.IV == null) { throw new CryptoSymmetricException("CFB:Initialize", "IV can not be null!", new ArgumentNullException()); } if (IsParallel && ParallelBlockSize < ParallelMinimumSize || ParallelBlockSize > ParallelMaximumSize) { throw new CryptoSymmetricException("CFB:Initialize", "The parallel block size is out of bounds!"); } if (IsParallel && ParallelBlockSize % ParallelMinimumSize != 0) { throw new CryptoSymmetricException("CFB:Initialize", "The parallel block size must be evenly aligned to the ParallelMinimumSize!"); } byte[] iv = KeyParam.IV; int diff = m_cfbIv.Length - iv.Length; Buffer.BlockCopy(iv, 0, m_cfbIv, diff, iv.Length); Array.Clear(m_cfbIv, 0, diff); m_blockCipher.Initialize(true, KeyParam); m_isEncryption = Encryption; m_isInitialized = true; }
//public static string DecryptStream(Stream str, string keyStrBase64) //{ // byte[] keyBytes = Convert.FromBase64String(keyStrBase64); // string keyStr = Encoding.UTF8.GetString(keyBytes); // Security.Encryption.EncryptedData encryptedData = Security.Encryption.EncryptedData.DeserializeJSON(keyStr); // encryptedData.Content = str.ReadFully(); // return Security.Encryption.DecryptToString(encryptedData); //} public static byte[] Decrypt(byte[] dataIn, KeyParams keyParams) //, string passphrase = null) { //byte[] decryptedData = null; ////KeyParams kp = new KeyParams(keyParams.Key, keyParams.IV, new byte[3] { 1, 2, 3 }); // RSM: Rijndael and Serpent merged. HKDF key schedule and up to 42 rounds of diffusion using (ICipherMode cipher = new CTR(new RSM(42, 32))) // TSM(32))) //, 32))) // TODO: Test TSM! ... for RSM: RSM(18, 32) { // init with key and iv //////cipher.Initialize(false, keyParams); //////using (CipherStream sc = new CipherStream(cipher)) //////{ ////// MemoryStream dataOut = new MemoryStream(); ////// sc.Initialize(false, keyParams); ////// // encrypt the buffer ////// sc.Write(new MemoryStream(dataIn), dataOut); ////// return dataOut.ToArray(); //////} //////////using (CompressionCipher cstrm = new CompressionCipher(true, cipher)) using (CompressionCipher cstrm = new CompressionCipher(cipher)) { using (MemoryStream dataInStream = new MemoryStream(dataIn)) using (MemoryStream dataOutStream = new MemoryStream()) { //////var dataInMemStream = ; // TODO: rollup in Initialize cstrm.Initialize(false, keyParams); cstrm.Write(dataInStream, dataOutStream); return(dataOutStream.ToArray()); } } } }
/// <summary> /// The DtmForwardKeyStruct primary constructor /// </summary> /// /// <param name="Key">The forward symmetric cipher key</param> /// <param name="SessionParams">The forward symmetric cipher description</param> /// <param name="LifeSpan">The time (in seconds, milliseconds, or ticks) that this key is to be considered valid</param> /// <param name="Instruction">A flag indicating a special handling instruction</param> /// <param name="OptionsFlag">Can be additonal information; like a 'valid from' UTC time stamp</param> public DtmForwardKeyStruct(KeyParams Key, DtmSessionStruct SessionParams, long LifeSpan = 0, short Instruction = 0, long OptionsFlag = 0) { this.Key = Key; this.SessionParams = SessionParams; this.LifeSpan = LifeSpan; this.Instruction = Instruction; this.OptionsFlag = OptionsFlag; }
private void button2_Click(object sender, EventArgs e) { KeyParams paramers = new KeyParams(VirtualKeyCode.TAB, (char)9); _browser.KeyDown(paramers); _browser.KeyUp(paramers); Debug.WriteLine("Tab"); }
/// <summary> /// Write the key data from the key stream /// </summary> /// /// <param name="KeyStream">The stream containing a session key</param> /// <param name="KeyParam">KeyParams class containing the keying material</param> public static void SetKey(Stream KeyStream, KeyParams KeyParam) { byte[] key = KeyParam.Key; byte[] iv = KeyParam.IV; KeyStream.Seek(HDR_SIZE, SeekOrigin.Begin); KeyStream.Write(key, 0, key.Length); KeyStream.Write(iv, 0, iv.Length); }
/// <summary> /// Decrypt the files in the specified directory /// </summary> /// /// <param name="FilePaths">A list of the files to be processed</param> /// /// <exception cref="CryptoProcessingException">Thrown if the VolumeKey does not contain enough keys to encrypt all the files in the directory</exception> public void Decrypt(string[] FilePaths) { if (FilePaths.Length < 1) { throw new CryptoProcessingException("VolumeCipher:Transform", "The file paths list is empty!", new ArgumentException()); } InitializeProgress(FilePaths); if (m_progressTotal < 1) { throw new CryptoProcessingException("VolumeCipher:Initialize", "The files are all zero bytes!", new ArgumentException()); } long prgCtr = 0; for (int i = 0; i < FilePaths.Length; ++i) { FileStream inpStream = GetStream(FilePaths[i], true); VolumeHeader vh = GetHeader(inpStream); KeyParams key = VolumeKey.FromId(m_keyStream, vh.FileId); // user dropped a file in, notify or log if (key == null) { if (ErrorNotification != null) { ErrorNotification(this, string.Format("The file {0}; has no key assigned", FilePaths[i])); } } else { FileStream outStream = GetStream(FilePaths[i], false); if (inpStream == null || outStream == null) { if (ErrorNotification != null) { ErrorNotification(this, string.Format("The file {0}; could not be written to", FilePaths[i])); } } else { m_volumeKey.State[m_volumeKey.GetIndex(vh.FileId)] = (byte)VolumeKeyStates.Decrypted; m_cipherStream.Initialize(false, key); m_cipherStream.Write(inpStream, outStream); outStream.SetLength(outStream.Length - VolumeHeader.GetHeaderSize); prgCtr += inpStream.Position; CalculateProgress(prgCtr); inpStream.Dispose(); outStream.Dispose(); UpdateKey(); } } } }
/// <summary> /// Constructs a DtmForwardKeyStruct from a stream /// </summary> /// /// <param name="SessionStream">Stream containing a serialized DtmForwardKeyStruct</param> /// /// <returns>A populated DtmForwardKeyStruct</returns> public DtmForwardKeyStruct(Stream SessionStream) { BinaryReader reader = new BinaryReader(SessionStream); Key = KeyParams.DeSerialize(SessionStream); SessionParams = new DtmSessionStruct(SessionStream); LifeSpan = reader.ReadInt64(); Instruction = reader.ReadInt16(); OptionsFlag = reader.ReadInt64(); }
protected void AddVersion(KeyParams value) { VersionSelected = value; var copy = ParameterVersions; if (!copy.Contains(VersionSelected)) { copy.Add(VersionSelected); } }
/// <summary> /// Initialize the Cipher /// </summary> /// /// <param name="Encryption">Using Encryption or Decryption mode</param> /// <param name="KeyParam">KeyParam containing key and vector</param> /// /// <exception cref="CryptoSymmetricException">Thrown if a null Key is used</exception> public void Initialize(bool Encryption, KeyParams KeyParam) { if (KeyParam.Key == null) { throw new CryptoSymmetricException("ECB:Initialize", "Key can not be null!", new ArgumentNullException()); } _blockCipher.Initialize(Encryption, KeyParam); _isEncryption = Encryption; _isInitialized = true; }
protected string AddUsage(KeyParams parameters, string description) { AddVersion(parameters); if (string.IsNullOrEmpty(Name)) { throw new NullReferenceException(GetType().Name); } string usage = Name + " " + CommandInfo.ToBNF(parameters.Parameters); return(AddUsage(usage, description)); }
/// <summary> /// Initialize the Cipher. /// </summary> /// /// <param name="Encryption">Using Encryption or Decryption mode</param> /// <param name="KeyParam">Cipher key container. <para>The <see cref="LegalKeySizes"/> property contains valid sizes.</para></param> /// /// <exception cref="CryptoSymmetricException">Thrown if a null or invalid key is used</exception> public void Initialize(bool Encryption, KeyParams KeyParam) { if (KeyParam.Key == null) { throw new CryptoSymmetricException("TFX:Initialize", "Invalid key! Key can not be null.", new ArgumentNullException()); } if (KeyParam.Key.Length != 16 && KeyParam.Key.Length != 24 && KeyParam.Key.Length != 32 && KeyParam.Key.Length != 64) { throw new CryptoSymmetricException("TFX:Initialize", "Invalid key size! Valid sizes are 16, 24, 32 and 64 bytes.", new ArgumentOutOfRangeException()); } _isEncryption = Encryption; _expKey = ExpandKey(KeyParam.Key); }
static void Main(string[] args) { Console.WriteLine("Hello World!"); // GMSS/JWT test string testLabel = "MarekTest123"; var keyPairFiles = GMSS.GenerateGMSSKeys(testLabel); JwtPayload jwtPayload = new JwtPayload(); jwtPayload.Issuer = "Marek"; jwtPayload.IssuedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); jwtPayload.NotBefore = jwtPayload.IssuedAt; jwtPayload.Expires = jwtPayload.NotBefore + 3600; jwtPayload.Subject = "MarekTester"; jwtPayload.Audience = "MarekTest"; var jwtEncoded = JsonWebToken.Encode(jwtPayload, keyPairFiles.Item1, JwtAlgorithm.GMSS512); var jwtDecoded = JsonWebToken.Decode(jwtEncoded, keyPairFiles.Item2, "", ""); return; // GMSS TEST TestSign(GMSSParamSets.FromName(GMSSVersion)); return; // RSM/TSM TEST: KeyParams keyParams = null; byte[] test = Encoding.UTF8.GetBytes("ala ma kotka"); var testStream = new MemoryStream(test); using (KeyGenerator kg = new KeyGenerator()) { keyParams = kg.GetKeyParams(192, 32, 32); // for TSM: kg.GetKeyParams(192, 16, 16); // for RSM: kg.GetKeyParams(192, 32, 32); } var testEncrypted = Encrypt(test, keyParams); var testDecrypted = Decrypt(testEncrypted, keyParams); var xxxxx = Encoding.UTF8.GetString(testDecrypted); }
public void GenerateRandom() { byte[] rngBytes = new byte[Program.RNG_COUNT * Program.INT_SIZE]; ChaCha20 chaCha20 = new ChaCha20 { IsParallel = false }; var keyParam = new KeyParams(Guid.NewGuid().ToByteArray(), Guid.NewGuid().ToByteArray().Take(8).ToArray()); chaCha20.Initialize(keyParam); chaCha20.Transform(rngBytes, rngBytes); chaCha20.Dispose(); }
/// <summary> /// Extract a KeyParams and CipherKey /// </summary> /// /// <param name="KeyHeader">The <see cref="VTDev.Libraries.CEXEngine.Crypto.Processing.Structure.CipherKey"/> that receives the cipher description, key id, and extension key</param> /// <param name="KeyParam">The <see cref="VTDev.Libraries.CEXEngine.Crypto.Common.KeyParams"/> container that receives the key material from the file</param> /// /// <exception cref="CryptoProcessingException">Thrown if the key file could not be found or a Header parameter does not match the keystream length</exception> public void Extract(out CipherKey KeyHeader, out KeyParams KeyParam) { m_keyStream.Seek(0, SeekOrigin.Begin); KeyHeader = new CipherKey(m_keyStream); CipherDescription dsc = KeyHeader.Description; if (m_keyStream.Length < dsc.KeySize + dsc.IvSize + dsc.MacKeySize + CipherKey.GetHeaderSize()) { throw new CryptoProcessingException("KeyFactory:Extract", "The size of the key file does not align with the CipherKey sizes! Key is corrupt.", new ArgumentOutOfRangeException()); } m_keyStream.Seek(CipherKey.GetHeaderSize(), SeekOrigin.Begin); KeyParam = KeyParams.DeSerialize(m_keyStream); }
/// <summary> /// Create a key for the identityName according to params. The created key is /// named /{identityName}/[keyId]/KEY . /// This should only be called by KeyChain. /// </summary> /// /// <param name="identityName">The name if the identity.</param> /// <param name="params">The KeyParams for creating the key.</param> /// <returns>The name of the created key.</returns> /// <exception cref="Tpm.Error">if params is invalid or the key type is unsupported.</exception> /// <exception cref="TpmBackEnd.Error">if the key already exists or cannot be created.</exception> public Name createKey_(Name identityName, KeyParams paras) { if (paras.getKeyType() == net.named_data.jndn.security.KeyType.RSA || paras.getKeyType() == net.named_data.jndn.security.KeyType.EC) { TpmKeyHandle keyHandle = backEnd_.createKey(identityName, paras); Name keyName = keyHandle.getKeyName(); ILOG.J2CsMapping.Collections.Collections.Put(keys_, keyName, keyHandle); return(keyName); } else { throw new Tpm.Error("createKey: Unsupported key type"); } }
/// <summary> /// Returns the DtmForwardKeyStruct as an encoded MemoryStream /// </summary> /// /// <returns>The serialized DtmForwardKeyStruct</returns> public MemoryStream ToStream() { MemoryStream stream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(stream); KeyParams.Serialize(Key).CopyTo(stream); writer.Write(SessionParams.ToBytes()); writer.Write((long)LifeSpan); writer.Write((short)Instruction); writer.Write((long)OptionsFlag); stream.Seek(0, SeekOrigin.Begin); return(stream); }
/// <summary> /// Extract a KeyParams and CipherDescription /// </summary> /// /// <param name="Index">The index of the key set to extract</param> /// <param name="Description">The <see cref="CipherDescription"/> that receives the cipher description</param> /// <param name="KeyParam">The <see cref="KeyParams"/> container that receives the key material from the file</param> /// /// <exception cref="CryptoProcessingException">Thrown if the key file could not be found</exception> public void Extract(int Index, out CipherDescription Description, out KeyParams KeyParam) { if (!string.IsNullOrEmpty(_keyPath)) { if (!File.Exists(_keyPath)) throw new CryptoProcessingException("VolumeFactory:Extract", "The key file could not be found! Check the path.", new FileNotFoundException()); } if (_keyStream == null) _keyStream = new FileStream(_keyPath, FileMode.Open, FileAccess.Read); VolumeKey vkey = new VolumeKey(_keyStream); Description = vkey.Description; KeyParam = VolumeKey.AtIndex(_keyStream, Index); }
/// <summary> /// Create a single use key file using a <see cref="KeyParams"/> containing the key material, and a <see cref="CipherDescription"/> containing the cipher implementation details /// </summary> /// /// <param name="Description">The <see cref="CipherDescription">Cipher Description</see> containing the cipher details</param> /// <param name="KeyParam">An initialized and populated key material container</param> /// /// <exception cref="CryptoProcessingException">Thrown if a KeyParams member is null, but specified in the Header or a Header parameter does not match a KeyParams value</exception> public void Create(CipherDescription Description, KeyParams KeyParam) { if (KeyParam.Key == null) throw new CryptoProcessingException("KeyFactory:Create", "The key can not be null!", new ArgumentNullException()); if (KeyParam.Key.Length != Description.KeySize) throw new CryptoProcessingException("KeyFactory:Create", "The key parameter does not match the key size specified in the Header!", new ArgumentOutOfRangeException()); if (Description.IvSize > 0 && KeyParam.IV != null) { if (KeyParam.IV.Length != Description.IvSize) throw new CryptoProcessingException("KeyFactory:Create", "The KeyParam IV size does not align with the IVSize setting in the Header!", new ArgumentOutOfRangeException()); } if (Description.MacSize > 0) { if (KeyParam.IKM == null) throw new CryptoProcessingException("KeyFactory:Create", "Digest key is specified in the header MacSize, but is null in KeyParam!", new ArgumentNullException()); if (KeyParam.IKM.Length != Description.MacSize) throw new CryptoProcessingException("KeyFactory:Create", "Header MacSize does not align with the size of the KeyParam IKM!", new ArgumentOutOfRangeException()); } if (_keyStream == null) _keyStream = new FileStream(_keyPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read); byte[] hdr = new CipherKey(Description).ToBytes(); _keyStream.Write(hdr, 0, hdr.Length); byte[] key = ((MemoryStream)KeyParams.Serialize(KeyParam)).ToArray(); _keyStream.Write(key, 0, key.Length); }
/// <summary> /// Create a single use Key file using a manual description of the cipher parameters. /// </summary> /// /// <param name="KeyParam">An initialized and populated key material container</param> /// <param name="EngineType">The Cryptographic <see cref="SymmetricEngines">Engine</see> type</param> /// <param name="KeySize">The cipher Key Size in bytes</param> /// <param name="IvSize">Size of the cipher <see cref="IVSizes">Initialization Vector</see></param> /// <param name="CipherType">The type of <see cref="CipherModes">Cipher Mode</see></param> /// <param name="PaddingType">The type of cipher <see cref="PaddingModes">Padding Mode</see></param> /// <param name="BlockSize">The cipher <see cref="BlockSizes">Block Size</see></param> /// <param name="Rounds">The number of diffusion <see cref="RoundCounts">Rounds</see></param> /// <param name="KdfEngine">The <see cref="Digests">Digest</see> engine used to power the key schedule Key Derivation Function in HX and M series ciphers</param> /// <param name="MacSize">The size of the HMAC message authentication code; a zeroed parameter means authentication is not enabled with this key</param> /// <param name="MacEngine">The HMAC <see cref="Digests">Digest</see> engine used to authenticate a message file encrypted with this key</param> /// /// <exception cref="System.ArgumentNullException">Thrown if a KeyParams member is null, but specified in the Header</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown if a Header parameter does not match a KeyParams value</exception> public void Create(KeyParams KeyParam, SymmetricEngines EngineType, int KeySize, IVSizes IvSize, CipherModes CipherType, PaddingModes PaddingType, BlockSizes BlockSize, RoundCounts Rounds, Digests KdfEngine, int MacSize, Digests MacEngine) { CipherDescription dsc = new CipherDescription() { EngineType = (int)EngineType, KeySize = KeySize, IvSize = (int)IvSize, CipherType = (int)CipherType, PaddingType = (int)PaddingType, BlockSize = (int)BlockSize, RoundCount = (int)Rounds, KdfEngine = (int)KdfEngine, MacEngine = (int)MacEngine, MacSize = MacSize }; Create(dsc, KeyParam); }
/// <summary> /// Extract a KeyParams and CipherKey /// </summary> /// /// <param name="KeyHeader">The <see cref="CipherKey"/> that receives the cipher description, key id, and extension key</param> /// <param name="KeyParam">The <see cref="KeyParams"/> container that receives the key material from the file</param> /// /// <exception cref="CryptoProcessingException">Thrown if the key file could not be found or a Header parameter does not match the keystream length</exception> public void Extract(out CipherKey KeyHeader, out KeyParams KeyParam) { if (!string.IsNullOrEmpty(_keyPath)) { if (!File.Exists(_keyPath)) throw new CryptoProcessingException("KeyFactory:Extract", "The key file could not be found! Check the path.", new FileNotFoundException()); } if (_keyStream == null) _keyStream = new FileStream(_keyPath, FileMode.Open, FileAccess.Read); KeyHeader = new CipherKey(_keyStream); CipherDescription dsc = KeyHeader.Description; if (_keyStream.Length < dsc.KeySize + dsc.IvSize + dsc.MacSize + CipherKey.GetHeaderSize()) throw new CryptoProcessingException("KeyFactory:Extract", "The size of the key file does not align with the CipherKey sizes! Key is corrupt.", new ArgumentOutOfRangeException()); _keyStream.Position = CipherKey.GetHeaderSize(); KeyParam = KeyParams.DeSerialize(_keyStream); }
/// <summary> /// Initialize the Cipher. /// </summary> /// /// <param name="KeyParam">Cipher key container. The <see cref="LegalKeySizes"/> property contains valid sizes</param> /// /// <exception cref="System.ArgumentNullException">Thrown if a null key is used</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown if an invalid key size is used</exception> /// <exception cref="System.ArgumentException">Thrown if key contains too many repeating sequences</exception> public void Initialize(KeyParams KeyParam) { if (KeyParam.Key == null) throw new ArgumentNullException("Invalid seed! Seed can not be null."); if (KeyParam.Key.Length != 96) throw new ArgumentOutOfRangeException("Invalid seed size! Seed must be 96 bytes."); if (ZerosFrequency(KeyParam.Key) > 24) throw new ArgumentException("Bad seed! Seed material contains too many zeroes."); if (!EvaluateSeed(KeyParam.Key)) throw new ArgumentException("Bad seed! Seed material contains repeating sequence."); // copy seed Buffer.BlockCopy(KeyParam.Key, 0, _keyBuffer, 0, _keyBuffer.Length); byte[] keyBuffer1 = new byte[AESKEY_BYTES]; byte[] keyBuffer2 = new byte[AESKEY_BYTES]; // copy seed to keys Buffer.BlockCopy(KeyParam.Key, 0, keyBuffer1, 0, AESKEY_BYTES); Buffer.BlockCopy(KeyParam.Key, AESKEY_BYTES, keyBuffer2, 0, AESKEY_BYTES); if (IsEqual(keyBuffer1, keyBuffer2)) throw new ArgumentException("Bad seed! Seed material is a repeating sequence."); // copy seed to counters Buffer.BlockCopy(KeyParam.Key, AESKEY_BYTES * 2, _ctrBuffer1, 0, BLOCK_SIZE); Buffer.BlockCopy(KeyParam.Key, (AESKEY_BYTES * 2) + BLOCK_SIZE, _ctrBuffer2, 0, BLOCK_SIZE); if (IsEqual(_ctrBuffer1, _ctrBuffer2)) throw new ArgumentException("Bad seed! Seed material is a repeating sequence."); // expand AES keys _exKey1 = ExpandKey(keyBuffer1); _exKey2 = ExpandKey(keyBuffer2); _isInitialized = true; }
/// <remarks> /// Encrypts the key package buffer /// </remarks> private void TransformBuffer(byte[] KeyData, byte[] Salt) { byte[] kvm = new byte[48]; // use salt to derive key and counter vector using (Keccak512 digest = new Keccak512(384)) kvm = digest.ComputeHash(Salt); byte[] key = new byte[32]; byte[] iv = new byte[16]; Buffer.BlockCopy(kvm, 0, key, 0, key.Length); Buffer.BlockCopy(kvm, key.Length, iv, 0, iv.Length); using (KeyParams keyparam = new KeyParams(key, iv)) { // 40 rounds of serpent using (CTR cipher = new CTR(new SPX(40))) { cipher.Initialize(true, keyparam); cipher.Transform(KeyData, KeyData); } } }
/// <remarks> /// Returns the populated KeyParams class /// </remarks> private KeyParams GetKeySet(MemoryStream KeyStream, CipherDescription Description, long Position) { KeyParams keyParam; KeyStream.Seek(Position, SeekOrigin.Begin); // create the keyparams class if (Description.MacSize > 0 && Description.IvSize > 0) { byte[] key = new byte[Description.KeySize]; byte[] iv = new byte[Description.IvSize]; byte[] ikm = new byte[Description.MacSize]; KeyStream.Read(key, 0, key.Length); KeyStream.Read(iv, 0, iv.Length); KeyStream.Read(ikm, 0, ikm.Length); keyParam = new KeyParams(key, iv, ikm); } else if (Description.IvSize > 0) { byte[] key = new byte[Description.KeySize]; byte[] iv = new byte[Description.IvSize]; KeyStream.Read(key, 0, key.Length); KeyStream.Read(iv, 0, iv.Length); keyParam = new KeyParams(key, iv); } else if (Description.MacSize > 0) { byte[] key = new byte[Description.KeySize]; byte[] ikm = new byte[Description.MacSize]; KeyStream.Read(key, 0, key.Length); KeyStream.Read(ikm, 0, ikm.Length); keyParam = new KeyParams(key, null, ikm); } else { byte[] key = new byte[Description.KeySize]; KeyStream.Read(key, 0, key.Length); keyParam = new KeyParams(key); } return keyParam; }
/// <summary> /// Extract the next valid subkey set (Expired flag not set) as a KeyParam, and a CipherDescription structure. /// <para>Used only when calling a Encryption function.</para> /// </summary> /// /// <param name="Description">out: The CipherDescription structure; the properties required to create a specific cipher instance</param> /// <param name="KeyParam">out: The KeyParams class containing a unique key, initialization vector and HMAC key</param> /// <param name="ExtensionKey">out: The random key used to encrypt the message file extension</param> /// /// <returns>The KeyId array used to identify a subkey set; set as the KeyId in a MessageHeader structure</returns> /// /// <exception cref="CryptoProcessingException">Thrown if the user has insufficient access rights to perform encryption with this key.</exception> public byte[] NextKey(out CipherDescription Description, out KeyParams KeyParam, out byte[] ExtensionKey) { if (!AccessScope.Equals(KeyScope.Creator)) throw new CryptoProcessingException("PackageFactory:NextKey", "You do not have permission to encrypt with this key!", new UnauthorizedAccessException()); try { // get the key data MemoryStream keyStream = GetKeyStream(); // get the next unused key for encryption int index = PackageKey.NextSubkey(keyStream); if (index == -1) throw new CryptoProcessingException("PackageFactory:NextKey", "The key file has expired! There are no keys left available for encryption.", new Exception()); // get the cipher description Description = _keyPackage.Description; // get the file extension key ExtensionKey = _keyPackage.ExtensionKey; // store the subkey identity, this is written into the message header to identify the subkey byte[] keyId = _keyPackage.SubKeyID[index]; // get the starting position of the keying material within the package long keyPos = PackageKey.SubKeyOffset(keyStream, keyId); // no unused keys in the package file if (keyPos == -1) throw new CryptoProcessingException("PackageFactory:NextKey", "The key file has expired! There are no keys left available for encryption.", new Exception()); // get the keying material KeyParam = GetKeySet(keyStream, _keyPackage.Description, keyPos); // mark the subkey as expired PackageKey.SubKeySetPolicy(keyStream, index, (long)PackageKeyStates.Expired); // write to file WriteKeyStream(keyStream); // return the subkey id return keyId; } catch { throw; } }
/// <summary> /// Extract a subkey set (KeyParam), a file extension key, and a CipherDescription. /// <para>Used only when calling a Decryption function to get a specific subkey /// The KeyId field corresponds with the KeyId field contained in a MessageHeader structure.</para> /// </summary> /// /// <param name="KeyId">The KeyId array used to identify a subkey set; set as the KeyId in a MessageHeader structure</param> /// <param name="Description">out: The CipherDescription structure; the properties required to create a specific cipher instance</param> /// <param name="KeyParam">out: The KeyParams class containing a unique key, initialization vector and HMAC key</param> /// <param name="ExtensionKey">out: The random key used to encrypt the message file extension</param> /// /// <exception cref="CryptoProcessingException">Thrown if the user has insufficient access rights to access this PackageKey, or the PackageKey does not contain the KeyId specified</exception> public void Extract(byte[] KeyId, out CipherDescription Description, out KeyParams KeyParam, out byte[] ExtensionKey) { if (AccessScope.Equals(KeyScope.NoAccess)) throw new CryptoProcessingException("PackageFactory:Extract", "You do not have permission to access this key!", new UnauthorizedAccessException()); try { long keyPos; int index; // get the key data MemoryStream keyStream = GetKeyStream(); // get the keying materials starting offset within the key file keyPos = PackageKey.SubKeyOffset(keyStream, KeyId); if (keyPos == -1) throw new CryptoProcessingException("PackageFactory:Extract", "This package does not contain the key file!", new ArgumentException()); // get the index index = PackageKey.IndexFromId(keyStream, KeyId); // key flagged SingleUse was used for decryption and is locked out if (PackageKey.KeyHasPolicy(_keyPackage.SubKeyPolicy[index], (long)PackageKeyStates.Locked)) throw new CryptoProcessingException("PackageFactory:Extract", "SubKey is locked. The subkey has a single use policy and was previously used to decrypt the file.", new Exception()); // key flagged PostOverwrite was used for decryption and was erased if (PackageKey.KeyHasPolicy(_keyPackage.SubKeyPolicy[index], (long)PackageKeyStates.Erased)) throw new CryptoProcessingException("PackageFactory:Extract", "SubKey is erased. The subkey has a post erase policy and was previously used to decrypt the file.", new Exception()); // get the cipher description Description = _keyPackage.Description; // get the keying material KeyParam = GetKeySet(keyStream, _keyPackage.Description, keyPos); // encrypts the file extension ExtensionKey = _keyPackage.ExtensionKey; // test flags for overwrite or single use policies if (PackageKey.KeyHasPolicy(KeyPolicy, (long)KeyPolicies.PostOverwrite)) PackageKey.SubKeySetPolicy(keyStream, index, (long)PackageKeyStates.Erased); else if (PackageKey.KeyHasPolicy(KeyPolicy, (long)KeyPolicies.SingleUse)) PackageKey.SubKeySetPolicy(keyStream, index, (long)PackageKeyStates.Locked); // post overwrite flag set, erase the subkey if (PackageKey.KeyHasPolicy(KeyPolicy, (long)KeyPolicies.PostOverwrite)) { int keySize = Description.KeySize + Description.IvSize + Description.MacSize; // overwrite the region within file Erase(keyPos, keySize); // clear this section of the key keyStream.Seek(keyPos, SeekOrigin.Begin); keyStream.Write(new byte[keySize], 0, keySize); } // write to file WriteKeyStream(keyStream); } catch { throw; } }
/// <summary> /// Initialize the Cipher. /// </summary> /// /// <param name="Encryption">Using Encryption or Decryption mode</param> /// <param name="KeyParam">Cipher key container. <para>The <see cref="LegalKeySizes"/> property contains valid sizes.</para></param> /// /// <exception cref="System.ArgumentNullException">Thrown if a null key is used</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown if an invalid key size is used</exception> public void Initialize(bool Encryption, KeyParams KeyParam) { if (KeyParam.Key == null) throw new ArgumentNullException("Invalid key! Key can not be null."); if (KeyParam.Key.Length != 32 && KeyParam.Key.Length != 64) throw new ArgumentOutOfRangeException("Invalid key size! Valid sizes are 32 and 64 bytes."); _isEncryption = Encryption; // expand the key _expKey = ExpandKey(KeyParam.Key, Encryption); }