private static BlockCipherMode SetCryptoAlgorithm() { var preferenceA = _socketA.ReadString(); var preferenceB = _socketB.ReadString(); Console.WriteLine("Preferences read from clients."); var finalChoice = "ECB"; var randomChoice = new Random().Next(0, 1) == 0 ? "ECB" : "CFB"; BlockCipherMode mode; if (preferenceA.Equals("CFB") && preferenceB.Equals("CFB")) { _algorithm = new SecurityAlgorithm(Secrets.KeyCfb, Secrets.Iv, BlockCipherMode.CFB); mode = BlockCipherMode.ECB; } else if (preferenceA.Equals("ECB") && preferenceB.Equals("ECB") || randomChoice.Equals("ECB")) { _algorithm = new SecurityAlgorithm(Secrets.KeyEcb, Secrets.Iv, BlockCipherMode.ECB); mode = BlockCipherMode.ECB; } else { _algorithm = new SecurityAlgorithm(Secrets.KeyCfb, Secrets.Iv, BlockCipherMode.CFB); finalChoice = "CFB"; mode = BlockCipherMode.CFB; } _socketA.WriteString(finalChoice); _socketB.WriteString(finalChoice); Console.WriteLine("Final choice sent!"); return(mode); }
/// <summary> /// Creates a new <see cref="CommonFrameHeader"/> from serialization parameters. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> with populated with data.</param> /// <param name="context">The source <see cref="StreamingContext"/> for this deserialization.</param> protected CommonFrameHeader(SerializationInfo info, StreamingContext context) { // Deserialize common frame header m_frameType = (FrameType)info.GetValue("frameType", typeof(FrameType)); m_version = info.GetByte("version"); m_frameLength = info.GetUInt16("frameLength"); m_timebase = info.GetUInt32("timebase"); m_timeQualityFlags = info.GetUInt32("timeQualityFlags"); if (m_frameType != IEC61850_90_5.FrameType.DataFrame) { return; } m_headerLength = info.GetUInt16("headerLength"); m_dataLength = info.GetUInt16("dataLength"); m_packetNumber = info.GetUInt32("packetNumber"); m_signatureAlgorithm = (SignatureAlgorithm)info.GetValue("signatureAlgorithm", typeof(SignatureAlgorithm)); m_securityAlgorithm = (SecurityAlgorithm)info.GetValue("securityAlgorithm", typeof(SecurityAlgorithm)); m_asduCount = info.GetInt32("adsuCount"); m_simulatedData = info.GetBoolean("simulatedData"); m_applicationID = info.GetUInt16("applicationID"); m_payloadSize = info.GetUInt16("payloadSize"); m_keyID = info.GetUInt32("keyID"); }
/// <summary> /// Creates a new instance of the <see cref="DNSKEYRecord"/> class /// from the specified RSA key. /// </summary> /// <param name="key"> /// A public or private RSA key. /// </param> /// <param name="algorithm"> /// The security algorithm to use. Only RSA types are allowed. /// </param> public DNSKEYRecord(RSA key, SecurityAlgorithm algorithm) : this() { switch (algorithm) { case SecurityAlgorithm.RSAMD5: case SecurityAlgorithm.RSASHA1: case SecurityAlgorithm.RSASHA1NSEC3SHA1: case SecurityAlgorithm.RSASHA256: case SecurityAlgorithm.RSASHA512: break; default: throw new ArgumentException($"Security algorithm '{algorithm}' is not allowed for a RSA key."); } Algorithm = algorithm; using (var ms = new MemoryStream()) { var p = key.ExportParameters(includePrivateParameters: false); ms.WriteByte((byte)p.Exponent.Length); ms.Write(p.Exponent, 0, p.Exponent.Length); ms.Write(p.Modulus, 0, p.Modulus.Length); PublicKey = ms.ToArray(); } }
/// <summary> /// Gets the meta data for the the <see cref="SecurityAlgorithm"/>. /// </summary> /// <param name="algorithm"> /// One of the <see cref="SecurityAlgorithm"/> values. /// </param> /// <returns> /// The <see cref="Metadata"/> for the <paramref name="algorithm"/>. /// </returns> /// <exception cref="NotImplementedException"> /// When the <paramref name="algorithm"/> is not defined. /// </exception> public static Metadata GetMetadata(SecurityAlgorithm algorithm) { if (Algorithms.TryGetValue(algorithm, out Metadata metadata)) { return(metadata); } throw new NotImplementedException($"The security algorithm '{algorithm}' is not defined."); }
public string EncryptString(string text, SecurityAlgorithm algorithm) { if (string.IsNullOrEmpty(text)) { throw new ArgumentException("message", nameof(text)); } Debug.WriteLine($"Encryption Algorithm: {algorithm}"); throw new NotImplementedException(); }
public static DnsSecAlgorithm ToDnsSecAlgorithm(this SecurityAlgorithm securityAlgorithm) { switch (securityAlgorithm) { case SecurityAlgorithm.RSAMD5: return(DnsSecAlgorithm.RsaMd5); case SecurityAlgorithm.DH: return(DnsSecAlgorithm.DiffieHellman); case SecurityAlgorithm.DSA: return(DnsSecAlgorithm.Dsa); case SecurityAlgorithm.RSASHA1: return(DnsSecAlgorithm.RsaSha1); case SecurityAlgorithm.DSANSEC3SHA1: return(DnsSecAlgorithm.DsaNsec3Sha1); case SecurityAlgorithm.RSASHA1NSEC3SHA1: return(DnsSecAlgorithm.RsaSha1Nsec3Sha1); case SecurityAlgorithm.RSASHA256: return(DnsSecAlgorithm.RsaSha256); case SecurityAlgorithm.RSASHA512: return(DnsSecAlgorithm.RsaSha512); case SecurityAlgorithm.ECCGOST: return(DnsSecAlgorithm.EccGost); case SecurityAlgorithm.ECDSAP256SHA256: return(DnsSecAlgorithm.EcDsaP256Sha256); case SecurityAlgorithm.ECDSAP384SHA384: return(DnsSecAlgorithm.EcDsaP384Sha384); case SecurityAlgorithm.INDIRECT: return(DnsSecAlgorithm.Indirect); case SecurityAlgorithm.PRIVATEDNS: return(DnsSecAlgorithm.PrivateDns); case SecurityAlgorithm.PRIVATEOID: return(DnsSecAlgorithm.PrivateOid); case SecurityAlgorithm.ED25519: case SecurityAlgorithm.ED448: case SecurityAlgorithm.DELETE: default: throw new ArgumentOutOfRangeException(nameof(securityAlgorithm), securityAlgorithm, null); } }
/// <summary> /// Convert Algorithm to string form. /// </summary> public static string ToString(this SecurityAlgorithm alg) { return(alg switch { SecurityAlgorithm.HS256 => "HS256", SecurityAlgorithm.HS384 => "HS384", SecurityAlgorithm.HS512 => "HS512", SecurityAlgorithm.RS256 => "RS256", SecurityAlgorithm.RS384 => "RS384", SecurityAlgorithm.RS512 => "RS512", SecurityAlgorithm.ES256 => "ES256", SecurityAlgorithm.ES384 => "ES384", SecurityAlgorithm.ES512 => "ES512", _ => "HS256", });
public ClientBehavior(BlockCipherMode modeChoice) { this.modeChoice = modeChoice; _sender = GetClientSocket(); this.modeFinal = GetFinalMode(); Debug("Final mode chosen"); alg = getSecurityAlgorithm(); return; var inputList = "heyy looka this 1234g5g5asd789a9sd3".SplitInBlocks(); var encryptedList = alg.EncryptList(inputList); var decryptedlist = alg.DecryptList(encryptedList); Debug(inputList.ToString()); Debug(encryptedList.ToString()); Debug(decryptedlist.ToString()); }
public HillTest() { matrix = new int[3, 3]; matrix[0, 0] = 17; matrix[0, 1] = 21; matrix[0, 2] = 2; matrix[1, 0] = 17; matrix[1, 1] = 18; matrix[1, 2] = 2; matrix[2, 0] = 5; matrix[2, 1] = 21; matrix[2, 2] = 19; _target = new Hill(matrix); }
/// <summary> /// Creates a new <see cref="CommonFrameHeader"/> from specified parameters. /// </summary> /// <param name="configurationFrame">IEC 61850-90-5 <see cref="ConfigurationFrame"/> if available.</param> /// <param name="typeID">The IEC 61850-90-5 specific frame type of this frame.</param> /// <param name="idCode">The ID code of this frame.</param> /// <param name="timestamp">The timestamp of this frame.</param> /// <param name="msvID">MSVID to use for this frame, if any.</param> /// <param name="asduCount">ASDU count.</param> /// <param name="configurationRevision">Configuration revision.</param> public CommonFrameHeader(ConfigurationFrame configurationFrame, FrameType typeID, ushort idCode, Ticks timestamp, string msvID = null, int asduCount = 1, uint configurationRevision = 1) { m_frameType = typeID; m_idCode = idCode; m_timestamp = timestamp; m_version = 1; m_timebase = Common.Timebase; m_msvID = msvID; m_asduCount = asduCount; m_configurationRevision = configurationRevision; m_securityAlgorithm = SecurityAlgorithm.None; m_signatureAlgorithm = SignatureAlgorithm.None; if ((object)configurationFrame != null) { // Hang on to configured frame rate and ticks per frame m_framesPerSecond = configurationFrame.FrameRate; m_ticksPerFrame = Ticks.PerSecond / (double)m_framesPerSecond; } }
/// <summary> /// Creates a new <see cref="CommonFrameHeader"/> from given <paramref name="buffer"/>. /// </summary> /// <param name="configurationFrame">IEC 61850-90-5 <see cref="ConfigurationFrame"/> if already parsed.</param> /// <param name="useETRConfiguration">Determines if system should find associated ETR file using MSVID with same name for configuration.</param> /// <param name="guessConfiguration">Determines if system should try to guess at a possible configuration given payload size.</param> /// <param name="parseRedundantASDUs">Determines if system should expose redundantly parsed ASDUs.</param> /// <param name="ignoreSignatureValidationFailures">Determines if system should ignore checksum signature validation errors.</param> /// <param name="ignoreSampleSizeValidationFailures">Determines if system should ignore sample size validation errors.</param> /// <param name="angleFormat">Allows customization of the angle parsing format.</param> /// <param name="buffer">Buffer that contains data to parse.</param> /// <param name="startIndex">Start index into buffer where valid data begins.</param> /// <param name="length">Maximum length of valid data from offset.</param> // ReSharper disable once UnusedParameter.Local public CommonFrameHeader(ConfigurationFrame configurationFrame, bool useETRConfiguration, bool guessConfiguration, bool parseRedundantASDUs, bool ignoreSignatureValidationFailures, bool ignoreSampleSizeValidationFailures, AngleFormat angleFormat, byte[] buffer, int startIndex, int length) { const byte VersionNumberMask = (byte)IEC61850_90_5.FrameType.VersionNumberMask; // Cache behavioral connection parameters m_useETRConfiguration = useETRConfiguration; m_guessConfiguration = guessConfiguration; m_parseRedundantASDUs = parseRedundantASDUs; m_ignoreSignatureValidationFailures = ignoreSignatureValidationFailures; m_ignoreSampleSizeValidationFailures = ignoreSampleSizeValidationFailures; m_angleFormat = angleFormat; // Ignore the time base from configuration frame if available. The timebase is not adjustable for 61850. m_timebase = Common.Timebase; // See if frame is for a common IEEE C37.118 frame (e.g., for configuration or command) if (buffer[startIndex] == PhasorProtocols.Common.SyncByte) { // Strip out frame type and version information... m_frameType = (FrameType)(buffer[startIndex + 1] & ~VersionNumberMask); m_version = (byte)(buffer[startIndex + 1] & VersionNumberMask); m_frameLength = BigEndian.ToUInt16(buffer, startIndex + 2); m_idCode = BigEndian.ToUInt16(buffer, startIndex + 4); uint secondOfCentury = BigEndian.ToUInt32(buffer, startIndex + 6); uint fractionOfSecond = BigEndian.ToUInt32(buffer, startIndex + 10); long ticksBeyondSecond; // Without timebase, the best timestamp you can get is down to the whole second m_timestamp = (new UnixTimeTag((double)secondOfCentury)).ToDateTime().Ticks; // "Actual fractional seconds" are obtained by taking fractionOfSecond and dividing by timebase. // Since we are converting to ticks, we need to multiply by Ticks.PerSecond. // We do the multiplication first so that the whole operation can be done using integer arithmetic. // m_timebase / 2L is added before dividing by timebase in order to round the result. ticksBeyondSecond = (fractionOfSecond & ~Common.TimeQualityFlagsMask) * Ticks.PerSecond; m_timestamp += (ticksBeyondSecond + m_timebase / 2L) / m_timebase; if ((object)configurationFrame != null) { // Hang on to configured frame rate and ticks per frame m_framesPerSecond = configurationFrame.FrameRate; m_ticksPerFrame = Ticks.PerSecond / (double)m_framesPerSecond; } m_timeQualityFlags = fractionOfSecond & Common.TimeQualityFlagsMask; } else if (buffer[startIndex + 1] == Common.CltpTag) { // Make sure there is enough data to parse session header from frame if (length > Common.SessionHeaderSize) { // Manually assign frame type - this is an IEC 61850-90-5 data frame m_frameType = IEC61850_90_5.FrameType.DataFrame; // Calculate CLTP tag length int cltpTagLength = buffer[startIndex] + 1; // Initialize buffer parsing index starting past connectionless transport protocol header int index = startIndex + cltpTagLength; // Start calculating total frame length int frameLength = cltpTagLength; // Get session type (Goose, sampled values, etc.) SessionType sessionType = (SessionType)buffer[index++]; // Make sure session type is sampled values if (sessionType == SessionType.SampledValues) { byte headerSize = buffer[index]; // Make sure header size is standard if (headerSize == Common.SessionHeaderSize) { // Skip common header tag index += 3; // Get SPDU length m_spduLength = BigEndian.ToUInt32(buffer, index); index += 4; // Add SPDU length to total frame length (updated as of 10/3/2012 to accommodate extra 6 bytes) frameLength += (int)m_spduLength + 8; // Make sure full frame of data is available - cannot calculate full frame length needed for check sum // without the entire frame since signature algorithm calculation length varies by type and size if (length > m_spduLength + 13) { // Get SPDU packet number m_packetNumber = BigEndian.ToUInt32(buffer, index); // Get security algorithm type m_securityAlgorithm = (SecurityAlgorithm)buffer[index + 12]; // Get signature algorithm type m_signatureAlgorithm = (SignatureAlgorithm)buffer[index + 13]; // Get current key ID m_keyID = BigEndian.ToUInt32(buffer, index + 14); // Add signature calculation result length to total frame length switch (m_signatureAlgorithm) { case SignatureAlgorithm.None: break; case SignatureAlgorithm.Sha80: frameLength += 11; break; case SignatureAlgorithm.Sha128: case SignatureAlgorithm.Aes128: frameLength += 17; break; case SignatureAlgorithm.Sha256: frameLength += 33; break; case SignatureAlgorithm.Aes64: frameLength += 9; break; default: throw new InvalidOperationException("Invalid IEC 61850-90-5 signature algorithm detected: 0x" + buffer[index].ToString("X").PadLeft(2, '0')); } // Check signature algorithm packet checksum here, this step is skipped in data frame parsing due to non-standard location... if (m_signatureAlgorithm != SignatureAlgorithm.None) { int packetIndex = startIndex + cltpTagLength; int hmacIndex = (int)(packetIndex + m_spduLength + 2); // Check for signature tag if (buffer[hmacIndex++] == 0x85) { // KeyID is technically a lookup into derived rotating keys, but all these are using dummy key for now HMAC hmac = m_signatureAlgorithm <= SignatureAlgorithm.Sha256 ? (HMAC)(new ShaHmac(Common.DummyKey)) : (HMAC)(new AesHmac(Common.DummyKey)); int result = 0; switch (m_signatureAlgorithm) { case SignatureAlgorithm.None: break; case SignatureAlgorithm.Aes64: m_sourceHash = buffer.BlockCopy(hmacIndex, 8); m_calculatedHash = hmac.ComputeHash(buffer, packetIndex, (int)m_spduLength).BlockCopy(0, 8); result = m_sourceHash.CompareTo(0, m_calculatedHash, 0, 8); break; case SignatureAlgorithm.Sha80: m_sourceHash = buffer.BlockCopy(hmacIndex, 10); m_calculatedHash = hmac.ComputeHash(buffer, packetIndex, (int)m_spduLength).BlockCopy(0, 10); result = m_sourceHash.CompareTo(0, m_calculatedHash, 0, 10); break; case SignatureAlgorithm.Sha128: case SignatureAlgorithm.Aes128: m_sourceHash = buffer.BlockCopy(hmacIndex, 16); m_calculatedHash = hmac.ComputeHash(buffer, packetIndex, (int)m_spduLength).BlockCopy(0, 16); result = m_sourceHash.CompareTo(0, m_calculatedHash, 0, 16); break; case SignatureAlgorithm.Sha256: m_sourceHash = buffer.BlockCopy(hmacIndex, 32); m_calculatedHash = hmac.ComputeHash(buffer, packetIndex, (int)m_spduLength).BlockCopy(0, 32); result = m_sourceHash.CompareTo(0, m_calculatedHash, 0, 32); break; default: throw new NotSupportedException(string.Format("IEC 61850-90-5 signature algorithm \"{0}\" is not currently supported: ", m_signatureAlgorithm)); } if (result != 0 && !m_ignoreSignatureValidationFailures) { throw new CrcException("Invalid binary image detected - IEC 61850-90-5 check sum does not match."); } } else { throw new CrcException("Invalid binary image detected - expected IEC 61850-90-5 check sum does not exist."); } } // Get payload length index += 18; m_dataLength = (ushort)BigEndian.ToUInt32(buffer, index); index += 4; // Confirm payload type tag is sampled values if (buffer[index] != 0x82) { throw new InvalidOperationException("Encountered a payload that is not tagged 0x82 for sampled values: 0x" + buffer[index].ToString("X").PadLeft(2, '0')); } index++; // Get simulated bit value m_simulatedData = buffer[index++] != 0; // Get application ID m_applicationID = BigEndian.ToUInt16(buffer, index); index += 2; // Get ASDU payload size m_payloadSize = BigEndian.ToUInt16(buffer, index); index += 2; // Validate sampled value PDU tag exists and skip past it buffer.ValidateTag(SampledValueTag.SvPdu, ref index); // Parse number of ASDUs tag m_asduCount = buffer.ParseByteTag(SampledValueTag.AsduCount, ref index); if (m_asduCount == 0) { throw new InvalidOperationException("Total number of ADSUs must be greater than zero."); } // Validate sequence of ASDU tag exists and skip past it buffer.ValidateTag(SampledValueTag.SequenceOfAsdu, ref index); // Set header length m_headerLength = (ushort)(index - startIndex); // Set calculated frame length m_frameLength = (ushort)frameLength; } } else { throw new InvalidOperationException("Bad data stream, encountered an invalid session header size: " + headerSize); } } else { throw new InvalidOperationException(string.Format("This library can only parse IEC 61850-90-5 sampled value sessions, type \"{0}\" is not supported.", sessionType)); } } } else { throw new InvalidOperationException("Bad data stream, expected sync byte 0xAA or 0x01 as first byte in IEC 61850-90-5 frame, got 0x" + buffer[startIndex].ToString("X").PadLeft(2, '0')); } }
public CeaserTest() { _target = new Ceaser(3); }
public PlayFairTest() { _target = new PlayFair("playfairexample"); }
/// <summary> /// Encrypts a string using the selected algorithm. /// </summary> /// <param name="text">The string to encrypt.</param> /// <param name="algorithm"> /// The cryptographic algorithm used to encrypt the string. /// </param> /// <returns>Encrypted string</returns> public string EncryptString(string text, SecurityAlgorithm algorithm) { // ...implementation... throw new NotImplementedException(); }
public RowTranspositionTest() { _target = new RowTransposition(new int[] { 4, 3, 1, 2, 5, 6, 7 }); }
/// <summary> /// Gets the hash algorithm for the <see cref="SecurityAlgorithm"/>. /// </summary> /// <param name="algorithm"> /// One of the <see cref="SecurityAlgorithm"/> values. /// </param> /// <returns> /// A new instance of the <see cref="HashAlgorithm"/> that is used /// for the <paramref name="algorithm"/>. /// </returns> /// <exception cref="NotImplementedException"> /// When the <paramref name="algorithm"/> or its <see cref="HashAlgorithm"/> /// is not implemented. /// </exception> public static HashAlgorithm Create(SecurityAlgorithm algorithm) { var metadata = SecurityAlgorithmRegistry.GetMetadata(algorithm); return(Create(metadata.HashAlgorithm)); }
public RailFenceTest() { _target = new RailFence(2); }