internal EncryptionInfo GetClientStandardEncryptionInfo(ClientLicense clientLicense) { EncryptionInfo ei = new EncryptionInfo(); ei.HashAlgorithm = "SHA1"; ei.InitVector = Resources.ServicesIV; ei.Iterations = 2; ei.KeySize = 192; // Outbound Key string outKey1 = clientLicense.ServicesKeys.PrivateKey.Substring(0, (clientLicense.ServicesKeys.PrivateKey.Length / 2)); string outKey2 = clientLicense.ServicesKeys.PrivateKey.Substring(outKey1.Length, (clientLicense.ServicesKeys.PrivateKey.Length - outKey1.Length)); // Inbound Key string inKey1 = clientLicense.ServicesKeys.PublicKey.Substring(0, (clientLicense.ServicesKeys.PublicKey.Length / 2)); string inKey2 = clientLicense.ServicesKeys.PublicKey.Substring(inKey1.Length, (clientLicense.ServicesKeys.PublicKey.Length - inKey1.Length)); ei.PassPhrase = outKey2; ei.SaltValue = inKey2; return(ei); }
protected void CreateEncryptionInfoEntry(DirectoryNode dir, FileInfo tmpFile) { DataSpaceMapUtils.AddDefaultDataSpace(dir); EncryptionInfo info = builder.GetInfo(); //EncryptionRecord er = new EncryptionRecord(){ // public void Write(LittleEndianByteArrayOutputStream bos) { // // EncryptionVersionInfo (4 bytes): A Version structure (section 2.1.4), where // // Version.vMajor MUST be 0x0004 and Version.vMinor MUST be 0x0004 // bos.Writeshort(info.VersionMajor); // bos.Writeshort(info.VersionMinor); // // Reserved (4 bytes): A value that MUST be 0x00000040 // bos.WriteInt(info.EncryptionFlags); // EncryptionDocument ed = CreateEncryptionDocument(); // marshallEncryptionDocument(ed, bos); // } //}; //CreateEncryptionEntry(dir, "EncryptionInfo", er); }
/// <summary> /// 対称鍵暗号を使って文字列を暗号化する /// </summary> /// <param name="text">暗号化する文字列</param> /// <returns>暗号化された文字列</returns> public static string Encrypt(string text) { if (string.IsNullOrEmpty(text)) { return(""); } using (var rijndael = new RijndaelManaged()) { var info = new EncryptionInfo(); rijndael.BlockSize = info.BlockSize; rijndael.KeySize = info.KeySize; rijndael.Mode = CipherMode.CBC; rijndael.Padding = PaddingMode.PKCS7; rijndael.IV = Encoding.UTF8.GetBytes(info.IV); rijndael.Key = Encoding.UTF8.GetBytes(info.Key); var encryptor = rijndael.CreateEncryptor(rijndael.Key, rijndael.IV); byte[] encrypted; using (var mStream = new MemoryStream()) { using (var ctStream = new CryptoStream(mStream, encryptor, CryptoStreamMode.Write)) { using (var sw = new StreamWriter(ctStream)) { sw.Write(text); } encrypted = mStream.ToArray(); } } return(System.Convert.ToBase64String(encrypted)); } }
/// <summary> /// Wrap the OLE2 data in the NPOIFSFileSystem into a decrypted stream by using the given password. /// </summary> /// <param name="fs">The OLE2 stream for the document</param> /// <param name="password">The password, null if the default password should be used</param> /// <returns>A stream for reading the decrypted data</returns> /// <exception cref="System.IO.IOException">If an error occurs while decrypting or if the password does not match</exception> public static InputStream GetDecryptedStream(NPOIFSFileSystem fs, String password) { EncryptionInfo info = new EncryptionInfo(fs); Decryptor d = Decryptor.GetInstance(info); try { bool passwordCorrect = false; if (password != null && d.VerifyPassword(password)) { passwordCorrect = true; } if (!passwordCorrect && d.VerifyPassword(Decryptor.DEFAULT_PASSWORD)) { passwordCorrect = true; } if (passwordCorrect) { return(new FilterInputStream1(d.GetDataStream(fs.Root), fs)); } else { if (password != null) { throw new EncryptedDocumentException("Password incorrect"); } else { throw new EncryptedDocumentException("The supplied spreadsheet is protected, but no password was supplied"); } } } catch (Exception e) { throw new IOException("password does not match", e); } }
/** * Initialize the builder from scratch */ public void Initialize(EncryptionInfo info, CipherAlgorithm cipherAlgorithm, HashAlgorithm hashAlgorithm, int keyBits, int blockSize, ChainingMode chainingMode) { this.info = info; if (cipherAlgorithm == null) { cipherAlgorithm = CipherAlgorithm.rc4; } if (hashAlgorithm == null) { hashAlgorithm = HashAlgorithm.sha1; } if (keyBits == -1) { keyBits = 0x28; } Debug.Assert(cipherAlgorithm == CipherAlgorithm.rc4 && hashAlgorithm == HashAlgorithm.sha1); header = new CryptoAPIEncryptionHeader(cipherAlgorithm, hashAlgorithm, keyBits, blockSize, chainingMode); verifier = new CryptoAPIEncryptionVerifier(cipherAlgorithm, hashAlgorithm, keyBits, blockSize, chainingMode); decryptor = new CryptoAPIDecryptor(this); encryptor = new CryptoAPIEncryptor(this); }
/// <summary> /// 対称鍵暗号を使って暗号文を復号する /// </summary> /// <param name="cipher">暗号化された文字列</param> /// <returns>復号された文字列</returns> public static string Decrypt(string cipher) { if (string.IsNullOrEmpty(cipher)) { return(""); } using (var rijndael = new RijndaelManaged()) { var info = new EncryptionInfo(); rijndael.BlockSize = info.BlockSize; rijndael.KeySize = info.KeySize; rijndael.Mode = CipherMode.CBC; rijndael.Padding = PaddingMode.PKCS7; rijndael.IV = Encoding.UTF8.GetBytes(info.IV); rijndael.Key = Encoding.UTF8.GetBytes(info.Key); var decrypter = rijndael.CreateDecryptor(rijndael.Key, rijndael.IV); var plain = string.Empty; using (var mStream = new MemoryStream(System.Convert.FromBase64String(cipher))) { using (var ctStream = new CryptoStream(mStream, decrypter, CryptoStreamMode.Read)) { using (var sr = new StreamReader(ctStream)) { plain = sr.ReadLine(); } } } return(plain); } }
public void TestDataLength() { POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.GetPOIFSInstance().OpenResourceAsStream("protected_agile.docx")); EncryptionInfo info = new EncryptionInfo(fs); Decryptor d = Decryptor.GetInstance(info); d.VerifyPassword(Decryptor.DEFAULT_PASSWORD); Stream is1 = d.GetDataStream(fs); long len = d.Length; Assert.AreEqual(12810, len); byte[] buf = new byte[(int)len]; is1.Read(buf, 0, buf.Length); ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(buf)); while (true) { ZipEntry entry = zin.GetNextEntry(); if (entry == null) { break; } while (zin.Available > 0) { zin.Skip(zin.Available); } } }
/// <summary> /// Run the code example. /// </summary> /// <param name="service">An initialized Dfa Reporting service object /// </param> public override void Run(DfareportingService service) { long encryptionEntityId = long.Parse(_T("INSERT_ENCRYPTION_ENTITY_TYPE")); long floodlightActivityId = long.Parse(_T("INSERT_FLOODLIGHT_ACTIVITY_ID_HERE")); long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); string conversionUserId = _T("INSERT_CONVERSION_USER_ID_HERE"); string encryptionEntityType = _T("INSERT_ENCRYPTION_ENTITY_TYPE_HERE"); string encryptionSource = _T("INSERT_ENCRYPTION_SOURCE_HERE"); // Generate a timestamp in milliseconds since Unix epoch. TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1); long currentTimeInMilliseconds = (long)timeSpan.TotalMilliseconds; // Find the Floodlight configuration ID based on the provided activity ID. FloodlightActivity floodlightActivity = service.FloodlightActivities.Get(profileId, floodlightActivityId).Execute(); long floodlightConfigurationId = (long)floodlightActivity.FloodlightConfigurationId; // Create the conversion. Conversion conversion = new Conversion(); conversion.EncryptedUserId = conversionUserId; conversion.FloodlightActivityId = floodlightActivityId; conversion.FloodlightConfigurationId = floodlightConfigurationId; conversion.Ordinal = currentTimeInMilliseconds.ToString(); conversion.TimestampMicros = currentTimeInMilliseconds * 1000; // Create the encryption info. EncryptionInfo encryptionInfo = new EncryptionInfo(); encryptionInfo.EncryptionEntityId = encryptionEntityId; encryptionInfo.EncryptionEntityType = encryptionEntityType; encryptionInfo.EncryptionSource = encryptionSource; // Insert the conversion. ConversionsBatchInsertRequest request = new ConversionsBatchInsertRequest(); request.Conversions = new List <Conversion>() { conversion }; request.EncryptionInfo = encryptionInfo; ConversionsBatchInsertResponse response = service.Conversions.Batchinsert(request, profileId).Execute(); // Handle the batchinsert response. if (!response.HasFailures.Value) { Console.WriteLine("Successfully inserted conversion for encrypted user ID {0}.", conversionUserId); } else { Console.WriteLine("Error(s) inserting conversion for encrypted user ID {0}:", conversionUserId); ConversionStatus status = response.Status[0]; foreach (ConversionError error in status.Errors) { Console.WriteLine("\t[{0}]: {1}", error.Code, error.Message); } } }
/// <summary> /// Decrypt a document /// </summary> /// <param name="data">The Encrypted data</param> /// <param name="encryptionInfo">Encryption Info object</param> /// <param name="password">The password</param> /// <returns></returns> private MemoryStream DecryptDocument(byte[] data, EncryptionInfo encryptionInfo, string password) { long size = BitConverter.ToInt64(data, 0); var encryptedData = new byte[data.Length - 8]; Array.Copy(data, 8, encryptedData, 0, encryptedData.Length); if (encryptionInfo is EncryptionInfoBinary) { return DecryptBinary((EncryptionInfoBinary)encryptionInfo, password, size, encryptedData); } else { return DecryptAgile((EncryptionInfoAgile)encryptionInfo, password, size, encryptedData, data); } }
public dtoMacUrlProvider() { EncryptionInfo = new EncryptionInfo(); this.Type = Authentication.AuthenticationProviderType.UrlMacProvider; Attributes = new List <BaseUrlMacAttribute>(); }
/// <summary> /// Run the code example. /// </summary> /// <param name="service">An initialized Dfa Reporting service object /// </param> public override void Run(DfareportingService service) { long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); // Value that specify how the existing conversion is encrypted. long encryptionEntityId = long.Parse(_T("INSERT_ENCRYPTION_ENTITY_TYPE")); string encryptionEntityType = _T("INSERT_ENCRYPTION_ENTITY_TYPE_HERE"); string encryptionSource = _T("INSERT_ENCRYPTION_SOURCE_HERE"); // Values that identify the existing conversion. long floodlightActivityId = long.Parse(_T("INSERT_FLOODLIGHT_ACTIVITY_ID_HERE")); long conversionTimestamp = long.Parse(_T("INSERT_CONVERSION_TIMESTAMP_HERE")); string conversionOrdinal = _T("INSERT_CONVERSION_ORDINAL_VALUE_HERE"); string conversionUserId = _T("INSERT_CONVERSION_USER_ID_HERE"); // Values to update for the specified conversion. long newQuantity = long.Parse(_T("INSERT_NEW_CONVERSION_QUANTITY_HERE")); long newValue = long.Parse(_T("INSERT_NEW_CONVERSION_VALUE_HERE")); // [START create_conversion] MOE:strip_line // Find the Floodlight configuration ID based on the provided activity ID. FloodlightActivity floodlightActivity = service.FloodlightActivities.Get(profileId, floodlightActivityId).Execute(); long floodlightConfigurationId = (long)floodlightActivity.FloodlightConfigurationId; // Construct the conversion object with values that identify the conversion to update. Conversion conversion = new Conversion(); conversion.EncryptedUserId = conversionUserId; conversion.FloodlightActivityId = floodlightActivityId; conversion.FloodlightConfigurationId = floodlightConfigurationId; conversion.Ordinal = conversionOrdinal; conversion.TimestampMicros = conversionTimestamp; // Set the fields to be updated. These fields are required; to preserve a value from the // existing conversion, it must be copied over manually. conversion.Quantity = newQuantity; conversion.Value = newValue; // [END create_conversion] MOE:strip_line // [START create_encryption_info] MOE:strip_line // Create the encryption info. EncryptionInfo encryptionInfo = new EncryptionInfo(); encryptionInfo.EncryptionEntityId = encryptionEntityId; encryptionInfo.EncryptionEntityType = encryptionEntityType; encryptionInfo.EncryptionSource = encryptionSource; // [END create_encryption_info] MOE:strip_line // [START update_conversion] MOE:strip_line // Insert the conversion. ConversionsBatchUpdateRequest request = new ConversionsBatchUpdateRequest(); request.Conversions = new List <Conversion>() { conversion }; request.EncryptionInfo = encryptionInfo; ConversionsBatchUpdateResponse response = service.Conversions.Batchupdate(request, profileId).Execute(); // [END update_conversion] MOE:strip_line // [START process_response] MOE:strip_line // Handle the batchinsert response. if (!response.HasFailures.Value) { Console.WriteLine("Successfully updated conversion for encrypted user ID {0}.", conversionUserId); } else { Console.WriteLine("Error(s) updating conversion for encrypted user ID {0}:", conversionUserId); ConversionStatus status = response.Status[0]; foreach (ConversionError error in status.Errors) { Console.WriteLine("\t[{0}]: {1}", error.Code, error.Message); } } // [END process_response] MOE:strip_line }
public void SettingInitVectorToValidValueShouldNotThrowAnError() { EncryptionInfo es = new EncryptionInfo(); es.InitVector = "a1B2c3@4e5F6g7H^"; }
public void SettingInitVectorToSmallValueShouldThrowAnError() { EncryptionInfo es = new EncryptionInfo(); es.InitVector = "A4238&@@"; }
public void SettingHashAlgorithmToInvalidValueShouldThrowAnError() { EncryptionInfo es = new EncryptionInfo(); es.HashAlgorithm = "AES"; }
public GetAllLicenseActivationsResult GetAllServiceLicenseActivations(string url, string token, EncryptionInfo encryptionInfo, KeyPair serviceKeys) { ReportingServiceClient client = ReportingClientCreator(url); string encryptedToken = _symmetricEncryptionProvider.Encrypt(token, encryptionInfo); string encryptedResult = client.GetAllLicenseActivations(encryptedToken); string decryptedResult = _asymmetricEncryptionProvider.DecryptPublic(encryptedResult, serviceKeys); GetAllLicenseActivationsResult result = _objectSerializationProvider.Deserialize <GetAllLicenseActivationsResult>(decryptedResult); return(result); }
public void AgileEncryption() { int maxKeyLen = Cipher.GetMaxAllowedKeyLength("AES"); Assume.That(maxKeyLen == 2147483647, "Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256"); FileStream file = POIDataSamples.GetDocumentInstance().GetFile("bug53475-password-is-pass.docx"); String pass = "******"; NPOIFSFileSystem nfs = new NPOIFSFileSystem(file); // Check the encryption details EncryptionInfo infoExpected = new EncryptionInfo(nfs); Decryptor decExpected = Decryptor.GetInstance(infoExpected); bool passed = decExpected.VerifyPassword(pass); Assert.IsTrue(passed, "Unable to Process: document is encrypted"); // extract the payload Stream is1 = decExpected.GetDataStream(nfs); byte[] payloadExpected = IOUtils.ToByteArray(is1); is1.Close(); long decPackLenExpected = decExpected.GetLength(); Assert.AreEqual(decPackLenExpected, payloadExpected.Length); is1 = nfs.Root.CreateDocumentInputStream(Decryptor.DEFAULT_POIFS_ENTRY); ///is1 = new BoundedInputStream(is1, is1.Available() - 16); // ignore pAdding block ///throw new NotImplementedException(BoundedInputStream); byte[] encPackExpected = IOUtils.ToByteArray(is1); is1.Close(); // listDir(nfs.Root, "orig", ""); nfs.Close(); // check that same verifier/salt lead to same hashes byte[] verifierSaltExpected = infoExpected.Verifier.Salt; byte[] verifierExpected = decExpected.GetVerifier(); byte[] keySalt = infoExpected.Header.KeySalt; byte[] keySpec = decExpected.GetSecretKey().GetEncoded(); byte[] integritySalt = decExpected.GetIntegrityHmacKey(); // the hmacs of the file always differ, as we use PKCS5-pAdding to pad the bytes // whereas office just uses random bytes // byte integrityHash[] = d.IntegrityHmacValue; POIFSFileSystem fs = new POIFSFileSystem(); EncryptionInfo infoActual = new EncryptionInfo( EncryptionMode.Agile , infoExpected.Verifier.CipherAlgorithm , infoExpected.Verifier.HashAlgorithm , infoExpected.Header.KeySize , infoExpected.Header.BlockSize , infoExpected.Verifier.ChainingMode ); Encryptor e = Encryptor.GetInstance(infoActual); e.ConfirmPassword(pass, keySpec, keySalt, verifierExpected, verifierSaltExpected, integritySalt); Stream os = e.GetDataStream(fs); IOUtils.Copy(new MemoryStream(payloadExpected), os); os.Close(); MemoryStream bos = new MemoryStream(); fs.WriteFileSystem(bos); nfs = new NPOIFSFileSystem(new MemoryStream(bos.ToArray())); infoActual = new EncryptionInfo(nfs.Root); Decryptor decActual = Decryptor.GetInstance(infoActual); passed = decActual.VerifyPassword(pass); Assert.IsTrue(passed, "Unable to Process: document is encrypted"); // extract the payload is1 = decActual.GetDataStream(nfs); byte[] payloadActual = IOUtils.ToByteArray(is1); is1.Close(); long decPackLenActual = decActual.GetLength(); is1 = nfs.Root.CreateDocumentInputStream(Decryptor.DEFAULT_POIFS_ENTRY); ///is1 = new BoundedInputStream(is1, is1.Available() - 16); // ignore pAdding block ///throw new NotImplementedException(BoundedInputStream); byte[] encPackActual = IOUtils.ToByteArray(is1); is1.Close(); // listDir(nfs.Root, "copy", ""); nfs.Close(); AgileEncryptionHeader aehExpected = (AgileEncryptionHeader)infoExpected.Header; AgileEncryptionHeader aehActual = (AgileEncryptionHeader)infoActual.Header; CollectionAssert.AreEqual(aehExpected.GetEncryptedHmacKey(), aehActual.GetEncryptedHmacKey()); Assert.AreEqual(decPackLenExpected, decPackLenActual); CollectionAssert.AreEqual(payloadExpected, payloadActual); CollectionAssert.AreEqual(encPackExpected, encPackActual); }
public void StandardEncryption() { FileStream file = POIDataSamples.GetDocumentInstance().GetFile("bug53475-password-is-solrcell.docx"); String pass = "******"; NPOIFSFileSystem nfs = new NPOIFSFileSystem(file); // Check the encryption details EncryptionInfo infoExpected = new EncryptionInfo(nfs); Decryptor d = Decryptor.GetInstance(infoExpected); bool passed = d.VerifyPassword(pass); Assert.IsTrue(passed, "Unable to Process: document is encrypted"); // extract the payload MemoryStream bos = new MemoryStream(); Stream is1 = d.GetDataStream(nfs); IOUtils.Copy(is1, bos); is1.Close(); nfs.Close(); byte[] payloadExpected = bos.ToArray(); // check that same verifier/salt lead to same hashes byte[] verifierSaltExpected = infoExpected.Verifier.Salt; byte[] verifierExpected = d.GetVerifier(); byte[] keySpec = d.GetSecretKey().GetEncoded(); byte[] keySalt = infoExpected.Header.KeySalt; EncryptionInfo infoActual = new EncryptionInfo( EncryptionMode.Standard , infoExpected.Verifier.CipherAlgorithm , infoExpected.Verifier.HashAlgorithm , infoExpected.Header.KeySize , infoExpected.Header.BlockSize , infoExpected.Verifier.ChainingMode ); Encryptor e = Encryptor.GetInstance(infoActual); e.ConfirmPassword(pass, keySpec, keySalt, verifierExpected, verifierSaltExpected, null); CollectionAssert.AreEqual(infoExpected.Verifier.EncryptedVerifier, infoActual.Verifier.EncryptedVerifier); CollectionAssert.AreEqual(infoExpected.Verifier.EncryptedVerifierHash, infoActual.Verifier.EncryptedVerifierHash); // now we use a newly generated salt/verifier and check // if the file content is still the same infoActual = new EncryptionInfo( EncryptionMode.Standard , infoExpected.Verifier.CipherAlgorithm , infoExpected.Verifier.HashAlgorithm , infoExpected.Header.KeySize , infoExpected.Header.BlockSize , infoExpected.Verifier.ChainingMode ); e = Encryptor.GetInstance(infoActual); e.ConfirmPassword(pass); POIFSFileSystem fs = new POIFSFileSystem(); Stream os = e.GetDataStream(fs); IOUtils.Copy(new MemoryStream(payloadExpected), os); os.Close(); bos.Seek(0, SeekOrigin.Begin); //bos.Reset(); fs.WriteFileSystem(bos); ByteArrayInputStream bis = new ByteArrayInputStream(bos.ToArray()); // FileOutputStream fos = new FileOutputStream("encrypted.docx"); // IOUtils.Copy(bis, fos); // fos.Close(); // bis.Reset(); nfs = new NPOIFSFileSystem(bis); infoExpected = new EncryptionInfo(nfs); d = Decryptor.GetInstance(infoExpected); passed = d.VerifyPassword(pass); Assert.IsTrue(passed, "Unable to Process: document is encrypted"); bos.Seek(0, SeekOrigin.Begin); //bos.Reset(); is1 = d.GetDataStream(nfs); IOUtils.Copy(is1, bos); is1.Close(); nfs.Close(); byte[] payloadActual = bos.ToArray(); CollectionAssert.AreEqual(payloadExpected, payloadActual); //assertArrayEquals(payloadExpected, payloadActual); }
public string Decrypt(string cipherText, EncryptionInfo info) { // Convert strings defining encryption key characteristics into byte // arrays. Let us assume that strings only contain ASCII codes. // If strings include Unicode characters, use Unicode, UTF7, or UTF8 // encoding. byte[] initVectorBytes = Encoding.ASCII.GetBytes(info.InitVector); byte[] saltValueBytes = Encoding.ASCII.GetBytes(info.SaltValue); // Convert our ciphertext into a byte array. byte[] cipherTextBytes = Convert.FromBase64String(cipherText); // First, we must create a password, from which the key will be // derived. This password will be generated from the specified // passphrase and salt value. The password will be created using // the specified hash algorithm. Password creation can be done in // several iterations. PasswordDeriveBytes password = new PasswordDeriveBytes( info.PassPhrase, saltValueBytes, info.HashAlgorithm, info.Iterations); // Use the password to generate pseudo-random bytes for the encryption // key. Specify the size of the key in bytes (instead of bits). byte[] keyBytes = password.GetBytes(info.KeySize / 8); // Create uninitialized Rijndael encryption object. RijndaelManaged symmetricKey = new RijndaelManaged(); // It is reasonable to set encryption mode to Cipher Block Chaining // (CBC). Use default options for other symmetric key parameters. symmetricKey.Mode = CipherMode.CBC; // Generate decryptor from the existing key bytes and initialization // vector. Key size will be defined based on the number of the key // bytes. ICryptoTransform decryptor = symmetricKey.CreateDecryptor( keyBytes, initVectorBytes); // Define memory stream which will be used to hold encrypted data. MemoryStream memoryStream = new MemoryStream(cipherTextBytes); // Define cryptographic stream (always use Read mode for encryption). CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); // Since at this point we don't know what the size of decrypted data // will be, allocate the buffer long enough to hold ciphertext; // plaintext is never longer than ciphertext. byte[] plainTextBytes = new byte[cipherTextBytes.Length]; // Start decrypting. int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); // Close both streams. memoryStream.Close(); cryptoStream.Close(); // Convert decrypted data into a string. // Let us assume that the original plaintext string was UTF8-encoded. string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount); // Return decrypted string. return(plainText); }
/// <summary> /// Converts Encryption Info to the Vislink required format /// </summary> /// <param name="info">info to convert</param> /// <param name="type">integer type indicator for h-scr parameter</param> /// <param name="key">32 char string for h-key parameter</param> private void GetEncryptionType(EncryptionInfo info, out int type, out string key) { if (info == null) { info = new EncryptionInfo() { Type = EncryptionType.None }; } switch (info.Type) { case EncryptionType.None: type = 0; break; case EncryptionType.AES_Legacy: if (info.KeyLength == 128) { type = 1; } else if (info.KeyLength == 256) { type = 2; } else { throw new NotSupportedException("Encryption algorithm " + info.Type + " with a key length of " + info.KeyLength + " bits is not supported!"); } break; case EncryptionType.AES_Bcrypt: if (info.KeyLength == 128) { type = 3; } else if (info.KeyLength == 256) { type = 4; } else { throw new NotSupportedException("Encryption algorithm " + info.Type + " with a key length of " + info.KeyLength + " bits is not supported!"); } break; case EncryptionType.BISS_1: type = 5; break; case EncryptionType.BISS_E: type = 6; break; case EncryptionType.DES: type = 7; break; default: throw new NotSupportedException("Encryption algorithim " + info.Type + " is not supported!"); } if (info.Type != EncryptionType.None) { if (info.DecryptionKey == null) { throw new ArgumentNullException("EncryptionInfo.DecryptionKey", "DecryptionKey may not be null"); } if ((info.KeyLength / 4) != info.DecryptionKey.Length) { throw new ArgumentOutOfRangeException("KeyLength does not match DecryptionKey length!"); } StringBuilder k = new StringBuilder(); foreach (byte b in info.DecryptionKey) { k.Append(b.ToString("X1")); } key = k.ToString(); } else { key = null; } }
public void SettingKeySizeToAnIncorrectValueShouldThrowAnError() { EncryptionInfo es = new EncryptionInfo(); es.KeySize = 101; }
public void SettingKeySizeTo256ValueShouldNotThrowAnError() { EncryptionInfo es = new EncryptionInfo(); es.KeySize = 256; }
public MasterConfiguration SaveMasterConfiguration(MasterConfiguration masterConfiguration, EncryptionInfo encryptionInfo) { if (File.Exists(Name)) { File.Delete(Name); } string plainTextObjectData; plainTextObjectData = _objectSerializationProvider.Serialize(masterConfiguration); string encryptedObjectData; encryptedObjectData = _encryptionProvider.Encrypt(plainTextObjectData, encryptionInfo); using (StreamWriter writer = new StreamWriter(Name)) { writer.Write(encryptedObjectData); } return(GetMasterConfiguration(encryptionInfo)); }
public void SettingHashAlgorithmToMD5ShouldNotThrowAnError() { EncryptionInfo es = new EncryptionInfo(); es.HashAlgorithm = "MD5"; }
public SetupTestProductResult CleanUpTestProductData(string url, string token, EncryptionInfo encryptionInfo) { StatusServiceClient client = StatusServiceClientCreator(url); string encryptedToken = _symmetricEncryptionProvider.Encrypt(token, encryptionInfo); string result = client.CleanTestProductData(encryptedToken); string decryptedResult = _symmetricEncryptionProvider.Decrypt(result, encryptionInfo); SetupTestProductResult setupTestProductResult = _objectSerializationProvider.Deserialize <SetupTestProductResult>(decryptedResult); return(setupTestProductResult); }
public void SettingInitVectorToLargeValueShouldThrowAnError() { EncryptionInfo es = new EncryptionInfo(); es.InitVector = "A4238&@@AS!@@Dasd)_!jasdad1351D4!@#"; }
public string Encrypt(string plainText, EncryptionInfo info) { // Convert strings into byte arrays. // Let us assume that strings only contain ASCII codes. // If strings include Unicode characters, use Unicode, UTF7, or UTF8 // encoding. byte[] initVectorBytes = Encoding.ASCII.GetBytes(info.InitVector); byte[] saltValueBytes = Encoding.ASCII.GetBytes(info.SaltValue); // Convert our plaintext into a byte array. // Let us assume that plaintext contains UTF8-encoded characters. byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); // First, we must create a password, from which the key will be derived. // This password will be generated from the specified passphrase and // salt value. The password will be created using the specified hash // algorithm. Password creation can be done in several iterations. PasswordDeriveBytes password = new PasswordDeriveBytes( info.PassPhrase, saltValueBytes, info.HashAlgorithm, info.Iterations); // Use the password to generate pseudo-random bytes for the encryption // key. Specify the size of the key in bytes (instead of bits). byte[] keyBytes = password.GetBytes(info.KeySize / 8); // Create uninitialized Rijndael encryption object. RijndaelManaged symmetricKey = new RijndaelManaged(); // It is reasonable to set encryption mode to Cipher Block Chaining // (CBC). Use default options for other symmetric key parameters. symmetricKey.Mode = CipherMode.CBC; // Generate encryptor from the existing key bytes and initialization // vector. Key size will be defined based on the number of the key // bytes. ICryptoTransform encryptor = symmetricKey.CreateEncryptor( keyBytes, initVectorBytes); // Define memory stream which will be used to hold encrypted data. MemoryStream memoryStream = new MemoryStream(); // Define cryptographic stream (always use Write mode for encryption). CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); // Start encrypting. cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); // Finish encrypting. cryptoStream.FlushFinalBlock(); // Convert our encrypted data from a memory stream into a byte array. byte[] cipherTextBytes = memoryStream.ToArray(); // Close both streams. memoryStream.Close(); cryptoStream.Close(); // Convert encrypted data into a base64-encoded string. string cipherText = Convert.ToBase64String(cipherTextBytes); // Return encrypted string. return(cipherText); }
public XlsBiffStream(Stream baseStream, int offset = 0, int explicitVersion = 0, string password = null, byte[] secretKey = null, EncryptionInfo encryption = null) { BaseStream = baseStream; Position = offset; var bof = Read() as XlsBiffBOF; if (bof != null) { BiffVersion = explicitVersion == 0 ? GetBiffVersion(bof) : explicitVersion; BiffType = bof.Type; } CipherBlock = -1; if (secretKey != null) { SecretKey = secretKey; Encryption = encryption; Cipher = Encryption.CreateCipher(); } else { var filePass = Read() as XlsBiffFilePass; if (filePass == null) { filePass = Read() as XlsBiffFilePass; } if (filePass != null) { Encryption = filePass.EncryptionInfo; if (Encryption.VerifyPassword("VelvetSweatshop")) { // Magic password used for write-protected workbooks password = "******"; } else if (!Encryption.VerifyPassword(password)) { throw new InvalidPasswordException(Errors.ErrorInvalidPassword); } SecretKey = Encryption.GenerateSecretKey(password); Cipher = Encryption.CreateCipher(); } } Position = offset; }
/// <summary> /// For a given named property entry, either return it or null if /// if it wasn't found /// </summary> /// <param name="setName">The property to read</param> /// <param name="encryptionInfo">the encryption descriptor in case of cryptoAPI encryption</param> /// <returns>The value of the given property or null if it wasn't found.</returns> /// <exception cref="IOException">If retrieving properties fails</exception> protected PropertySet GetPropertySet(string setName, EncryptionInfo encryptionInfo) { DirectoryNode dirNode = directory; NPOIFSFileSystem encPoifs = null; String step = "getting"; try { if (encryptionInfo != null) { step = "getting encrypted"; InputStream is1 = encryptionInfo.Decryptor.GetDataStream(directory); try { encPoifs = new NPOIFSFileSystem(is1); dirNode = encPoifs.Root; } finally { is1.Close(); } } //directory can be null when creating new documents if (dirNode == null || !dirNode.HasEntry(setName)) { return(null); } // Find the entry, and get an input stream for it step = "getting"; DocumentInputStream dis = dirNode.CreateDocumentInputStream(dirNode.GetEntry(setName)); try { // Create the Property Set step = "creating"; return(PropertySetFactory.Create(dis)); } finally { dis.Close(); } } catch (Exception e) { logger.Log(POILogger.WARN, "Error " + step + " property set with name " + setName, e); return(null); } finally { if (encPoifs != null) { try { encPoifs.Close(); } catch (IOException e) { logger.Log(POILogger.WARN, "Error closing encrypted property poifs", e); } } } }
public InitializationResult InitializeService(string url, string token, MasterServiceData data, EncryptionInfo encryptionInfo) { StatusServiceClient client = StatusServiceClientCreator(url); string encryptedToken = _symmetricEncryptionProvider.Encrypt(token, encryptionInfo); string serializedData = _objectSerializationProvider.Serialize(data); string encryptedData = _symmetricEncryptionProvider.Encrypt(serializedData, encryptionInfo); string result = client.InitializeService(encryptedToken, encryptedData); string decryptedResult = _symmetricEncryptionProvider.Decrypt(result, encryptionInfo); InitializationResult initializationResult = _objectSerializationProvider.Deserialize <InitializationResult>(decryptedResult); return(initializationResult); }
private void clear_Click(object sender, EventArgs e) { SelectedEncryption = null; RaiseDialogClosed(false); }
public QueryActiveServiceProductsResult GetActiveServiceProducts(string url, string token, EncryptionInfo encryptionInfo, KeyPair serviceKeys) { StatusServiceClient client = StatusServiceClientCreator(url); string encryptedToken = _symmetricEncryptionProvider.Encrypt(token, encryptionInfo); string encryptedResult = client.QueryActiveProductsAndLiceseSets(encryptedToken); string decryptedResult = _asymmetricEncryptionProvider.DecryptPublic(encryptedResult, serviceKeys); QueryActiveServiceProductsResult result = _objectSerializationProvider.Deserialize <QueryActiveServiceProductsResult>(decryptedResult); return(result); }
/// <summary> /// Run the code example. /// </summary> /// <param name="service">An initialized Dfa Reporting service object /// </param> public override void Run(DfareportingService service) { long encryptionEntityId = long.Parse(_T("INSERT_ENCRYPTION_ENTITY_TYPE")); long floodlightActivityId = long.Parse(_T("INSERT_FLOODLIGHT_ACTIVITY_ID_HERE")); long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); string conversionUserId = _T("INSERT_CONVERSION_USER_ID_HERE"); string encryptionEntityType = _T("INSERT_ENCRYPTION_ENTITY_TYPE_HERE"); string encryptionSource = _T("INSERT_ENCRYPTION_SOURCE_HERE"); // Generate a timestamp in milliseconds since Unix epoch. TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1); long currentTimeInMilliseconds = (long) timeSpan.TotalMilliseconds; // Find the Floodlight configuration ID based on the provided activity ID. FloodlightActivity floodlightActivity = service.FloodlightActivities.Get(profileId, floodlightActivityId).Execute(); long floodlightConfigurationId = (long) floodlightActivity.FloodlightConfigurationId; // Create the conversion. Conversion conversion = new Conversion(); conversion.EncryptedUserId = conversionUserId; conversion.FloodlightActivityId = floodlightActivityId; conversion.FloodlightConfigurationId = floodlightConfigurationId; conversion.Ordinal = currentTimeInMilliseconds.ToString(); conversion.TimestampMicros = currentTimeInMilliseconds * 1000; // Create the encryption info. EncryptionInfo encryptionInfo = new EncryptionInfo(); encryptionInfo.EncryptionEntityId = encryptionEntityId; encryptionInfo.EncryptionEntityType = encryptionEntityType; encryptionInfo.EncryptionSource = encryptionSource; // Insert the conversion. ConversionsBatchInsertRequest request = new ConversionsBatchInsertRequest(); request.Conversions = new List<Conversion>() { conversion }; request.EncryptionInfo = encryptionInfo; ConversionsBatchInsertResponse response = service.Conversions.Batchinsert(request, profileId).Execute(); // Handle the batchinsert response. if (!response.HasFailures.Value) { Console.WriteLine("Successfully inserted conversion for encrypted user ID {0}.", conversionUserId); } else { Console.WriteLine("Error(s) inserting conversion for encrypted user ID {0}:", conversionUserId); ConversionStatus status = response.Status[0]; foreach(ConversionError error in status.Errors) { Console.WriteLine("\t[{0}]: {1}", error.Code, error.Message); } } }