public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo( string algorithm, char[] passPhrase, byte[] salt, int iterationCount, PrivateKeyInfo keyInfo) { if (!PbeUtilities.IsPbeAlgorithm(algorithm)) { throw new ArgumentException("attempt to use non-PBE algorithm with PBE EncryptedPrivateKeyInfo generation"); } IBufferedCipher cipher = PbeUtilities.CreateEngine(algorithm) as IBufferedCipher; if (cipher == null) { // TODO Throw exception? } Asn1Encodable parameters = PbeUtilities.GenerateAlgorithmParameters( algorithm, salt, iterationCount); ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters( algorithm, passPhrase, parameters); cipher.Init(true, keyParameters); byte[] keyBytes = keyInfo.GetEncoded(); byte[] encoding = cipher.DoFinal(keyBytes); DerObjectIdentifier oid = PbeUtilities.GetObjectIdentifier(algorithm); AlgorithmIdentifier algID = new AlgorithmIdentifier(oid, parameters); return(new EncryptedPrivateKeyInfo(algID, encoding)); }
AsymmetricKeyParameter DecryptAsymmetricKeyParameter(byte[] buffer, int length) { using (var memory = new MemoryStream(buffer, 0, length, false)) { using (var asn1 = new Asn1InputStream(memory)) { var sequence = asn1.ReadObject() as Asn1Sequence; if (sequence == null) { return(null); } var encrypted = EncryptedPrivateKeyInfo.GetInstance(sequence); var algorithm = encrypted.EncryptionAlgorithm; var encoded = encrypted.GetEncryptedData(); var cipher = PbeUtilities.CreateEngine(algorithm) as IBufferedCipher; if (cipher == null) { return(null); } var cipherParameters = PbeUtilities.GenerateCipherParameters(algorithm, passwd); cipher.Init(false, cipherParameters); var decrypted = cipher.DoFinal(encoded); var keyInfo = PrivateKeyInfo.GetInstance(decrypted); return(PrivateKeyFactory.CreateKey(keyInfo)); } } }
private static byte[] CryptPbeData( bool forEncryption, AlgorithmIdentifier algId, char[] password, bool wrongPkcs12Zero, byte[] data) { IBufferedCipher cipher = PbeUtilities.CreateEngine(algId) as IBufferedCipher; if (cipher == null) { throw new Exception("Unknown encryption algorithm: " + algId.Algorithm); } if (algId.Algorithm.Equals(PkcsObjectIdentifiers.IdPbeS2)) { PbeS2Parameters pbeParameters = PbeS2Parameters.GetInstance(algId.Parameters); ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters( algId.Algorithm, password, pbeParameters); cipher.Init(forEncryption, cipherParams); return(cipher.DoFinal(data)); } else { Pkcs12PbeParams pbeParameters = Pkcs12PbeParams.GetInstance(algId.Parameters); ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters( algId.Algorithm, password, wrongPkcs12Zero, pbeParameters); cipher.Init(forEncryption, cipherParams); return(cipher.DoFinal(data)); } }
public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo( DerObjectIdentifier cipherAlgorithm, DerObjectIdentifier prfAlgorithm, char[] passPhrase, byte[] salt, int iterationCount, SecureRandom random, PrivateKeyInfo keyInfo) { IBufferedCipher cipher = CipherUtilities.GetCipher(cipherAlgorithm) as IBufferedCipher; if (cipher == null) { throw new Exception("Unknown encryption algorithm: " + cipherAlgorithm); } Asn1Encodable pbeParameters = PbeUtilities.GenerateAlgorithmParameters( cipherAlgorithm, prfAlgorithm, salt, iterationCount, random); ICipherParameters cipherParameters = PbeUtilities.GenerateCipherParameters( PkcsObjectIdentifiers.IdPbeS2, passPhrase, pbeParameters); cipher.Init(true, cipherParameters); byte[] encoding = cipher.DoFinal(keyInfo.GetEncoded()); AlgorithmIdentifier algID = new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPbeS2, pbeParameters); return(new EncryptedPrivateKeyInfo(algID, encoding)); }
public override void PerformTest() { byte[] salt = new byte[16]; int iCount = 100; for (int i = 0; i != salt.Length; i++) { salt[i] = (byte)i; } PbeParametersGenerator pGen = new OpenSslPbeParametersGenerator(); pGen.Init( PbeParametersGenerator.Pkcs5PasswordToBytes(password), salt, iCount); ParametersWithIV parameters = (ParametersWithIV) pGen.GenerateDerivedParameters(baseAlgorithm, keySize, ivSize); KeyParameter encKey = (KeyParameter)parameters.Parameters; IBufferedCipher c; if (baseAlgorithm.Equals("RC4")) { c = CipherUtilities.GetCipher(baseAlgorithm); c.Init(true, encKey); } else { c = CipherUtilities.GetCipher(baseAlgorithm + "/CBC/PKCS7Padding"); c.Init(true, parameters); } byte[] enc = c.DoFinal(salt); c = CipherUtilities.GetCipher(algorithm); // PBEKeySpec keySpec = new PBEKeySpec(password, salt, iCount); // SecretKeyFactory fact = SecretKeyFactory.getInstance(algorithm); // // c.Init(false, fact.generateSecret(keySpec)); Asn1Encodable algParams = PbeUtilities.GenerateAlgorithmParameters( algorithm, salt, iCount); ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters( algorithm, password, algParams); c.Init(false, cipherParams); byte[] dec = c.DoFinal(enc); if (!AreEqual(salt, dec)) { Fail("" + algorithm + "failed encryption/decryption test"); } }
public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo( string algorithm, char[] passPhrase, byte[] salt, int iterationCount, PrivateKeyInfo keyInfo) { IBufferedCipher cipher = PbeUtilities.CreateEngine(algorithm) as IBufferedCipher; if (cipher == null) { throw new Exception("Unknown encryption algorithm: " + algorithm); } Asn1Encodable pbeParameters = PbeUtilities.GenerateAlgorithmParameters( algorithm, salt, iterationCount); ICipherParameters cipherParameters = PbeUtilities.GenerateCipherParameters( algorithm, passPhrase, pbeParameters); cipher.Init(true, cipherParameters); byte[] encoding = cipher.DoFinal(keyInfo.GetEncoded()); DerObjectIdentifier oid = PbeUtilities.GetObjectIdentifier(algorithm); AlgorithmIdentifier algID = new AlgorithmIdentifier(oid, pbeParameters); return(new EncryptedPrivateKeyInfo(algID, encoding)); }
byte[] EncryptAsymmetricKeyParameter(AsymmetricKeyParameter key) { var cipher = PbeUtilities.CreateEngine(EncryptionAlgorithm.Id) as IBufferedCipher; var keyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(key); var random = new SecureRandom(); var salt = new byte[SaltSize]; if (cipher == null) { throw new Exception("Unknown encryption algorithm: " + EncryptionAlgorithm.Id); } random.NextBytes(salt); var pbeParameters = PbeUtilities.GenerateAlgorithmParameters(EncryptionAlgorithm.Id, salt, MinIterations); var algorithm = new AlgorithmIdentifier(EncryptionAlgorithm, pbeParameters); var cipherParameters = PbeUtilities.GenerateCipherParameters(algorithm, passwd); if (cipherParameters == null) { throw new Exception("BouncyCastle bug detected: Failed to generate cipher parameters."); } cipher.Init(true, cipherParameters); var encoded = cipher.DoFinal(keyInfo.GetEncoded()); var encrypted = new EncryptedPrivateKeyInfo(algorithm, encoded); return(encrypted.GetEncoded()); }
internal static byte[] CalculatePbeMac(DerObjectIdentifier oid, byte[] salt, int itCount, char[] password, bool wrongPkcs12Zero, byte[] data) { Asn1Encodable pbeParameters = PbeUtilities.GenerateAlgorithmParameters(oid, salt, itCount); ICipherParameters parameters = PbeUtilities.GenerateCipherParameters(oid, password, wrongPkcs12Zero, pbeParameters); IMac mac = (IMac)PbeUtilities.CreateEngine(oid); mac.Init(parameters); return(MacUtilities.DoFinal(mac, data)); }
internal static byte[] CalculatePbeMac(DerObjectIdentifier oid, byte[] salt, int itCount, char[] password, bool wrongPkcs12Zero, byte[] data) { Asn1Encodable asn1Params = PbeUtilities.GenerateAlgorithmParameters(oid, salt, itCount); ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters(oid, password, wrongPkcs12Zero, asn1Params); var mac = (IMac)PbeUtilities.CreateEngine(oid); mac.Init(cipherParams); mac.BlockUpdate(data, 0, data.Length); return(MacUtilities.DoFinal(mac)); }
private void doTestPbeHMac( string hmacName, byte[] output) { ICipherParameters key = null; byte[] outBytes; IMac mac = null; try { // SecretKeyFactory fact = SecretKeyFactory.getInstance(hmacName); // // key = fact.generateSecret(new PBEKeySpec("hello".ToCharArray())); Asn1Encodable algParams = PbeUtilities.GenerateAlgorithmParameters( hmacName, new byte[20], 100); key = PbeUtilities.GenerateCipherParameters( hmacName, "hello".ToCharArray(), algParams); mac = MacUtilities.GetMac(hmacName); } catch (Exception e) { Fail("Failed - exception " + e.ToString(), e); } try { // mac.Init(key, new PBEParameterSpec(new byte[20], 100)); mac.Init(key); } catch (Exception e) { Fail("Failed - exception " + e.ToString(), e); } mac.Reset(); mac.BlockUpdate(message, 0, message.Length); // outBytes = mac.DoFinal(); outBytes = new byte[mac.GetMacSize()]; mac.DoFinal(outBytes, 0); if (!AreEqual(outBytes, output)) { Fail("Failed - expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } }
private static byte[] CryptPbeData(bool forEncryption, AlgorithmIdentifier algId, char[] password, bool wrongPkcs12Zero, byte[] data) { IBufferedCipher bufferedCipher = PbeUtilities.CreateEngine(algId.ObjectID) as IBufferedCipher; if (bufferedCipher == null) { throw new Exception("Unknown encryption algorithm: " + algId.ObjectID); } Pkcs12PbeParams instance = Pkcs12PbeParams.GetInstance(algId.Parameters); ICipherParameters parameters = PbeUtilities.GenerateCipherParameters(algId.ObjectID, password, wrongPkcs12Zero, instance); bufferedCipher.Init(forEncryption, parameters); return(bufferedCipher.DoFinal(data)); }
public static PrivateKeyInfo CreatePrivateKeyInfo(char[] passPhrase, bool wrongPkcs12Zero, EncryptedPrivateKeyInfo encInfo) { AlgorithmIdentifier encryptionAlgorithm = encInfo.EncryptionAlgorithm; IBufferedCipher bufferedCipher = PbeUtilities.CreateEngine(encryptionAlgorithm) as IBufferedCipher; if (bufferedCipher == null) { throw new global::System.Exception(string.Concat((object)"Unknown encryption algorithm: ", (object)encryptionAlgorithm.Algorithm)); } ICipherParameters parameters = PbeUtilities.GenerateCipherParameters(encryptionAlgorithm, passPhrase, wrongPkcs12Zero); bufferedCipher.Init(forEncryption: false, parameters); byte[] obj = bufferedCipher.DoFinal(encInfo.GetEncryptedData()); return(PrivateKeyInfo.GetInstance(obj)); }
//public static byte[] Decrypt2(this byte[] cmessage,string password, byte[] salt) //{ // int KEY_SIZE = 256; // int iterations = 100; // //byte[] salt = new byte[KEY_SIZE >> 3]; // IBufferedCipher decCipher = BuildDecryptionCipher(password, iterations, salt); // return DecryptTemp(decCipher, cmessage); //} private static IBufferedCipher BuildDecryptionCipher(string password, int iterations, byte[] salt) { string DECRYPTION_ALGORITHM = "PBEWithSHA256And256BitAES-CBC-BC"; // get the password bytes char[] passwordChars = password.ToCharArray(); IBufferedCipher cipher = CipherUtilities.GetCipher(DECRYPTION_ALGORITHM); Org.BouncyCastle.Asn1.Asn1Encodable algParams = PbeUtilities.GenerateAlgorithmParameters(DECRYPTION_ALGORITHM, salt, iterations); ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters(DECRYPTION_ALGORITHM, passwordChars, algParams); cipher.Init(false, cipherParams); return(cipher); }
public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo(string algorithm, char[] passPhrase, byte[] salt, int iterationCount, PrivateKeyInfo keyInfo) { IBufferedCipher bufferedCipher = PbeUtilities.CreateEngine(algorithm) as IBufferedCipher; if (bufferedCipher == null) { throw new global::System.Exception("Unknown encryption algorithm: " + algorithm); } Asn1Encodable asn1Encodable = PbeUtilities.GenerateAlgorithmParameters(algorithm, salt, iterationCount); ICipherParameters parameters = PbeUtilities.GenerateCipherParameters(algorithm, passPhrase, asn1Encodable); bufferedCipher.Init(forEncryption: true, parameters); byte[] encoding = bufferedCipher.DoFinal(keyInfo.GetEncoded()); DerObjectIdentifier objectIdentifier = PbeUtilities.GetObjectIdentifier(algorithm); AlgorithmIdentifier algId = new AlgorithmIdentifier(objectIdentifier, asn1Encodable); return(new EncryptedPrivateKeyInfo(algId, encoding)); }
internal byte[] EncryptData( AlgorithmIdentifier algId, byte[] data, char[] password) { Pkcs12PbeParams pbeParams = Pkcs12PbeParams.GetInstance(algId.Parameters); ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters( algId.ObjectID, password, pbeParams); IBufferedCipher cipher = PbeUtilities.CreateEngine(algId.ObjectID) as IBufferedCipher; if (cipher == null) { // TODO Throw exception? } cipher.Init(true, keyParameters); return(cipher.DoFinal(data)); }
public static PrivateKeyInfo CreatePrivateKeyInfo( char[] passPhrase, bool wrongPkcs12Zero, EncryptedPrivateKeyInfo encInfo) { AlgorithmIdentifier algID = encInfo.EncryptionAlgorithm; IBufferedCipher cipher = PbeUtilities.CreateEngine(algID) as IBufferedCipher; if (cipher == null) { throw new Exception("Unknown encryption algorithm: " + algID.Algorithm); } ICipherParameters cipherParameters = PbeUtilities.GenerateCipherParameters( algID, passPhrase, wrongPkcs12Zero); cipher.Init(false, cipherParameters); byte[] keyBytes = cipher.DoFinal(encInfo.GetEncryptedData()); return(PrivateKeyInfo.GetInstance(keyBytes)); }
// NB: These two makePbeCipher... methods are same in .NET private IBufferedCipher makePbeCipherWithoutParam( string algorithm, bool forEncryption, char[] password, byte[] salt, int iterationCount) { // PBEKeySpec pbeSpec = new PBEKeySpec(password, salt, iterationCount); // SecretKeyFactory keyFact = SecretKeyFactory.getInstance(algorithm); Asn1Encodable algParams = PbeUtilities.GenerateAlgorithmParameters( algorithm, salt, iterationCount); ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters( algorithm, password, algParams); IBufferedCipher cipher = CipherUtilities.GetCipher(algorithm); // cipher.Init(forEncryption, keyFact.generateSecret(pbeSpec)); cipher.Init(forEncryption, cipherParams); return(cipher); }
internal Asn1Sequence DecryptData( AlgorithmIdentifier algId, byte[] data, char[] password, bool wrongPkcs12Zero) { Pkcs12PbeParams pbeParams = Pkcs12PbeParams.GetInstance(algId.Parameters); ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters( algId.ObjectID, password, wrongPkcs12Zero, pbeParams); IBufferedCipher cipher = PbeUtilities.CreateEngine(algId.ObjectID) as IBufferedCipher; if (cipher == null) { // TODO Throw exception? } cipher.Init(false, keyParameters); byte[] encoding = cipher.DoFinal(data); return((Asn1Sequence)Asn1Object.FromByteArray(encoding)); }
public static PrivateKeyInfo CreatePrivateKeyInfo( char[] passPhrase, bool wrongPkcs12Zero, EncryptedPrivateKeyInfo encInfo) { AlgorithmIdentifier algID = encInfo.EncryptionAlgorithm; IBufferedCipher cipher = PbeUtilities.CreateEngine(algID) as IBufferedCipher; if (cipher == null) { // TODO Throw exception? } ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters( algID, passPhrase, wrongPkcs12Zero); cipher.Init(false, keyParameters); byte[] keyBytes = encInfo.GetEncryptedData(); byte[] encoding = cipher.DoFinal(keyBytes); Asn1Object asn1Data = Asn1Object.FromByteArray(encoding); return(PrivateKeyInfo.GetInstance(asn1Data)); }
private const string alg = "1.2.840.113549.1.12.1.3"; // 3 key triple DES with SHA-1 public override void PerformTest() { IAsymmetricCipherKeyPairGenerator fact = GeneratorUtilities.GetKeyPairGenerator("RSA"); fact.Init(new KeyGenerationParameters(new SecureRandom(), 512)); AsymmetricCipherKeyPair keyPair = fact.GenerateKeyPair(); AsymmetricKeyParameter priKey = keyPair.Private; AsymmetricKeyParameter pubKey = keyPair.Public; // // set up the parameters // byte[] salt = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int iterationCount = 100; Asn1Encodable defParams = PbeUtilities.GenerateAlgorithmParameters(alg, salt, iterationCount); char[] password1 = { 'h', 'e', 'l', 'l', 'o' }; // AlgorithmParameters parameters = AlgorithmParameters.getInstance(alg); // // parameters.init(defParams); // // set up the key // // PBEKeySpec pbeSpec = new PBEKeySpec(password1); // SecretKeyFactory keyFact = SecretKeyFactory.getInstance(alg); // IBufferedCipher cipher = CipherUtilities.GetCipher(alg); IWrapper wrapper = WrapperUtilities.GetWrapper(alg); ICipherParameters parameters = PbeUtilities.GenerateCipherParameters( alg, password1, defParams); // cipher.Init(IBufferedCipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), parameters); wrapper.Init(true, parameters); // byte[] wrappedKey = cipher.Wrap(priKey); byte[] pkb = PrivateKeyInfoFactory.CreatePrivateKeyInfo(priKey).GetDerEncoded(); byte[] wrappedKey = wrapper.Wrap(pkb, 0, pkb.Length); // // create encrypted object // // TODO Figure out what this was supposed to do // EncryptedPrivateKeyInfo pInfo = new EncryptedPrivateKeyInfo(parameters, wrappedKey); PrivateKeyInfo plain = PrivateKeyInfoFactory.CreatePrivateKeyInfo(priKey); EncryptedPrivateKeyInfo pInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo( alg, password1, salt, iterationCount, plain); // // decryption step // char[] password2 = { 'h', 'e', 'l', 'l', 'o' }; // pbeSpec = new PBEKeySpec(password2); // // cipher = CipherUtilities.GetCipher(pInfo.EncryptionAlgorithm); // // cipher.Init(false, keyFact.generateSecret(pbeSpec), pInfo.getAlgParameters()); // // PKCS8EncodedKeySpec keySpec = pInfo.getKeySpec(cipher); PrivateKeyInfo decrypted = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password2, pInfo); // if (!MessageDigest.isEqual(priKey.GetEncoded(), keySpec.GetEncoded())) if (!decrypted.Equals(plain)) { Fail("Private key does not match"); } // // using ICipherParameters test // // pbeSpec = new PBEKeySpec(password1); // keyFact = SecretKeyFactory.getInstance(alg); // cipher = CipherUtilities.GetCipher(alg); wrapper = WrapperUtilities.GetWrapper(alg); // cipher.init(IBufferedCipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), parameters); wrapper.Init(true, parameters); // wrappedKey = cipher.wrap(priKey); wrappedKey = wrapper.Wrap(pkb, 0, pkb.Length); // // create encrypted object // // TODO Figure out what this was supposed to do // pInfo = new EncryptedPrivateKeyInfo(cipher.getParameters(), wrappedKey); plain = PrivateKeyInfoFactory.CreatePrivateKeyInfo(priKey); pInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo( alg, password1, salt, iterationCount, plain); // // decryption step // // pbeSpec = new PBEKeySpec(password2); // // cipher = CipherUtilities.GetCipher(pInfo.getAlgName()); // // cipher.init(IBufferedCipher.DECRYPT_MODE, keyFact.generateSecret(pbeSpec), pInfo.getAlgParameters()); // // keySpec = pInfo.getKeySpec(cipher); decrypted = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password2, pInfo); // if (!MessageDigest.isEqual(priKey.GetEncoded(), keySpec.GetEncoded())) if (!decrypted.Equals(plain)) { Fail("Private key does not match"); } }
public static void Save(this Pkcs12Store store, Stream stream, string encryptionPassword, string integrityPassword, SecureRandom random) { const int saltSize = 20; const int minIterations = 1024; if (stream == null) { throw new ArgumentNullException("stream"); } //if (null != encryptionPassword && encryptionPassword == integrityPassword) //{ // store.Save(stream, encryptionPassword.ToArray(), random); // return; //} if (random == null) { throw new ArgumentNullException("random"); } var T = store.GetType(); Func <AsymmetricKeyParameter, SubjectKeyIdentifier> CreateSubjectKeyID = (pubKey_) => { var method = T.GetMethod("CreateSubjectKeyID", BindingFlags.NonPublic | BindingFlags.Static); return((SubjectKeyIdentifier)method.Invoke(store, new object[] { pubKey_ })); }; Func <DerObjectIdentifier> keyAlgorithm = () => { var property = T.GetField("keyAlgorithm", BindingFlags.NonPublic | BindingFlags.Instance); return((DerObjectIdentifier)property.GetValue(store)); }; Func <DerObjectIdentifier> certAlgorithm = () => { var property = T.GetField("certAlgorithm", BindingFlags.NonPublic | BindingFlags.Instance); return((DerObjectIdentifier)property.GetValue(store)); }; // // handle the key // Asn1EncodableVector keyS = new Asn1EncodableVector(); var keys = store.Aliases.OfType <string>().ToDictionary(alias => alias, store.GetKey); foreach (string name in store.Aliases.OfType <string>()) { byte[] kSalt = new byte[saltSize]; random.NextBytes(kSalt); AsymmetricKeyEntry privKey = keys[name]; Asn1Encodable kInfo = null; if (!string.IsNullOrEmpty(encryptionPassword)) { kInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(keyAlgorithm(), encryptionPassword.ToArray(), kSalt, minIterations, privKey.Key); } else { kInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey.Key); } Asn1EncodableVector kName = new Asn1EncodableVector(); foreach (string oid in privKey.BagAttributeKeys) { Asn1Encodable entry = privKey[oid]; // NB: Ignore any existing FriendlyName if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) { continue; } kName.Add(new DerSequence(new DerObjectIdentifier(oid), new DerSet(entry))); } // // make sure we are using the local alias on store // // NB: We always set the FriendlyName based on 'name' //if (privKey[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null) { kName.Add(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(name)))); } // // make sure we have a local key-id // if (privKey[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null) { X509CertificateEntry ct = store.GetCertificate(name); AsymmetricKeyParameter pubKey = ct.Certificate.GetPublicKey(); SubjectKeyIdentifier subjectKeyID = CreateSubjectKeyID(pubKey); kName.Add(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID, new DerSet(subjectKeyID))); } SafeBag kBag = null; if (!string.IsNullOrEmpty(encryptionPassword)) { kBag = new SafeBag(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag, kInfo.ToAsn1Object(), new DerSet(kName)); } else { kBag = new SafeBag(PkcsObjectIdentifiers.KeyBag, 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()); ISet doneCerts = new HashSet(); foreach (string name in keys.Keys) { X509CertificateEntry certEntry = store.GetCertificate(name); CertBag cBag = new CertBag(PkcsObjectIdentifiers.X509Certificate, new DerOctetString(certEntry.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in certEntry.BagAttributeKeys) { Asn1Encodable entry = certEntry[oid]; // NB: Ignore any existing FriendlyName if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) { continue; } fName.Add(new DerSequence(new DerObjectIdentifier(oid), new DerSet(entry))); } // // make sure we are using the local alias on store // // NB: We always set the FriendlyName based on 'name' //if (certEntry[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null) { fName.Add(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(name)))); } // // make sure we have a local key-id // if (certEntry[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null) { AsymmetricKeyParameter pubKey = certEntry.Certificate.GetPublicKey(); SubjectKeyIdentifier subjectKeyID = CreateSubjectKeyID(pubKey); fName.Add(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID, new DerSet(subjectKeyID))); } SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); doneCerts.Add(certEntry.Certificate); } var certs = store.Aliases.OfType <string>().Select(store.GetCertificate); foreach (var cert in certs) { //X509CertificateEntry cert = (X509CertificateEntry)certs[certId]; //if (keys[certId] != null) // continue; if (doneCerts.Contains(cert.Certificate)) { continue; } CertBag cBag = new CertBag(PkcsObjectIdentifiers.X509Certificate, new DerOctetString(cert.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in cert.BagAttributeKeys) { // a certificate not immediately linked to a key doesn't require // a localKeyID and will confuse some PKCS12 implementations. // // If we find one, we'll prune it out. if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id)) { continue; } Asn1Encodable entry = cert[oid]; // NB: Ignore any existing FriendlyName if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) { continue; } fName.Add(new DerSequence(new DerObjectIdentifier(oid), new DerSet(entry))); } // // make sure we are using the local alias on store // // NB: We always set the FriendlyName based on 'certId' //if (cert[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null) { //fName.Add(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(certId)))); fName.Add(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(CreateSubjectKeyID(cert.Certificate.GetPublicKey()).GetKeyIdentifier())))); } SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); doneCerts.Add(cert.Certificate); } var chainCerts = store.Aliases.OfType <string>().Select(store.GetCertificateChain).Aggregate <IEnumerable <X509CertificateEntry>, IEnumerable <X509CertificateEntry> >(new List <X509CertificateEntry>(), (list, entries) => list.Union(entries)); foreach (var cert in chainCerts) { //X509CertificateEntry cert = (X509CertificateEntry)chainCerts[certId]; if (doneCerts.Contains(cert.Certificate)) { continue; } CertBag cBag = new CertBag(PkcsObjectIdentifiers.X509Certificate, new DerOctetString(cert.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in cert.BagAttributeKeys) { // a certificate not immediately linked to a key doesn't require // a localKeyID and will confuse some PKCS12 implementations. // // If we find one, we'll prune it out. if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id)) { continue; } 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(); Func <bool, AlgorithmIdentifier, char[], bool, byte[], byte[]> CryptPbeData = (forEncryption_, algId_, password_, wrongPkcs12Zero_, data_) => { var method = T.GetMethod("CryptPbeData", BindingFlags.NonPublic | BindingFlags.Static); return((byte[])method.Invoke(store, new object[] { forEncryption_, algId_, password_, wrongPkcs12Zero_, data_ })); }; ContentInfo[] info = null; if (null != encryptionPassword) { byte[] certBytes = CryptPbeData(true, cAlgId, encryptionPassword.ToArray(), false, derEncodedBytes); var cInfo = new EncryptedData(PkcsObjectIdentifiers.Data, cAlgId, new BerOctetString(certBytes)); info = new ContentInfo[] { new ContentInfo(PkcsObjectIdentifiers.Data, keyString), new ContentInfo(PkcsObjectIdentifiers.EncryptedData, cInfo.ToAsn1Object()) }; } else { var cInfo = new BerOctetString(derEncodedBytes); info = new ContentInfo[] { new ContentInfo(PkcsObjectIdentifiers.Data, keyString), new ContentInfo(PkcsObjectIdentifiers.Data, cInfo.ToAsn1Object()) }; } byte[] data = new AuthenticatedSafe(info).GetEncoded(Asn1Encodable.Der); ContentInfo mainInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(data)); // // create the mac // byte[] mSalt = new byte[saltSize]; random.NextBytes(mSalt); Func <DerObjectIdentifier, byte[], int, char[], bool, byte[], byte[]> CalculatePbeMac = (oid_, salt_, itCount_, password_, wrongPkcs12Zero_, data_) => { var method = T.GetMethod("CalculatePbeMac", BindingFlags.NonPublic | BindingFlags.Static); return((byte[])method.Invoke(store, new object[] { oid_, salt_, itCount_, password_, wrongPkcs12Zero_, data_ })); }; MacData mData = null; if (null != integrityPassword) { //byte[] mac = CalculatePbeMac(OiwObjectIdentifiers.IdSha1, mSalt, minIterations, integrityPassword.ToArray(), false, data); byte[] mac = CalculatePbeMac(PbeUtilities.GetObjectIdentifier("PBEwithHmacSHA-256"), mSalt, minIterations, integrityPassword.ToArray(), false, data); //AlgorithmIdentifier algId = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance); AlgorithmIdentifier algId = new AlgorithmIdentifier(PbeUtilities.GetObjectIdentifier("PBEwithHmacSHA-256"), DerNull.Instance); DigestInfo dInfo = new DigestInfo(algId, mac); mData = new MacData(dInfo, mSalt, minIterations); } // // output the Pfx // Pfx pfx = new Pfx(mainInfo, mData); DerOutputStream derOut = new DerOutputStream(stream); derOut.WriteObject(pfx); }
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() { int iCount = 100; byte[] salt = DigestUtilities.DoFinal(digest); PbeParametersGenerator pGen = new Pkcs12ParametersGenerator(digest); pGen.Init( PbeParametersGenerator.Pkcs12PasswordToBytes(password), salt, iCount); ParametersWithIV parameters = (ParametersWithIV) pGen.GenerateDerivedParameters(baseAlgorithm, keySize, ivSize); KeyParameter encKey = (KeyParameter)parameters.Parameters; IBufferedCipher c; if (baseAlgorithm.Equals("RC4")) { c = CipherUtilities.GetCipher(baseAlgorithm); c.Init(true, encKey); } else { c = CipherUtilities.GetCipher(baseAlgorithm + "/CBC/PKCS7Padding"); c.Init(true, parameters); } byte[] enc = c.DoFinal(salt); c = CipherUtilities.GetCipher(algorithm); // PBEKeySpec keySpec = new PBEKeySpec(password, salt, iCount); // SecretKeyFactory fact = SecretKeyFactory.getInstance(algorithm); // // c.Init(false, fact.generateSecret(keySpec)); Asn1Encodable algParams = PbeUtilities.GenerateAlgorithmParameters( algorithm, salt, iCount); ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters( algorithm, password, algParams); c.Init(false, cipherParams); byte[] dec = c.DoFinal(enc); if (!AreEqual(salt, dec)) { Fail("" + algorithm + "failed encryption/decryption test"); } // NB: We don't support retrieving parameters from cipher // // // // get the parameters // // // AlgorithmParameters param = c.getParameters(); // PBEParameterSpec spec = (PBEParameterSpec)param.getParameterSpec(PBEParameterSpec.class); // // if (!AreEqual(salt, spec.getSalt())) // { // Fail("" + algorithm + "failed salt test"); // } // // if (iCount != spec.getIterationCount()) // { // Fail("" + algorithm + "failed count test"); // } // NB: This section just repeats earlier test passing 'param' separately // // // // try using parameters // // // keySpec = new PBEKeySpec(password); // // c.Init(false, fact.generateSecret(keySpec), param); // // dec = c.DoFinal(enc); // // if (!AreEqual(salt, dec)) // { // Fail("" + algorithm + "failed encryption/decryption test"); // } }