internal static AsymmetricKeyParameter GetPrivateKeyFromPEM(Org.BouncyCastle.Utilities.IO.Pem.PemObject pem) { if (pem == null) { throw new ArgumentNullException(nameof(pem)); } if (pem.Type.EndsWith("EC PRIVATE KEY")) { var sequence = Asn1Sequence.GetInstance(pem.Content); var e = sequence.GetEnumerator(); e.MoveNext(); var version = ((DerInteger)e.Current).Value; PrivateKeyInfo privateKeyInfo; if (version.IntValue == 0) //V1 { privateKeyInfo = PrivateKeyInfo.GetInstance(sequence); } else { var ec = ECPrivateKeyStructure.GetInstance(sequence); var algId = new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, ec.GetParameters()); privateKeyInfo = new PrivateKeyInfo(algId, ec.ToAsn1Object()); } return(PrivateKeyFactory.CreateKey(privateKeyInfo)); } else if (pem.Type.EndsWith("PRIVATE KEY")) { return(PrivateKeyFactory.CreateKey(pem.Content)); } return(null); }
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)); } } }
public static AsymmetricKeyParameter CreateKey( byte[] privateKeyInfoData) { return(CreateKey( PrivateKeyInfo.GetInstance( Asn1Object.FromByteArray(privateKeyInfoData)))); }
/** * 获取der编码格式中的纯私钥数据 */ public static byte[] GetPrivateKeyFormDER(byte[] derData) { PrivateKeyInfo pinfo = PrivateKeyInfo.GetInstance(derData); ECPrivateKeyStructure cpk = ECPrivateKeyStructure.GetInstance(pinfo.ParsePrivateKey()); int length = 32; byte[] bytes = cpk.GetKey().ToByteArray(); if (bytes.Length == length) { return(bytes); } int start = bytes[0] == 0 ? 1 : 0; int count = bytes.Length - start; if (count > length) { throw new ArgumentException("privateKey data is error"); } byte[] tmp = new byte[length]; Buffer.BlockCopy(bytes, start, tmp, tmp.Length - count, count); return(tmp); }
public static AsymmetricKeyParameter CreateKey( Stream inStr) { return(CreateKey( PrivateKeyInfo.GetInstance( new Asn1InputStream(inStr).ReadObject()))); }
public static AsymmetricKeyParameter CreateKey( Stream inStr) { return(CreateKey( PrivateKeyInfo.GetInstance( Asn1Object.FromStream(inStr)))); }
internal static AsymmetricKeyParameter GetPrivateKeyFromPEM(Org.BouncyCastle.Utilities.IO.Pem.PemObject pem) { AsymmetricKeyParameter result = null; if (pem.Type.EndsWith("EC PRIVATE KEY")) { Asn1Sequence sequence = Asn1Sequence.GetInstance(pem.Content); IEnumerator e = sequence.GetEnumerator(); e.MoveNext(); BigInteger version = ((DerInteger)e.Current).Value; PrivateKeyInfo privateKeyInfo; if (version.IntValue == 0) //V1 { privateKeyInfo = PrivateKeyInfo.GetInstance(sequence); } else { Org.BouncyCastle.Asn1.Sec.ECPrivateKeyStructure ec = Org.BouncyCastle.Asn1.Sec.ECPrivateKeyStructure.GetInstance(sequence); AlgorithmIdentifier algId = new AlgorithmIdentifier(Org.BouncyCastle.Asn1.X9.X9ObjectIdentifiers.IdECPublicKey, ec.GetParameters()); privateKeyInfo = new PrivateKeyInfo(algId, ec.ToAsn1Object()); } result = Org.BouncyCastle.Security.PrivateKeyFactory.CreateKey(privateKeyInfo); } else if (pem.Type.EndsWith("PRIVATE KEY")) { result = Org.BouncyCastle.Security.PrivateKeyFactory.CreateKey(pem.Content); } return(result); }
public object GetBagValue() { if (Type.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { return(new Pkcs8EncryptedPrivateKeyInfo(EncryptedPrivateKeyInfo.GetInstance(safeBag.BagValue))); } if (Type.Equals(PkcsObjectIdentifiers.CertBag)) { CertBag certBag = CertBag.GetInstance(safeBag.BagValue); return(new X509Certificate(X509CertificateStructure.GetInstance(Asn1OctetString.GetInstance(certBag.CertValue).GetOctets()))); } if (Type.Equals(PkcsObjectIdentifiers.KeyBag)) { return(PrivateKeyInfo.GetInstance(safeBag.BagValue)); } if (Type.Equals(PkcsObjectIdentifiers.CrlBag)) { CrlBag crlBag = CrlBag.GetInstance(safeBag.BagValue); return(new X509Crl(CertificateList.GetInstance(Asn1OctetString.GetInstance(crlBag.CrlValue).GetOctets()))); } return(safeBag.BagValue); }
public DecFormatter() { SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream")); // 載入私鑰. AsymmetricCipherKeyPair keyPair = ReadPem(this.pri_key); PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object(); this.priKey = PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(asn1ObjectPrivate)); }
public Object ParseObject(PemObject obj) { try { return(PrivateKeyInfo.GetInstance(obj.GetContent())); } catch (Exception e) { throw new OpenSslPemParsingException("problem parsing PRIVATE KEY: " + e.ToString(), e); } }
/// <summary> /// Converts the 32 byte private key to a 25 word mnemonic, including a checksum. /// Refer to the mnemonic package for additional documentation. /// </summary> /// <returns>return string a 25 word mnemonic</returns> public string ToMnemonic() { PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(this.privateKeyPair.Private); byte[] X509enc = privateKeyInfo.ToAsn1Object().GetEncoded(); PrivateKeyInfo pkinfo = PrivateKeyInfo.GetInstance(X509enc); var keyOcts = pkinfo.ParsePrivateKey(); byte[] res = Asn1OctetString.GetInstance(keyOcts).GetOctets(); return(Mnemonic.FromKey(res)); }
public void TestGost2012() { byte[] data = Base64.Decode( "MIGiAgEAMCEGCCqFAwcBAQECMBUGCSqFAwcBAgECAQYIKoUDBwEBAgMEQIXnWrZ6" + "ajvbCU6x9jK49PgQqCP00T/lW3laXCXueMF8X4Q1y3N9zfOJT2s/IgyPJVrUhgtO" + "1Akp+Roh8bCPPlqgODA2BggqhQMCCQMIATEqBCi72ZvrBVW6mFL/bQeXeMTf8Jh8" + "p/diI7Cg8ig4mXg3tsIUf4vBi61b"); var keyInfo = PrivateKeyInfo.GetInstance(data); var akp = Org.BouncyCastle.Security.PrivateKeyFactory.CreateKey(keyInfo); }
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)); }
/// <summary> /// 加载Pkcs8格式的私钥 /// </summary> /// <param name="privateKey"></param> /// <returns></returns> public static AsymmetricKeyParameter loadPrivateKeyPk8(string privateKey) { try { privateKey = KeyClear(privateKey); byte[] prikey = Convert.FromBase64String(privateKey); Asn1Object priKeyObj = Asn1Object.FromByteArray(prikey);//这里也可以从流中读取,从本地导入 AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(priKeyObj)); return(priKey); } catch (Exception) { throw new Exception("密钥格式不正确"); } }
private EncKeyWithID(Asn1Sequence seq) { this.privKeyInfo = PrivateKeyInfo.GetInstance(seq[0]); if (seq.Count <= 1) { this.identifier = null; return; } if (!(seq[1] is DerUtf8String)) { this.identifier = GeneralName.GetInstance(seq[1]); return; } this.identifier = seq[1]; }
/******** EXTERNAL OBJECT PUBLIC METHODS - END ********/ private bool ReadBase64(string base64) { byte[] keybytes = Base64.Decode(base64); Asn1InputStream istream = new Asn1InputStream(keybytes); Asn1Sequence seq = (Asn1Sequence)istream.ReadObject(); this.privateKeyInfo = PrivateKeyInfo.GetInstance(seq); istream.Close(); if (this.privateKeyInfo == null) { this.error.setError("PK015", "Could not read private key from base64 string"); return(false); } this.privateKeyAlgorithm = this.privateKeyInfo.PrivateKeyAlgorithm.Algorithm.Id;//this.privateKeyInfo.GetPrivateKeyAlgorithm().getAlgorithm().getId(); // 1.2.840.113549.1.1.1 return(true); }
/// <summary> /// 从Pkcs8私钥中提取公钥 /// </summary> /// <param name="privateKey">Pkcs8私钥</param> /// <returns></returns> public static string GetPublicKeyFromPrivateKeyPkcs8(string privateKey) { var privateKeyInfo = PrivateKeyInfo.GetInstance(Asn1Object.FromByteArray(Base64.Decode(privateKey))); privateKey = Base64.ToBase64String(privateKeyInfo.ParsePrivateKey().GetEncoded()); var instance = RsaPrivateKeyStructure.GetInstance(Base64.Decode(privateKey)); var publicParameter = (AsymmetricKeyParameter) new RsaKeyParameters(false, instance.Modulus, instance.PublicExponent); var privateParameter = (AsymmetricKeyParameter) new RsaPrivateCrtKeyParameters(instance.Modulus, instance.PublicExponent, instance.PrivateExponent, instance.Prime1, instance.Prime2, instance.Exponent1, instance.Exponent2, instance.Coefficient); var keyPair = new AsymmetricCipherKeyPair(publicParameter, privateParameter); var subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public); return(Base64.ToBase64String(subjectPublicKeyInfo.GetEncoded())); }
public override void PerformTest() { PrivateKeyInfo privInfo1 = PrivateKeyInfo.GetInstance(priv); IsTrue(!privInfo1.HasPublicKey); PrivateKeyInfo privInfo2 = new PrivateKeyInfo(privInfo1.PrivateKeyAlgorithm, privInfo1.ParsePrivateKey()); IsTrue("enc 1 failed", AreEqual(priv, privInfo2.GetEncoded())); privInfo1 = PrivateKeyInfo.GetInstance(privWithPub); IsTrue(privInfo1.HasPublicKey); privInfo2 = new PrivateKeyInfo(privInfo1.PrivateKeyAlgorithm, privInfo1.ParsePrivateKey(), privInfo1.Attributes, privInfo1.PublicKeyData.GetOctets()); IsTrue("enc 2 failed", AreEqual(privWithPub, privInfo2.GetEncoded())); }
/// <summary> /// -----BEGIN PRIVATE KEY----- /// ... /// -----END PRIVATE KEY----- /// </summary> /// <param name="privateKey">Pkcs8格式私钥</param> /// <returns></returns> public static RSAParameters GetRsaParametersFormAsn1PrivateKey(string privateKey) { var keyInfo = PrivateKeyInfo.GetInstance(Asn1Object.FromByteArray(Base64.Decode(privateKey))); var instance = RsaPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); return(new RSAParameters { D = instance.PrivateExponent.ToByteArrayUnsigned(), DP = instance.Exponent1.ToByteArrayUnsigned(), DQ = instance.Exponent2.ToByteArrayUnsigned(), Exponent = instance.PublicExponent.ToByteArrayUnsigned(), InverseQ = instance.Coefficient.ToByteArrayUnsigned(), Modulus = instance.Modulus.ToByteArrayUnsigned(), P = instance.Prime1.ToByteArrayUnsigned(), Q = instance.Prime2.ToByteArrayUnsigned(), }); }
private static PrivateKeyInfo GetPrivateKeyInfo(byte[] encoding) { try { return(PrivateKeyInfo.GetInstance(encoding)); } catch (ArgumentException e) { // OpenSSL's old format, and some others - Try just the private key data. try { return(new PrivateKeyInfo(DEF_ALG_ID, Asn1Sequence.GetInstance(encoding))); } catch (Exception) { throw new ArgumentException("Unable to parse private key: " + e.Message, e); } } }
private EncKeyWithID(Asn1Sequence seq) { privKeyInfo = PrivateKeyInfo.GetInstance(seq[0]); if (seq.Count > 1) { if (!(seq[1] is DerUtf8String)) { identifier = GeneralName.GetInstance(seq[1]); } else { identifier = seq[1]; } } else { identifier = null; } }
/// <summary> /// Get a decryptor from the passed in provider and decrypt the encrypted private key info, returning the result. /// </summary> /// <param name="inputDecryptorProvider">A provider to query for decryptors for the object.</param> /// <returns>The decrypted private key info structure.</returns> public PrivateKeyInfo DecryptPrivateKeyInfo(IDecryptorBuilderProvider inputDecryptorProvider) { try { ICipherBuilder decryptorBuilder = inputDecryptorProvider.CreateDecryptorBuilder(encryptedPrivateKeyInfo.EncryptionAlgorithm); ICipher encIn = decryptorBuilder.BuildCipher(new MemoryInputStream(encryptedPrivateKeyInfo.GetEncryptedData())); Stream strm = encIn.Stream; byte[] data = Streams.ReadAll(encIn.Stream); Platform.Dispose(strm); return(PrivateKeyInfo.GetInstance(data)); } catch (Exception e) { throw new PkcsException("unable to read encrypted data: " + e.Message, e); } }
private void BaseOaepTest( int id, byte[] pubKeyEnc, byte[] privKeyEnc, byte[] output) { // // extract the public key info. // Asn1Object pubKeyObj = Asn1Object.FromByteArray(pubKeyEnc); RsaPublicKeyStructure pubStruct = RsaPublicKeyStructure.GetInstance( SubjectPublicKeyInfo.GetInstance(pubKeyObj).GetPublicKey()); // // extract the private key info. // Asn1Object privKeyObj = Asn1Object.FromByteArray(privKeyEnc); RsaPrivateKeyStructure privStruct = RsaPrivateKeyStructure.GetInstance( PrivateKeyInfo.GetInstance(privKeyObj).ParsePrivateKey()); RsaKeyParameters pubParameters = new RsaKeyParameters( false, pubStruct.Modulus, pubStruct.PublicExponent); RsaKeyParameters privParameters = new RsaPrivateCrtKeyParameters( privStruct.Modulus, privStruct.PublicExponent, privStruct.PrivateExponent, privStruct.Prime1, privStruct.Prime2, privStruct.Exponent1, privStruct.Exponent2, privStruct.Coefficient); byte[] input = new byte[] { (byte)0x54, (byte)0x85, (byte)0x9b, (byte)0x34, (byte)0x2c, (byte)0x49, (byte)0xea, (byte)0x2a }; EncDec("id(" + id + ")", pubParameters, privParameters, seed, input, output); }
public static IAsymmetricPrivateKey CreatePrivateKey(byte[] encodedPrivateKeyInfo) { PrivateKeyInfo keyInfo = PrivateKeyInfo.GetInstance(encodedPrivateKeyInfo); AlgorithmIdentifier algId = keyInfo.PrivateKeyAlgorithm; if (algId.Algorithm.Equals(PkcsObjectIdentifiers.RsaEncryption) || algId.Algorithm.Equals(X509ObjectIdentifiers.IdEARsa)) { return(new AsymmetricRsaPrivateKey(FipsRsa.Alg, encodedPrivateKeyInfo)); } else if (algId.Algorithm.Equals(X9ObjectIdentifiers.IdDsa) || algId.Algorithm.Equals(OiwObjectIdentifiers.DsaWithSha1)) { return(new AsymmetricDsaPrivateKey(FipsDsa.Alg, encodedPrivateKeyInfo)); } else if (algId.Algorithm.Equals(X9ObjectIdentifiers.IdECPublicKey)) { return(new AsymmetricECPrivateKey(FipsEC.Alg, encodedPrivateKeyInfo)); } else if (algId.Algorithm.Equals(BCObjectIdentifiers.sphincs256)) { return(new AsymmetricSphincsPrivateKey(Sphincs.Alg, encodedPrivateKeyInfo)); } else if (algId.Algorithm.Equals(BCObjectIdentifiers.newHope)) { return(new AsymmetricNHPrivateKey(NewHope.Alg, encodedPrivateKeyInfo)); } else if (algId.Algorithm.Equals(X9ObjectIdentifiers.DHPublicNumber) || algId.Algorithm.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { return(new AsymmetricDHPrivateKey(new GeneralAlgorithm("DH"), encodedPrivateKeyInfo)); } else if (algId.Algorithm.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { return(new AsymmetricDHPrivateKey(ElGamal.Alg, encodedPrivateKeyInfo)); } else { throw new ArgumentException("algorithm identifier in key not recognised"); } }
public IActionResult Get() { string plain_text = "hello world"; // 加密 byte[] pubkey = System.Convert.FromBase64String(pub_key); Asn1Object pubKeyObj = Asn1Object.FromByteArray(pubkey); AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(SubjectPublicKeyInfo.GetInstance(pubKeyObj)); IBufferedCipher cipher1 = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); cipher1.Init(true, pubKey);//true表示加密 byte[] enc_utf8 = System.Text.Encoding.UTF8.GetBytes(plain_text); byte[] encoded_data = cipher1.DoFinal(enc_utf8); // 解密 var keyPair = ReadPem(pri_key); _logger.LogError(keyPair.ToString()); AsymmetricKeyParameter private_key = keyPair.Private; PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(private_key); Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object(); AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(asn1ObjectPrivate)); IBufferedCipher cipher = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); cipher.Init(false, priKey); //false表示解密 var dec_utf8 = cipher.DoFinal(encoded_data); var answer = System.Text.Encoding.UTF8.GetString(dec_utf8); var result = new { plain_text, enc_utf8 = (enc_utf8), encoded_data = (encoded_data), encoded_len = (encoded_data.Length), dec_utf8 = (dec_utf8), answer }; return(Ok(result)); }
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)); }
public (string PrivateKey, string PublicKey) GenerateRsaKeys(string companyName) { var rsaKeyPairGenerator = new RsaKeyPairGenerator(); rsaKeyPairGenerator.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); var pair = rsaKeyPairGenerator.GenerateKeyPair(); var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(pair.Private); byte[] privateKeyPkcs8DerEncodedBytes = privateKeyInfo.ToAsn1Object().GetDerEncoded(); // privateKeyPkcs8DerEncodedBytes contains PKCS#8 DER-encoded private key as a byte[] var pkcs8PrivateKeyInfo = PrivateKeyInfo.GetInstance(privateKeyPkcs8DerEncodedBytes); var pkcs1Key = RsaPrivateKeyStructure.GetInstance(pkcs8PrivateKeyInfo.ParsePrivateKey()); byte[] privateKeyPkcs1EncodedBytes = pkcs1Key.GetEncoded(); var sb = new StringBuilder(); sb.AppendLine("-----BEGIN RSA PRIVATE KEY-----"); sb.AppendLine(Convert.ToBase64String(privateKeyPkcs1EncodedBytes, Base64FormattingOptions.InsertLineBreaks)); sb.AppendLine("-----END RSA PRIVATE KEY-----"); var serializedPrivate = sb.ToString(); var caName = new X509Name($"CN={companyName}"); var caCert = GenerateCertificate(caName, caName, pair.Private, pair.Public); var certEncoded = caCert.GetEncoded(); sb = new StringBuilder(); sb.AppendLine("-----BEGIN CERTIFICATE-----"); sb.AppendLine(Convert.ToBase64String(certEncoded, Base64FormattingOptions.InsertLineBreaks)); sb.AppendLine("-----END CERTIFICATE-----"); var serializedPublic = sb.ToString(); return(serializedPrivate, serializedPublic); }
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)); }
public void Load( Stream input, char[] password) { if (input == null) { throw new ArgumentNullException("input"); } if (password == null) { throw new ArgumentNullException("password"); } Asn1Sequence obj = (Asn1Sequence)Asn1Object.FromStream(input); Pfx bag = new Pfx(obj); ContentInfo info = bag.AuthSafe; 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(); byte[] mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, false, data); byte[] dig = dInfo.GetDigest(); if (!Arrays.ConstantTimeAreEqual(mac, dig)) { if (password.Length > 0) { throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); } // Try with incorrect zero length password mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, true, data); if (!Arrays.ConstantTimeAreEqual(mac, dig)) { throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); } wrongPkcs12Zero = true; } } keys.Clear(); localIds.Clear(); IList chain = Platform.CreateArrayList(); if (info.ContentType.Equals(PkcsObjectIdentifiers.Data)) { byte[] octs = ((Asn1OctetString)info.Content).GetOctets(); AuthenticatedSafe authSafe = new AuthenticatedSafe( (Asn1Sequence)Asn1OctetString.FromByteArray(octs)); ContentInfo[] cis = authSafe.GetContentInfo(); foreach (ContentInfo ci in cis) { DerObjectIdentifier oid = ci.ContentType; if (oid.Equals(PkcsObjectIdentifiers.Data)) { byte[] octets = ((Asn1OctetString)ci.Content).GetOctets(); Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets); foreach (Asn1Sequence subSeq in seq) { SafeBag b = new SafeBag(subSeq); if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { EncryptedPrivateKeyInfo eIn = EncryptedPrivateKeyInfo.GetInstance(b.BagValue); PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo( password, wrongPkcs12Zero, eIn); IAsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo); // // set the attributes on the key // IDictionary attributes = Platform.CreateHashtable(); 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) { // TODO We should be adding all attributes in the set attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.Contains(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); // TODO Do these in a separate loop, just collect aliases here keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } } if (localId != null) { string name = Hex.ToHexString(localId.GetOctets()); if (alias == null) { keys[name] = pkcs12Key; } else { // TODO There may have been more than one alias localIds[alias] = name; } } else { unmarkedKey = true; keys["unmarked"] = pkcs12Key; } } else if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag)) { chain.Add(b); } else { #if !NETFX_CORE Console.WriteLine("extra " + b.BagID); Console.WriteLine("extra " + Asn1Dump.DumpAsString(b)); #endif } } } else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData)) { EncryptedData d = EncryptedData.GetInstance(ci.Content); byte[] octets = CryptPbeData(false, d.EncryptionAlgorithm, password, wrongPkcs12Zero, d.Content.GetOctets()); Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets); foreach (Asn1Sequence subSeq in seq) { SafeBag b = new SafeBag(subSeq); 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); IAsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo); // // set the attributes on the key // IDictionary attributes = Platform.CreateHashtable(); 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) { // TODO We should be adding all attributes in the set attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.Contains(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); // TODO Do these in a separate loop, just collect aliases here keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } // TODO Should we be checking localIds != null here // as for PkcsObjectIdentifiers.Data version above? string name = Hex.ToHexString(localId.GetOctets()); if (alias == null) { keys[name] = pkcs12Key; } else { // TODO There may have been more than one alias localIds[alias] = name; } } else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag)) { PrivateKeyInfo privKeyInfo = PrivateKeyInfo.GetInstance(b.BagValue); IAsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privKeyInfo); // // set the attributes on the key // string alias = null; Asn1OctetString localId = null; IDictionary attributes = Platform.CreateHashtable(); 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) { // TODO We should be adding all attributes in the set attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.Contains(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); // TODO Do these in a separate loop, just collect aliases here keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } // TODO Should we be checking localIds != null here // as for PkcsObjectIdentifiers.Data version above? string name = Hex.ToHexString(localId.GetOctets()); if (alias == null) { keys[name] = pkcs12Key; } else { // TODO There may have been more than one alias localIds[alias] = name; } } else { #if !NETFX_CORE Console.WriteLine("extra " + b.BagID); Console.WriteLine("extra " + Asn1Dump.DumpAsString(b)); #endif } } } else { #if !NETFX_CORE Console.WriteLine("extra " + oid); Console.WriteLine("extra " + Asn1Dump.DumpAsString(ci.Content)); #endif } } } certs.Clear(); chainCerts.Clear(); keyCerts.Clear(); foreach (SafeBag b in chain) { CertBag cb = new CertBag((Asn1Sequence)b.BagValue); byte[] octets = ((Asn1OctetString)cb.CertValue).GetOctets(); X509Certificate cert = new X509CertificateParser().ReadCertificate(octets); // // set the attributes // IDictionary attributes = Platform.CreateHashtable(); 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) { // TODO We should be adding all attributes in the set Asn1Encodable attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.Contains(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } } CertId certId = new CertId(cert.GetPublicKey()); X509CertificateEntry pkcs12Cert = new X509CertificateEntry(cert, attributes); chainCerts[certId] = pkcs12Cert; if (unmarkedKey) { if (keyCerts.Count == 0) { string name = Hex.ToHexString(certId.Id); keyCerts[name] = pkcs12Cert; object temp = keys["unmarked"]; keys.Remove("unmarked"); keys[name] = temp; } } else { if (localId != null) { string name = Hex.ToHexString(localId.GetOctets()); keyCerts[name] = pkcs12Cert; } if (alias != null) { // TODO There may have been more than one alias certs[alias] = pkcs12Cert; } } } }
public void Load( Stream input, char[] password) { if (input == null) { throw new ArgumentNullException("input"); } Asn1Sequence obj = (Asn1Sequence)Asn1Object.FromStream(input); Pfx bag = new Pfx(obj); ContentInfo info = bag.AuthSafe; bool wrongPkcs12Zero = false; if (password != null && 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(); byte[] mac = CalculatePbeMac(algId.Algorithm, salt, itCount, password, false, data); byte[] dig = dInfo.GetDigest(); if (!Arrays.ConstantTimeAreEqual(mac, dig)) { if (password.Length > 0) { throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); } // Try with incorrect zero length password mac = CalculatePbeMac(algId.Algorithm, salt, itCount, password, true, data); if (!Arrays.ConstantTimeAreEqual(mac, dig)) { throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); } wrongPkcs12Zero = true; } } keys.Clear(); localIds.Clear(); unmarkedKeyEntry = null; IList certBags = Platform.CreateArrayList(); if (info.ContentType.Equals(PkcsObjectIdentifiers.Data)) { byte[] octs = ((Asn1OctetString)info.Content).GetOctets(); AuthenticatedSafe authSafe = new AuthenticatedSafe( (Asn1Sequence)Asn1OctetString.FromByteArray(octs)); ContentInfo[] cis = authSafe.GetContentInfo(); foreach (ContentInfo ci in cis) { DerObjectIdentifier oid = ci.ContentType; byte[] octets = null; if (oid.Equals(PkcsObjectIdentifiers.Data)) { octets = ((Asn1OctetString)ci.Content).GetOctets(); } else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData)) { if (password != null) { EncryptedData d = EncryptedData.GetInstance(ci.Content); octets = CryptPbeData(false, d.EncryptionAlgorithm, password, wrongPkcs12Zero, d.Content.GetOctets()); } } else { // TODO Other data types } if (octets != null) { Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets); foreach (Asn1Sequence subSeq in seq) { SafeBag b = new SafeBag(subSeq); if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag)) { certBags.Add(b); } else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { LoadPkcs8ShroudedKeyBag(EncryptedPrivateKeyInfo.GetInstance(b.BagValue), b.BagAttributes, password, wrongPkcs12Zero); } else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag)) { LoadKeyBag(PrivateKeyInfo.GetInstance(b.BagValue), b.BagAttributes); } else { // TODO Other bag types } } } } } certs.Clear(); chainCerts.Clear(); keyCerts.Clear(); foreach (SafeBag b in certBags) { CertBag certBag = new CertBag((Asn1Sequence)b.BagValue); byte[] octets = ((Asn1OctetString)certBag.CertValue).GetOctets(); X509Certificate cert = new X509CertificateParser().ReadCertificate(octets); // // set the attributes // IDictionary attributes = Platform.CreateHashtable(); Asn1OctetString localId = null; string alias = null; if (b.BagAttributes != null) { foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = DerObjectIdentifier.GetInstance(sq[0]); Asn1Set attrSet = Asn1Set.GetInstance(sq[1]); if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set Asn1Encodable attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.Contains(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } } CertId certId = new CertId(cert.GetPublicKey()); X509CertificateEntry certEntry = new X509CertificateEntry(cert, attributes); chainCerts[certId] = certEntry; if (unmarkedKeyEntry != null) { if (keyCerts.Count == 0) { string name = Hex.ToHexString(certId.Id); keyCerts[name] = certEntry; keys[name] = unmarkedKeyEntry; } } else { if (localId != null) { string name = Hex.ToHexString(localId.GetOctets()); keyCerts[name] = certEntry; } if (alias != null) { // TODO There may have been more than one alias certs[alias] = certEntry; } } } }