public void TestFormatSignature() { var random = new Random(); var dsa_key = new SshKey(SshVersion.SSH2, new DsaPublicKeyParameters ( new BigInteger ("1"), new DsaParameters(new BigInteger ("2"), new BigInteger ("3"), new BigInteger ("4")))); // test that dsa signature works when values are not full 20 bytes. byte[] r_bytes = new byte[19]; byte[] s_bytes = new byte[19]; random.NextBytes(r_bytes); random.NextBytes(s_bytes); var r = new DerInteger(r_bytes); var s = new DerInteger(s_bytes); var sequence = new DerSequence(r, s); var signature = dsa_key.FormatSignature(sequence.GetEncoded()); Assert.That(signature.Count(), Is.EqualTo(40)); }
private void doTestNullDerNullCert() { AsymmetricCipherKeyPair keyPair = GenerateLongFixedKeys(); AsymmetricKeyParameter pubKey = keyPair.Public; AsymmetricKeyParameter privKey = keyPair.Private; X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(new X509Name("CN=Test")); certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); certGen.SetSubjectDN(new X509Name("CN=Test")); certGen.SetPublicKey(pubKey); certGen.SetSignatureAlgorithm("MD5WithRSAEncryption"); X509Certificate cert = certGen.Generate(privKey); X509CertificateStructure certStruct = X509CertificateStructure.GetInstance( Asn1Object.FromByteArray(cert.GetEncoded())); Asn1Encodable tbsCertificate = certStruct.TbsCertificate; AlgorithmIdentifier sig = certStruct.SignatureAlgorithm; DerSequence seq = new DerSequence( tbsCertificate, new AlgorithmIdentifier(sig.Algorithm), certStruct.Signature); try { // verify byte[] encoded = seq.GetEncoded(); X509CertificateParser fact = new X509CertificateParser(); cert = fact.ReadCertificate(encoded); cert.Verify(cert.GetPublicKey()); } catch (Exception e) { Fail("doTestNullDerNull failed - exception " + e.ToString(), e); } }
private static byte[] BuildOCSPResponse(byte[] BasicOCSPResponse) { DerOctetString doctet = new DerOctetString(BasicOCSPResponse); Asn1EncodableVector v2 = new Asn1EncodableVector(); v2.Add(OcspObjectIdentifiers.PkixOcspBasic); v2.Add(doctet); DerEnumerated den = new DerEnumerated(0); Asn1EncodableVector v3 = new Asn1EncodableVector(); v3.Add(den); v3.Add(new DerTaggedObject(true, 0, new DerSequence(v2))); DerSequence seq = new DerSequence(v3); return seq.GetEncoded(); }
public static bool verifySign(string signature, byte[] origdata, ICipherParameters pubkey) { var dsa = SignerUtilities.GetSigner(ECDSA); dsa.Init (false, pubkey); dsa.BlockUpdate(origdata, 0, origdata.Length); BigInteger r = new BigInteger (signature.Substring (0, 64), 16); BigInteger s = new BigInteger (signature.Substring (64, 64), 16); Asn1EncodableVector vec = new Asn1EncodableVector (); vec.Add (new DerInteger (r)); vec.Add (new DerInteger (s)); Asn1Sequence seq = new DerSequence(vec); byte[] sign = seq.GetEncoded (); bool result = dsa.VerifySignature (sign); return result; }
/// <summary> /// Write myself to the given stream /// </summary> public void WriteTo(Stream stream, out string md5FingerPrint, out string sha1FingerPrint) { X509Certificate[] cert; AsymmetricKeyEntry privateKey; LoadPfx(out cert, out privateKey); var certsVector = new Asn1EncodableVector(); md5FingerPrint = null; sha1FingerPrint = null; foreach (var c in cert) { var certStream = new MemoryStream(c.GetEncoded()); var certStruct = X509CertificateStructure.GetInstance(new Asn1InputStream(certStream).ReadObject()); certsVector.Add(certStruct); if (md5FingerPrint == null) { var certData = certStream.ToArray(); md5FingerPrint = CreateFingerprint(new MD5Digest(), certData); } if (sha1FingerPrint == null) { var certData = certStream.ToArray(); sha1FingerPrint = CreateFingerprint(new Sha1Digest(), certData); } } var encryptedSignature = GetSignature(signature, privateKey.Key); var signerInfo = new SignerInfo( new DerInteger(1), new IssuerAndSerialNumber(cert[0].IssuerDN, cert[0].SerialNumber), new AlgorithmIdentifier(Oids.SHA1, DerNull.Instance), null, new AlgorithmIdentifier(Oids.RSA, DerNull.Instance), new DerOctetString(encryptedSignature), null); var pkcs7 = new SignedData( new DerInteger(1), new DerSet(new AlgorithmIdentifier(Oids.SHA1, DerNull.Instance)), new ContentInfo(new DerObjectIdentifier(Oids.data), null), new DerSet(certsVector), null, new DerSet(signerInfo)); //var signedData = new ContentInfo(new DERObjectIdentifier(Oids.signedData), pkcs7); var v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(Oids.signedData)); v.Add(new DerTaggedObject(0, pkcs7)); var signedData = new DerSequence(v); // Save var data = signedData.GetEncoded(); stream.Write(data, 0, data.Length); }
private string GenerateX509Cert(string publicKey, string x509Subject) { Asn1Sequence asn1Sequence = null; using (var reader = new StringReader(publicKey)) { // Read the RSA public key from the input string. var pemReader = new PemReader(reader); var pemObject = pemReader.ReadPemObject(); asn1Sequence = (Asn1Sequence)Asn1Object.FromByteArray(pemObject.Content); } // Generate a TBS certificate. We use placeholder-like values since // the consumer of this certificate should only use the subject // public key info. var tbsCertGen = new V3TbsCertificateGenerator(); tbsCertGen.SetSerialNumber(new DerInteger(1)); var signatureAlgId = new AlgorithmIdentifier(PkcsObjectIdentifiers.Sha1WithRsaEncryption, DerNull.Instance); tbsCertGen.SetSignature(signatureAlgId); tbsCertGen.SetIssuer(new X509Name("CN=Root Agency")); var dateTimeNow = DateTime.Now; tbsCertGen.SetStartDate(new Time(dateTimeNow.AddMinutes(-10))); tbsCertGen.SetEndDate(new Time(dateTimeNow.AddYears(1))); // Openssh key doesn`t have any start/end date, this is to satisfy RDFE tbsCertGen.SetSubject(new X509Name(x509Subject)); tbsCertGen.SetSubjectPublicKeyInfo(new SubjectPublicKeyInfo(new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance), asn1Sequence)); var tbsCert = tbsCertGen.GenerateTbsCertificate(); // Per RFC 3280, the layout of an X.509 v3 certificate looks like: // Certificate ::= SEQUENCE { // tbsCertificate TBSCertificate, // signatureAlgorithm AlgorithmIdentifier, // signatureValue BIT STRING // } // Since we don't have access to the private key, we cannot create // a signature for the TBS. However, a valid certificate requires // a bit string for the signature value, so we use a 0-byte array // in its place. Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(tbsCert); v.Add(signatureAlgId); v.Add(new DerBitString(new byte[0])); var derSequence = new DerSequence(v); // Output the DER-encoded X509 certificate. var sb = new StringBuilder(); using (var writer = new StringWriter(sb, CultureInfo.InvariantCulture)) { var pemWriter = new PemWriter(writer); pemWriter.WriteObject(new PemObject("CERTIFICATE", derSequence.GetEncoded())); } return sb.ToString(); }
private string GeneratePkcs1PublicKeyFromRsaEncryptedOpenSshPublicKey(string content) { List<byte[]> data = this.GetOpenSshPublicKeyInBinary(content); if (data.Count != 3) { throw new InvalidOperationException("Given OpenSSH key body is invalid."); } //// RFC 3447 (PKCS #1) //// 3.1 RSA public key //// For the purposes of this document, an RSA public key consists of two //// components: //// n the RSA modulus, a positive integer //// e the RSA public exponent, a positive integer //// A recommended syntax for interchanging RSA public keys between //// implementations is given in Appendix A.1.1; an implementation's //// internal representation may differ. //// A.1.1 RSA public key syntax //// An RSA public key should be represented with the ASN.1 type //// RSAPublicKey: //// RSAPublicKey ::= SEQUENCE { //// modulus INTEGER, -- n //// publicExponent INTEGER -- e //// } //// The fields of type RSAPublicKey have the following meanings: //// * modulus is the RSA modulus n. //// * publicExponent is the RSA public exponent e. //// RFC 4251: Strings are also used to store text. In that case, US-ASCII is //// used for internal names, and ISO-10646 UTF-8 for text that might be displayed to the user. string algorithmName = Encoding.UTF8.GetString(data[0]); if (!"ssh-rsa".Equals(algorithmName, StringComparison.Ordinal)) { throw new InvalidOperationException("Invalid OpenSSH key body, expected 'ssh-rsa' encrypted."); } var publicExponent = new DerInteger(data[1]); var modulus = new DerInteger(data[2]); var sequence = new DerSequence(new Asn1Encodable[] { modulus, publicExponent }); // Generate DER-encoded public key StringBuilder sb = new StringBuilder(); using (var sw = new StringWriter(sb, CultureInfo.InvariantCulture)) { var pemWriter = new Org.BouncyCastle.Utilities.IO.Pem.PemWriter(sw); pemWriter.WriteObject(new PemObject("RSA PUBLIC KEY", sequence.GetEncoded())); } return sb.ToString(); }