public static byte[] DoFinal( IMac mac) { byte[] b = new byte[mac.GetMacSize()]; mac.DoFinal(b, 0); return b; }
public string PubnubAccessManagerSign(string key, string data) { string secret = key; string message = data; var encoding = new System.Text.UTF8Encoding(); byte[] keyByte = encoding.GetBytes(secret); byte[] messageBytes = encoding.GetBytes(message); //http://mycsharp.de/wbb2/thread.php?postid=3550104 KeyParameter paramKey = new KeyParameter(keyByte); IMac mac = MacUtilities.GetMac("HMac-SHA256"); mac.Init(paramKey); mac.Reset(); mac.BlockUpdate(messageBytes, 0, messageBytes.Length); byte[] hashmessage = new byte[mac.GetMacSize()]; mac.DoFinal(hashmessage, 0); return(Convert.ToBase64String(hashmessage).Replace('+', '-').Replace('/', '_')); }
private byte[] Compute(long Length) { long bytesTotal = 0; byte[] chkSum = new byte[_macEngine.MacSize]; if (!m_isConcurrent) { byte[] buffer = new byte[m_blockSize]; int bytesRead = 0; long maxBlocks = Length / m_blockSize; for (int i = 0; i < maxBlocks; i++) { bytesRead = m_inStream.Read(buffer, 0, m_blockSize); _macEngine.BlockUpdate(buffer, 0, bytesRead); bytesTotal += bytesRead; CalculateProgress(bytesTotal); } // last block if (bytesTotal < Length) { buffer = new byte[Length - bytesTotal]; bytesRead = m_inStream.Read(buffer, 0, buffer.Length); _macEngine.BlockUpdate(buffer, 0, bytesRead); bytesTotal += bytesRead; } } else { bytesTotal = ConcurrentStream(m_inStream, Length); } // get the hash _macEngine.DoFinal(chkSum, 0); CalculateProgress(bytesTotal); return(chkSum); }
private void generateNext() { int i = generatedBytes / h + 1; // encode i into counter buffer switch (ios.Length) { case 4: ios[0] = (byte)(i >> 24); goto case 3; // fall through case 3: ios[ios.Length - 3] = (byte)(i >> 16); // fall through goto case 2; case 2: ios[ios.Length - 2] = (byte)(i >> 8); // fall through goto case 1; case 1: ios[ios.Length - 1] = (byte)i; break; default: throw new InvalidOperationException("Unsupported size of counter i"); } // special case for K(0): K(0) is empty, so no update prf.BlockUpdate(fixedInputDataCtrPrefix, 0, fixedInputDataCtrPrefix.Length); prf.BlockUpdate(ios, 0, ios.Length); prf.BlockUpdate(fixedInputData_afterCtr, 0, fixedInputData_afterCtr.Length); prf.DoFinal(k, 0); }
public void Save( Stream stream, char[] password, SecureRandom random) { if (stream == null) { throw new ArgumentNullException("stream"); } if (password == null) { throw new ArgumentNullException("password"); } if (random == null) { throw new ArgumentNullException("random"); } ContentInfo[] c = new ContentInfo[2]; // // handle the key // Asn1EncodableVector keyS = new Asn1EncodableVector(); foreach (string name in keys.Keys) { byte[] kSalt = new byte[saltSize]; random.NextBytes(kSalt); AsymmetricKeyEntry privKey = (AsymmetricKeyEntry)keys[name]; EncryptedPrivateKeyInfo kInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo( keyAlgorithm, password, kSalt, minIterations, privKey.Key); Asn1EncodableVector kName = new Asn1EncodableVector(); foreach (string oid in privKey.BagAttributeKeys) { kName.Add( new DerSequence( new DerObjectIdentifier(oid), new DerSet(privKey[oid]))); } // // make sure we have a local key-id // if (privKey[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null) { X509CertificateEntry ct = GetCertificate(name); SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo( ct.Certificate.GetPublicKey()); kName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtLocalKeyID, new DerSet(new SubjectKeyIdentifier(info)))); } // // make sure we are using the local alias on store // DerBmpString nm = (DerBmpString)privKey[PkcsObjectIdentifiers.Pkcs9AtFriendlyName]; if (nm == null || !nm.GetString().Equals(name)) { kName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(name)))); } SafeBag kBag = new SafeBag(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag, kInfo.ToAsn1Object(), new DerSet(kName)); keyS.Add(kBag); } byte[] derEncodedBytes = new DerSequence(keyS).GetDerEncoded(); BerOctetString keyString = new BerOctetString(derEncodedBytes); // // certificate processing // byte[] cSalt = new byte[saltSize]; random.NextBytes(cSalt); Asn1EncodableVector certSeq = new Asn1EncodableVector(); Pkcs12PbeParams cParams = new Pkcs12PbeParams(cSalt, minIterations); AlgorithmIdentifier cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.ToAsn1Object()); Hashtable doneCerts = new Hashtable(); foreach (string name in keys.Keys) { X509CertificateEntry certEntry = GetCertificate(name); CertBag cBag = new CertBag( PkcsObjectIdentifiers.X509CertType, new DerOctetString(certEntry.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in certEntry.BagAttributeKeys) { fName.Add( new DerSequence( new DerObjectIdentifier(oid), new DerSet(certEntry[oid]))); } // // make sure we are using the local alias on store // DerBmpString nm = (DerBmpString)certEntry[PkcsObjectIdentifiers.Pkcs9AtFriendlyName]; if (nm == null || !nm.GetString().Equals(name)) { fName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(name)))); } // // make sure we have a local key-id // if (certEntry[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null) { SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo( certEntry.Certificate.GetPublicKey()); fName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtLocalKeyID, new DerSet(new SubjectKeyIdentifier(info)))); } SafeBag sBag = new SafeBag( PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); doneCerts.Add(certEntry.Certificate, certEntry.Certificate); } foreach (string certId in certs.Keys) { X509CertificateEntry cert = (X509CertificateEntry)certs[certId]; if (keys[certId] != null) { continue; } CertBag cBag = new CertBag( PkcsObjectIdentifiers.X509CertType, new DerOctetString(cert.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in cert.BagAttributeKeys) { fName.Add( new DerSequence( new DerObjectIdentifier(oid), new DerSet(cert[oid]))); } // // make sure we are using the local alias on store // DerBmpString nm = (DerBmpString)cert[PkcsObjectIdentifiers.Pkcs9AtFriendlyName]; if (nm == null || !nm.GetString().Equals(certId)) { fName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(certId)))); } SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); doneCerts.Add(cert, cert); } foreach (CertId certId in chainCerts.Keys) { X509CertificateEntry cert = (X509CertificateEntry)chainCerts[certId]; if (doneCerts[cert] != null) { continue; } CertBag cBag = new CertBag( PkcsObjectIdentifiers.X509CertType, new DerOctetString(cert.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in cert.BagAttributeKeys) { fName.Add(new DerSequence(new DerObjectIdentifier(oid), new DerSet(cert[oid]))); } SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); } derEncodedBytes = new DerSequence(certSeq).GetDerEncoded(); byte[] certBytes = EncryptData(new AlgorithmIdentifier(certAlgorithm, cParams), derEncodedBytes, password); EncryptedData cInfo = new EncryptedData(PkcsObjectIdentifiers.Data, cAlgId, new BerOctetString(certBytes)); c[0] = new ContentInfo(PkcsObjectIdentifiers.Data, keyString); c[1] = new ContentInfo(PkcsObjectIdentifiers.EncryptedData, cInfo.ToAsn1Object()); AuthenticatedSafe auth = new AuthenticatedSafe(c); byte[] pkg = auth.GetEncoded(); ContentInfo mainInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(pkg)); // // create the mac // byte[] mSalt = new byte[20]; int itCount = minIterations; random.NextBytes(mSalt); byte[] data = ((Asn1OctetString)mainInfo.Content).GetOctets(); MacData mData = null; Asn1Encodable parameters = PbeUtilities.GenerateAlgorithmParameters(OiwObjectIdentifiers.IdSha1, mSalt, itCount); ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters( OiwObjectIdentifiers.IdSha1, password, parameters); IMac mac = (IMac)PbeUtilities.CreateEngine(OiwObjectIdentifiers.IdSha1); mac.Init(keyParameters); mac.BlockUpdate(data, 0, data.Length); byte[] res = new byte[mac.GetMacSize()]; mac.DoFinal(res, 0); AlgorithmIdentifier algId = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance); DigestInfo dInfo = new DigestInfo(algId, res); mData = new MacData(dInfo, mSalt, itCount); // // output the Pfx // Pfx pfx = new Pfx(mainInfo, mData); BerOutputStream berOut = new BerOutputStream(stream); berOut.WriteObject(pfx); }
public Pkcs12Store( Stream input, char[] password) { if (input == null) { throw new ArgumentNullException("input"); } if (password == null) { throw new ArgumentNullException("password"); } Asn1InputStream bIn = new Asn1InputStream(input); Asn1Sequence obj = (Asn1Sequence)bIn.ReadObject(); Pfx bag = new Pfx(obj); ContentInfo info = bag.AuthSafe; ArrayList chain = new ArrayList(); bool unmarkedKey = false; bool wrongPkcs12Zero = false; if (bag.MacData != null) // check the mac code { MacData mData = bag.MacData; DigestInfo dInfo = mData.Mac; AlgorithmIdentifier algId = dInfo.AlgorithmID; byte[] salt = mData.GetSalt(); int itCount = mData.IterationCount.IntValue; byte[] data = ((Asn1OctetString)info.Content).GetOctets(); Asn1Encodable parameters = PbeUtilities.GenerateAlgorithmParameters( algId.ObjectID, salt, itCount); ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters( algId.ObjectID, password, parameters); IMac mac = (IMac)PbeUtilities.CreateEngine(algId.ObjectID); mac.Init(keyParameters); mac.BlockUpdate(data, 0, data.Length); byte[] res = new byte[mac.GetMacSize()]; mac.DoFinal(res, 0); byte[] dig = dInfo.GetDigest(); if (!Arrays.AreEqual(res, dig)) { if (password.Length > 0) { throw new Exception("Pkcs12 key store mac invalid - wrong password or corrupted file."); } // // may be incorrect zero length password // keyParameters = PbeUtilities.GenerateCipherParameters( algId.ObjectID, password, true, parameters); mac.Init(keyParameters); mac.BlockUpdate(data, 0, data.Length); res = new byte[mac.GetMacSize()]; mac.DoFinal(res, 0); if (!Arrays.AreEqual(res, dig)) { throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file."); } wrongPkcs12Zero = true; } } keys = new Hashtable(); localIds = new Hashtable(); if (info.ContentType.Equals(PkcsObjectIdentifiers.Data)) { byte[] octs = ((Asn1OctetString)info.Content).GetOctets(); AuthenticatedSafe authSafe = new AuthenticatedSafe( (Asn1Sequence)Asn1OctetString.FromByteArray(octs)); ContentInfo[] c = authSafe.GetContentInfo(); for (int i = 0; i != c.Length; i++) { if (c[i].ContentType.Equals(PkcsObjectIdentifiers.Data)) { byte[] octets = ((Asn1OctetString)c[i].Content).GetOctets(); Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets); for (int j = 0; j != seq.Count; j++) { SafeBag b = new SafeBag((Asn1Sequence)seq[j]); if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { EncryptedPrivateKeyInfo eIn = EncryptedPrivateKeyInfo.GetInstance(b.BagValue); PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo( password, wrongPkcs12Zero, eIn); AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo); // // set the attributes on the key // Hashtable attributes = new Hashtable(); AsymmetricKeyEntry pkcs12Key = new AsymmetricKeyEntry(privKey, attributes); string alias = null; Asn1OctetString localId = null; if (b.BagAttributes != null) { foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier)sq[0]; Asn1Set attrSet = (Asn1Set)sq[1]; Asn1Encodable attr = null; if (attrSet.Count > 0) { attr = attrSet[0]; attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } if (localId != null) { string name = Encoding.ASCII.GetString(Hex.Encode(localId.GetOctets())); if (alias == null) { keys[name] = pkcs12Key; } else { localIds[alias] = name; } } else { unmarkedKey = true; keys["unmarked"] = pkcs12Key; } } else if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag)) { chain.Add(b); } else { Console.WriteLine("extra " + b.BagID); Console.WriteLine("extra " + Asn1Dump.DumpAsString(b)); } } } else if (c[i].ContentType.Equals(PkcsObjectIdentifiers.EncryptedData)) { EncryptedData d = EncryptedData.GetInstance(c[i].Content); Asn1Sequence seq = DecryptData(d.EncryptionAlgorithm, d.Content.GetOctets(), password, wrongPkcs12Zero); for (int j = 0; j != seq.Count; j++) { SafeBag b = new SafeBag((Asn1Sequence)seq[j]); if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag)) { chain.Add(b); } else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { EncryptedPrivateKeyInfo eIn = EncryptedPrivateKeyInfo.GetInstance(b.BagValue); PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo( password, wrongPkcs12Zero, eIn); AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo); // // set the attributes on the key // Hashtable attributes = new Hashtable(); AsymmetricKeyEntry pkcs12Key = new AsymmetricKeyEntry(privKey, attributes); string alias = null; Asn1OctetString localId = null; foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier)sq[0]; Asn1Set attrSet = (Asn1Set)sq[1]; Asn1Encodable attr = null; if (attrSet.Count > 0) { attr = attrSet[0]; attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } string name = Encoding.ASCII.GetString(Hex.Encode(localId.GetOctets())); if (alias == null) { keys[name] = pkcs12Key; } else { localIds[alias] = name; } } else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag)) { PrivateKeyInfo privKeyInfo = PrivateKeyInfo.GetInstance(b.BagValue); AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privKeyInfo); // // set the attributes on the key // string alias = null; Asn1OctetString localId = null; Hashtable attributes = new Hashtable(); AsymmetricKeyEntry pkcs12Key = new AsymmetricKeyEntry(privKey, attributes); foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier)sq[0]; Asn1Set attrSet = (Asn1Set)sq[1]; Asn1Encodable attr = null; if (attrSet.Count > 0) { attr = attrSet[0]; attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } string name = Encoding.ASCII.GetString(Hex.Encode(localId.GetOctets())); if (alias == null) { keys[name] = pkcs12Key; } else { localIds[alias] = name; } } else { Console.WriteLine("extra " + b.BagID); Console.WriteLine("extra " + Asn1Dump.DumpAsString(b)); } } } else { Console.WriteLine("extra " + c[i].ContentType.Id); Console.WriteLine("extra " + Asn1Dump.DumpAsString(c[i].Content)); } } } certs = new Hashtable(); chainCerts = new Hashtable(); keyCerts = new Hashtable(); for (int i = 0; i < chain.Count; ++i) { SafeBag b = (SafeBag)chain[i]; CertBag cb = new CertBag((Asn1Sequence)b.BagValue); byte[] octets = ((Asn1OctetString)cb.CertValue).GetOctets(); X509Certificate cert = new X509CertificateParser().ReadCertificate(octets); // // set the attributes // Hashtable attributes = new Hashtable(); X509CertificateEntry pkcs12Cert = new X509CertificateEntry(cert, attributes); Asn1OctetString localId = null; string alias = null; if (b.BagAttributes != null) { foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier)sq[0]; Asn1Set attrSet = (Asn1Set)sq[1]; if (attrSet.Count > 0) { Asn1Encodable attr = attrSet[0]; attributes.Add(aOid.Id, attr); if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } } AsymmetricKeyParameter publicKey = cert.GetPublicKey(); chainCerts[new CertId(publicKey)] = pkcs12Cert; if (unmarkedKey) { if (keyCerts.Count == 0) { string name = Encoding.ASCII.GetString( Hex.Encode( new SubjectKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey)).GetKeyIdentifier())); keyCerts[name] = pkcs12Cert; object temp = keys["unmarked"]; keys.Remove("unmarked"); keys[name] = temp; } } else { if (localId != null) { string name = Encoding.ASCII.GetString( Hex.Encode(localId.GetOctets())); keyCerts[name] = pkcs12Cert; } if (alias != null) { certs[alias] = pkcs12Cert; } } } }
public override void PerformTest() { KeyParameter key = new DesParameters(keyBytes); IMac mac = MacUtilities.GetMac("DESMac"); // // standard DAC - zero IV // mac.Init(key); mac.BlockUpdate(input, 0, input.Length); //byte[] outBytes = mac.DoFinal(); byte[] outBytes = new byte[mac.GetMacSize()]; mac.DoFinal(outBytes, 0); if (!AreEqual(outBytes, output1)) { Fail("Failed - expected " + Hex.ToHexString(output1) + " got " + Hex.ToHexString(outBytes)); } // // mac with IV. // mac.Init(new ParametersWithIV(key, ivBytes)); mac.BlockUpdate(input, 0, input.Length); //outBytes = mac.DoFinal(); outBytes = new byte[mac.GetMacSize()]; mac.DoFinal(outBytes, 0); if (!AreEqual(outBytes, output2)) { Fail("Failed - expected " + Hex.ToHexString(output2) + " got " + Hex.ToHexString(outBytes)); } // // CFB mac with IV - 8 bit CFB mode // mac = MacUtilities.GetMac("DESMac/CFB8"); mac.Init(new ParametersWithIV(key, ivBytes)); mac.BlockUpdate(input, 0, input.Length); //outBytes = mac.DoFinal(); outBytes = new byte[mac.GetMacSize()]; mac.DoFinal(outBytes, 0); if (!AreEqual(outBytes, output3)) { Fail("Failed - expected " + Hex.ToHexString(output3) + " got " + Hex.ToHexString(outBytes)); } // // ISO9797 algorithm 3 using DESEDE // key = new DesEdeParameters(keyBytesISO9797); mac = MacUtilities.GetMac("ISO9797ALG3"); mac.Init(key); mac.BlockUpdate(inputISO9797, 0, inputISO9797.Length); //outBytes = mac.DoFinal(); outBytes = new byte[mac.GetMacSize()]; mac.DoFinal(outBytes, 0); if (!AreEqual(outBytes, outputISO9797)) { Fail("Failed - expected " + Hex.ToHexString(outputISO9797) + " got " + Hex.ToHexString(outBytes)); } // // 64bit DESede Mac // key = new DesEdeParameters(keyBytesISO9797); mac = MacUtilities.GetMac("DESEDE64"); mac.Init(key); mac.BlockUpdate(inputDesEDE64, 0, inputDesEDE64.Length); //outBytes = mac.DoFinal(); outBytes = new byte[mac.GetMacSize()]; mac.DoFinal(outBytes, 0); if (!AreEqual(outBytes, outputDesEDE64)) { Fail("Failed - expected " + Hex.ToHexString(outputDesEDE64) + " got " + Hex.ToHexString(outBytes)); } aliasTest( ParameterUtilities.CreateKeyParameter("DESede", keyBytesISO9797), "DESedeMac64withISO7816-4Padding", "DESEDE64WITHISO7816-4PADDING", "DESEDEISO9797ALG1MACWITHISO7816-4PADDING", "DESEDEISO9797ALG1WITHISO7816-4PADDING"); aliasTest( ParameterUtilities.CreateKeyParameter("DESede", keyBytesISO9797), "ISO9797ALG3WITHISO7816-4PADDING", "ISO9797ALG3MACWITHISO7816-4PADDING"); }
public static byte[] DoFinal(IMac mac) { byte[] b = new byte[mac.GetMacSize()]; mac.DoFinal(b, 0); return(b); }
public int Collect(byte[] destination, int offset) { mac.DoFinal(destination, offset); return(mac.GetMacSize()); }
private void checkMac(IMac mac, TestCase testCase) { byte[] generatedMac = new byte[mac.GetMacSize()]; mac.DoFinal(generatedMac, 0); if (!AreEqual(testCase.getTag(), generatedMac)) { Fail("Failed " + testCase.getName() + " - expected " + Hex.ToHexString(testCase.getTag()) + " got " + Hex.ToHexString(generatedMac)); } }
public void ComputeSignature(IMac macAlg) { if (macAlg == null) { throw new ArgumentNullException(nameof(macAlg)); } if (!(macAlg is HMac)) { throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_SignatureMethodKeyMismatch); } int signatureLength; if (MSignature.SignedInfo.SignatureLength == null) { signatureLength = macAlg.GetMacSize() * 8; } else { signatureLength = Convert.ToInt32(MSignature.SignedInfo.SignatureLength, null); } if (signatureLength < 0 || signatureLength > macAlg.GetMacSize() * 8) { throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength); } if (signatureLength % 8 != 0) { throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength2); } ReferenceManager.BuildDigestedReferences(this); var algorithmName = macAlg.AlgorithmName.Substring(0, macAlg.AlgorithmName.IndexOf('/')).ToUpperInvariant(); var signedXmlDictionary = new Dictionary <string, NS>() { { "SHA-1", NS.XmlDsigHMACSHA1Url }, { "SHA-256", NS.XmlDsigMoreHMACSHA256Url }, { "SHA-384", NS.XmlDsigMoreHMACSHA384Url }, { "SHA-512", NS.XmlDsigMoreHMACSHA512Url }, { "MD5", NS.XmlDsigMoreHMACMD5Url }, { "RIPEMD160", NS.XmlDsigMoreHMACRIPEMD160Url } }; try { SignedInfo.SignatureMethod = XmlNameSpace.Url[signedXmlDictionary[algorithmName]]; } catch (Exception) { throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_SignatureMethodKeyMismatch); } CheckSignatureManager.GetC14NDigest(new MacHashWrapper(macAlg), this); byte[] hashValue = new byte[macAlg.GetMacSize()]; macAlg.DoFinal(hashValue, 0); SignedXmlDebugLog.LogSigning(this, macAlg); MSignature.SetSignatureValue(new byte[signatureLength / 8]); Buffer.BlockCopy(hashValue, 0, MSignature.GetSignatureValue(), 0, signatureLength / 8); }
public void ComputeSignature(IMac macAlg) { if (macAlg == null) { throw new ArgumentNullException("macAlg"); } if (!(macAlg is HMac)) { throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_SignatureMethodKeyMismatch); } int signatureLength; if (m_signature.SignedInfo.SignatureLength == null) { signatureLength = macAlg.GetMacSize() * 8; } else { signatureLength = Convert.ToInt32(m_signature.SignedInfo.SignatureLength, null); } // signatureLength should be less than hash size if (signatureLength < 0 || signatureLength > macAlg.GetMacSize() * 8) { throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength); } if (signatureLength % 8 != 0) { throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength2); } BuildDigestedReferences(); switch (macAlg.AlgorithmName.Substring(0, macAlg.AlgorithmName.IndexOf('/')).ToUpperInvariant()) { case "SHA-1": SignedInfo.SignatureMethod = SignedXml.XmlDsigHMACSHA1Url; break; case "SHA-256": SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACSHA256Url; break; case "SHA-384": SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACSHA384Url; break; case "SHA-512": SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACSHA512Url; break; case "MD5": SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACMD5Url; break; case "RIPEMD160": SignedInfo.SignatureMethod = SignedXml.XmlDsigMoreHMACRIPEMD160Url; break; default: throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_SignatureMethodKeyMismatch); } GetC14NDigest(new MacHashWrapper(macAlg)); byte[] hashValue = new byte[macAlg.GetMacSize()]; macAlg.DoFinal(hashValue, 0); SignedXmlDebugLog.LogSigning(this, macAlg); m_signature.SignatureValue = new byte[signatureLength / 8]; Buffer.BlockCopy(hashValue, 0, m_signature.SignatureValue, 0, signatureLength / 8); }
private byte[] DecryptBlock( byte[] in_enc, int inOff, int inLen, byte[] z) { byte[] M = null; KeyParameter macKey = null; KdfParameters kParam = new KdfParameters(z, param.GetDerivationV()); int macKeySize = param.MacKeySize; kdf.Init(kParam); inLen -= mac.GetMacSize(); if (cipher == null) // stream mode { byte[] Buffer = GenerateKdfBytes(kParam, inLen + (macKeySize / 8)); M = new byte[inLen]; for (int i = 0; i != inLen; i++) { M[i] = (byte)(in_enc[inOff + i] ^ Buffer[i]); } macKey = new KeyParameter(Buffer, inLen, (macKeySize / 8)); } else { int cipherKeySize = ((IesWithCipherParameters)param).CipherKeySize; byte[] Buffer = GenerateKdfBytes(kParam, (cipherKeySize / 8) + (macKeySize / 8)); cipher.Init(false, new KeyParameter(Buffer, 0, (cipherKeySize / 8))); // byte[] tmp = new byte[cipher.GetOutputSize(inLen)]; // int len = cipher.ProcessBytes(in_enc, inOff, inLen, tmp, 0); // len += cipher.DoFinal(tmp, len); // M = new byte[len]; // Array.Copy(tmp, 0, M, 0, len); M = cipher.DoFinal(in_enc, inOff, inLen); macKey = new KeyParameter(Buffer, (cipherKeySize / 8), (macKeySize / 8)); } byte[] macIV = param.GetEncodingV(); mac.Init(macKey); mac.BlockUpdate(in_enc, inOff, inLen); mac.BlockUpdate(macIV, 0, macIV.Length); mac.DoFinal(macBuf, 0); inOff += inLen; for (int t = 0; t < macBuf.Length; t++) { if (macBuf[t] != in_enc[inOff + t]) { throw (new InvalidCipherTextException("IMac codes failed to equal.")); } } return(M); }
public static byte[] DoFinal(IMac mac) { byte[] output = new byte[mac.GetMacSize()]; mac.DoFinal(output, 0); return(output); }
internal static byte[] DoFinal(IMac mac) { byte[] result = new byte[mac.GetMacSize()]; mac.DoFinal(result, 0); return(result); }
/** * Compute the pseudorandom k for signature generation, * using the process specified for deterministic DSA. * * @param h1 the hashed message * @return the pseudorandom k to use */ private BigInteger computek(byte[] h1) { /* * Convert hash value into an appropriately truncated * and/or expanded sequence of octets. The private * key was already processed (into field bx[]). */ byte[] bh = bits2octets(h1); /* * HMAC is always used with K as key. * Whenever K is updated, we reset the * current HMAC key. */ /* step b. */ byte[] V = new byte[holen]; for (int i = 0; i < holen; i++) { V[i] = 0x01; } /* step c. */ byte[] K = new byte[holen]; setHmacKey(K); /* step d. */ hmac.Update(V); hmac.Update((byte)0x00); hmac.Update(bx); hmac.Update(bh); K = hmac.DoFinal(); setHmacKey(K); /* step e. */ hmac.Update(V); V = hmac.DoFinal(); /* step f. */ hmac.Update(V); hmac.Update((byte)0x01); hmac.Update(bx); hmac.Update(bh); K = hmac.DoFinal(); setHmacKey(K); /* step g. */ hmac.Update(V); V = hmac.DoFinal(); /* step h. */ byte[] T = new byte[rolen]; for ( ; ;) { /* * We want qlen bits, but we support only * hash functions with an output length * multiple of 8;acd hence, we will gather * rlen bits, i.e., rolen octets. */ int toff = 0; while (toff < rolen) { hmac.Update(V); V = hmac.DoFinal(); int cc = Math.Min(V.Length, T.Length - toff); Array.Copy(V, 0, T, toff, cc); toff += cc; } BigInteger k = bits2int(T); if (k.SignValue > 0 && k.CompareTo(q) < 0) { return(k); } /* * k is not in the proper range; update * K and V, and loop. */ hmac.Update(V); hmac.Update((byte)0x00); K = hmac.DoFinal(); setHmacKey(K); hmac.Update(V); V = hmac.DoFinal(); } }
private byte[] DecryptBlock( byte[] in_enc, int inOff, int inLen, byte[] z) { byte[] M = null; KeyParameter macKey = null; KdfParameters kParam = new KdfParameters(z, param.GetDerivationV()); int macKeySize = param.MacKeySize; kdf.Init(kParam); // Ensure that the length of the input is greater than the MAC in bytes if (inLen < mac.GetMacSize()) { throw new InvalidCipherTextException("Length of input must be greater than the MAC"); } inLen -= mac.GetMacSize(); if (cipher == null) // stream mode { byte[] Buffer = GenerateKdfBytes(kParam, inLen + (macKeySize / 8)); M = new byte[inLen]; for (int i = 0; i != inLen; i++) { M[i] = (byte)(in_enc[inOff + i] ^ Buffer[i]); } macKey = new KeyParameter(Buffer, inLen, (macKeySize / 8)); } else { int cipherKeySize = ((IesWithCipherParameters)param).CipherKeySize; byte[] Buffer = GenerateKdfBytes(kParam, (cipherKeySize / 8) + (macKeySize / 8)); cipher.Init(false, new KeyParameter(Buffer, 0, (cipherKeySize / 8))); M = cipher.DoFinal(in_enc, inOff, inLen); macKey = new KeyParameter(Buffer, (cipherKeySize / 8), (macKeySize / 8)); } byte[] macIV = param.GetEncodingV(); mac.Init(macKey); mac.BlockUpdate(in_enc, inOff, inLen); mac.BlockUpdate(macIV, 0, macIV.Length); mac.DoFinal(macBuf, 0); inOff += inLen; byte[] T1 = Arrays.CopyOfRange(in_enc, inOff, inOff + macBuf.Length); if (!Arrays.ConstantTimeAreEqual(T1, macBuf)) { throw (new InvalidCipherTextException("Invalid MAC.")); } return(M); }
/// <summary> /// Gets a validation function that returns the output of a configured verification method. /// Input: <c>tag || salt || AD || message</c> /// </summary> /// <returns>Callable validation function.</returns> /// <param name="keyConfirmation">Key confirmation configuration defining validation method to be employed.</param> /// <param name="tag"></param> /// <param name="message"></param> /// <param name="outputSizeBytes">Expected length of output of verification function in bytes.</param> /// <exception cref="ConfigurationInvalidException"> /// Some aspect of configuration invalid - detailed inside exception message. /// </exception> internal static Func <byte[], byte[]> GetValidator(IAuthenticationConfiguration keyConfirmation, byte[] tag, byte[] message, int?outputSizeBytes = null) { AuthenticationFunctionType functionType = keyConfirmation.FunctionType; if (functionType == AuthenticationFunctionType.None) { throw new ConfigurationInvalidException("Authentication function type cannot be None."); } if (String.IsNullOrEmpty(keyConfirmation.FunctionName)) { throw new ConfigurationInvalidException("Authentication function name cannot be null or empty."); } const string lengthIncompatibleString = "Expected length incompatible with function specified."; Func <byte[], byte[]> validator; // Used as an adaptor between different validation methods switch (functionType) { case AuthenticationFunctionType.Kdf: { if (outputSizeBytes == null) { throw new ArgumentNullException("outputSizeBytes", "Cannot be null if KDF is being used."); } KeyDerivationFunction kdfEnum; try { kdfEnum = keyConfirmation.FunctionName.ToEnum <KeyDerivationFunction>(); } catch (EnumerationParsingException ex) { throw new ConfigurationInvalidException("Key derivation function is unsupported/unknown.", ex); } validator = key => { int superSaltSize = keyConfirmation.Salt.Length + (keyConfirmation.AdditionalData != null ? keyConfirmation.AdditionalData.Length : 0) + (tag != null ? tag.Length : 0) + (message != null ? message.Length : 0); var superSalt = new byte[superSaltSize]; tag.DeepCopy_NoChecks(0, superSalt, 0, tag.Length); int index = tag.Length; // Compose the rest of the input to the KDF (as a super-salt) if (keyConfirmation.Salt.IsNullOrZeroLength() == false) { keyConfirmation.Salt.DeepCopy_NoChecks(0, superSalt, index, keyConfirmation.Salt.Length); index += keyConfirmation.Salt.Length; } if (keyConfirmation.AdditionalData.IsNullOrZeroLength() == false) { keyConfirmation.AdditionalData.DeepCopy_NoChecks(0, superSalt, index, keyConfirmation.AdditionalData.Length); index += keyConfirmation.AdditionalData.Length; } if (message.IsNullOrZeroLength() == false) { message.DeepCopy_NoChecks(0, superSalt, index, message.Length); } return(KdfFactory.DeriveKeyWithKdf(kdfEnum, key, superSalt, outputSizeBytes.Value, keyConfirmation.FunctionConfiguration)); }; break; } case AuthenticationFunctionType.Mac: MacFunction macFEnum; try { macFEnum = keyConfirmation.FunctionName.ToEnum <MacFunction>(); } catch (EnumerationParsingException ex) { throw new ConfigurationInvalidException("MAC function is unsupported/unknown.", ex); } validator = key => { IMac macF = AuthenticatorFactory.CreateMacPrimitive(macFEnum, key, tag, keyConfirmation.FunctionConfiguration, keyConfirmation.Nonce); if (outputSizeBytes != null && outputSizeBytes != macF.OutputSize) { throw new ArgumentException(lengthIncompatibleString, "outputSizeBytes"); } if (keyConfirmation.Salt.IsNullOrZeroLength() == false) { macF.BlockUpdate(keyConfirmation.Salt, 0, keyConfirmation.Salt.Length); } if (keyConfirmation.AdditionalData.IsNullOrZeroLength() == false) { macF.BlockUpdate(keyConfirmation.AdditionalData, 0, keyConfirmation.AdditionalData.Length); } if (message.IsNullOrZeroLength() == false) { macF.BlockUpdate(message, 0, message.Length); } var output = new byte[macF.OutputSize]; macF.DoFinal(output, 0); return(output); }; break; default: throw new NotSupportedException("Function type not supported for key confirmation."); } return(validator); }
public int DoFinal(byte[] output, int outOff) { return(_hash.DoFinal(output, outOff)); }
public static byte[] DoFinal(IMac mac) { byte[] array = new byte[mac.GetMacSize()]; mac.DoFinal(array, 0); return array; }
public byte[] Collect() { byte[] res = new byte[mac.GetMacSize()]; mac.DoFinal(res, 0); return(res); }
public static int DoFinalOut(IMac mac, byte[] outBuffer) { mac.DoFinal(outBuffer, 0); return(mac.GetMacSize()); }
public static byte[] DoFinal(this IMac hmac) { byte[] result = new byte[hmac.GetMacSize()]; hmac.DoFinal(result, 0); return(result); }
void ComputeHmac(byte[] input, byte[] output) { _hmacAlgorithm.Reset(); _hmacAlgorithm.BlockUpdate(input, 0, input.Length); _hmacAlgorithm.DoFinal(output, 0); }