public static TransactionBroadcast Sign(this TransactionBroadcast transaction, ICryptoContext cryptoContext, IPrivateKey privateKey, SigningContext context) { var clone = transaction.Clone(); if (transaction.Signature?.RawBytes.Length == cryptoContext.SignatureLength) { Logger.Debug("The transaction was already signed, returning a clone."); return(clone); } clone.Signature = null; var signatureBytes = cryptoContext.Sign(privateKey, clone.ToByteArray(), context.ToByteArray()).SignatureBytes; clone.Signature = new Signature { RawBytes = signatureBytes.ToByteString(), SigningContext = context }; return(clone); }
public static int Main(string[] args) { var logger = new LoggerConfiguration().WriteTo.Console().CreateLogger(); var userOutput = new ConsoleUserOutput(); userOutput.WriteLine("Catalyst Network Simulator"); var passwordRegistry = new PasswordRegistry(); Parser.Default.ParseArguments <Options>(args).WithParsed(options => passwordRegistry.SetFromOptions(options)); var fileSystem = new FileSystem(); var userInput = new ConsoleUserInput(); var consolePasswordReader = new ConsolePasswordReader(userOutput, userInput); var certificateStore = new CertificateStore(fileSystem, new PasswordManager(consolePasswordReader, passwordRegistry)); var certificate = certificateStore.ReadOrCreateCertificateFile("mycert.pfx"); var signingContext = new SigningContext { NetworkType = NetworkType.Devnet, SignatureType = SignatureType.ProtocolPeer }; var clientRpcInfoList = ConfigHelper.GenerateClientRpcInfoFromConfig(userOutput, passwordRegistry, certificate, logger, signingContext ).ToList(); var simulation = new TransactionSimulation(userOutput); var simulator = new Simulator(simulation, logger); simulator.SimulateAsync(clientRpcInfoList).Wait(); return(Environment.ExitCode); }
public void ValidateTransactionSignature_will_pass_with_valid_transaction_signature() { var subbedLogger = Substitute.For <ILogger>(); var cryptoContext = new FfiWrapper(); var transactionValidator = new TransactionValidator(subbedLogger, cryptoContext); // build a valid transaction var privateKey = cryptoContext.GeneratePrivateKey(); var validTransaction = new PublicEntry { SenderAddress = privateKey.GetPublicKey().Bytes.ToByteString() }; var signingContext = new SigningContext { NetworkType = NetworkType.Devnet, SignatureType = SignatureType.TransactionPublic }; var signature = new Signature { // sign an actual TransactionBroadcast object RawBytes = cryptoContext.Sign(privateKey, validTransaction.ToByteArray(), signingContext.ToByteArray()) .SignatureBytes.ToByteString(), SigningContext = signingContext }; validTransaction.Signature = signature; var result = transactionValidator.ValidateTransaction(validTransaction); result.Should().BeTrue(); }
public ChatterProxyService() { WriteLogToFile("Starting ChatterProxyService"); url = ConfigurationSettings.AppSettings["SalesForceUrl"]; userName = ConfigurationSettings.AppSettings["SalesForceUserName"]; password = ConfigurationSettings.AppSettings["SalesForcePassword"]; token = ConfigurationSettings.AppSettings["SalesForceToken"]; clientId = ConfigurationSettings.AppSettings["SalesForceClientId"]; grantType = ConfigurationSettings.AppSettings["SalesForceGrantType"]; clientSecret = ConfigurationSettings.AppSettings["SalesForceClientSecret"]; cacheInterval = Int32.Parse(ConfigurationSettings.AppSettings["CacheInterval"]); cacheCapacity = Int32.Parse(ConfigurationSettings.AppSettings["cacheCapacity"]); logService = Boolean.Parse(ConfigurationSettings.AppSettings["LogService"]); signedFetch = Boolean.Parse(ConfigurationSettings.AppSettings["SignedFetch"]); ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(customXertificateValidation); profilesService = new ProfilesServices(); getChatterSoapService(); if (signedFetch) { // load default cert X509Certificate2 cert = new X509Certificate2(ConfigurationSettings.AppSettings["OAuthCert"]); provider = cert.PublicKey.Key; signer = new OAuthContextSigner(); signingContext = new SigningContext(); //signingContext.ConsumerSecret = ...; // if there is a consumer secret signingContext.Algorithm = provider; } activitiesFetcher = new Timer(GetActivities, null, 0, cacheInterval * 1000); }
/** * @TODO this should extend file system based tests and resolve tests via autofac container */ public DeltaExecutorTests() { _specProvider = new CatalystSpecProvider(); _stateProvider = new StateProvider(new StateDb(), new StateDb(), LimboLogs.Instance); var storageProvider = new StorageProvider(new StateDb(), _stateProvider, LimboLogs.Instance); IKvm virtualMachine = new KatVirtualMachine(_stateProvider, storageProvider, new StateUpdateHashProvider(), _specProvider, LimboLogs.Instance); var logger = Substitute.For <ILogger>(); logger.IsEnabled(Arg.Any <LogEventLevel>()).Returns(true); _senderPrivateKey = _cryptoContext.GeneratePrivateKey(); _senderPublicKey = _senderPrivateKey.GetPublicKey(); _recipient = _cryptoContext.GeneratePrivateKey().GetPublicKey(); _poorSender = _cryptoContext.GeneratePrivateKey().GetPublicKey(); _stateProvider.CreateAccount(_poorSender.ToKvmAddress(), 0.Kat()); _stateProvider.CreateAccount(_senderPublicKey.ToKvmAddress(), 1000.Kat()); _stateProvider.CreateAccount(Address.Zero, 1000.Kat()); _stateProvider.Commit(_specProvider.GenesisSpec); _executor = new DeltaExecutor(_specProvider, _stateProvider, storageProvider, virtualMachine, new FfiWrapper(), logger); _signingContext = new SigningContext { NetworkType = NetworkType.Devnet, SignatureType = SignatureType.TransactionPublic }; }
public CryptoBenchmark() { _context = new SigningContext { NetworkType = NetworkType.Mainnet, SignatureType = SignatureType.TransactionConfidential }; var key = ByteString.CopyFrom(new byte[32]); var amount = ByteString.CopyFrom(new byte[32]); _transaction = new TransactionBroadcast { PublicEntry = new PublicEntry { Amount = amount, Nonce = 1, SenderAddress = key, ReceiverAddress = key, GasPrice = amount } }; _crypto = new NoopCryptoContext(); }
public static Signature GenerateSignature(this PublicEntry publicEntry, ICryptoContext cryptoContext, IPrivateKey privateKey, SigningContext context) { return(GeneratePublicEntrySignature(publicEntry.Clone(), cryptoContext, privateKey, context)); }
public VerifyMessageRequestObserverTests() { _signingContext = new SigningContext { NetworkType = NetworkType.Devnet, SignatureType = SignatureType.ProtocolRpc }; _testPeerId = PeerIdHelper.GetPeerId("TestPeerIdentifier"); var peerSettings = _testPeerId.ToSubstitutedPeerSettings(); _keySigner = Substitute.For <FakeKeySigner>(); _keySigner.CryptoContext.Returns(new FfiWrapper()); var logger = Substitute.For <ILogger>(); _fakeContext = Substitute.For <IChannelHandlerContext>(); var fakeChannel = Substitute.For <IChannel>(); _fakeContext.Channel.Returns(fakeChannel); _verifyMessageRequestObserver = new VerifyMessageRequestObserver(peerSettings, logger, _keySigner); _verifyMessageRequest = GetValidVerifyMessageRequest(); }
public LedgerTests() { _testScheduler = new TestScheduler(); _fakeRepository = Substitute.For <IAccountRepository>(); _hashProvider = new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("keccak-256")); _mapperProvider = new TestMapperProvider(); _logger = Substitute.For <ILogger>(); _mempool = Substitute.For <IMempool <PublicEntryDao> >(); _deltaHashProvider = Substitute.For <IDeltaHashProvider>(); _receipts = Substitute.For <ITransactionRepository>(); _synchroniser = Substitute.For <ISynchroniser>(); _genesisHash = _hashProvider.ComputeUtf8MultiHash("genesis").ToCid(); _synchroniser.DeltaCache.GenesisHash.Returns(_genesisHash); _executor = Substitute.For <IDeltaExecutor>(); _stateProvider = Substitute.For <IStateProvider>(); _storageProvider = Substitute.For <IStorageProvider>(); _cryptoContext = new FfiWrapper(); _signingContext = new SigningContext { NetworkType = NetworkType.Devnet, SignatureType = SignatureType.TransactionPublic }; _deltaIndexService = new DeltaIndexService(new InMemoryRepository <DeltaIndexDao, string>()); }
public ISignature Sign(ReadOnlySpan <byte> data, SigningContext signingContext) { var privateKey = GetPrivateKey(KeyRegistryTypes.DefaultKey); using var pooled = signingContext.SerializeToPooledBytes(); return(_cryptoContext.Sign(privateKey, data, pooled.Span)); }
public static ProtocolMessage ToSignedProtocolMessage(this IMessage proto, PeerId senderId, ISignature signature = default, SigningContext signingContext = default, ICorrelationId correlationId = default) { return(ToSignedProtocolMessage(proto, senderId, signature?.SignatureBytes, signingContext, correlationId)); }
public static ProtocolMessage Sign(this ProtocolMessage protocolMessage, byte[] signature = default, SigningContext signingContext = default) { var clone = protocolMessage.Clone(); clone.Signature = SignatureHelper.GetSignature(signature, signingContext); return(clone); }
public virtual void InspectContext(ProviderPhase phase, IOAuthContext context) { SigningContext signingContext = CreateSignatureContextForConsumer(context); if (!_signer.ValidateSignature(context, signingContext)) { throw Error.FailedToValidateSignature(context); } }
public SimpleRpcClient(IUserOutput userOutput, IPasswordRegistry passwordRegistry, X509Certificate2 certificate, ILogger logger, SigningContext signingContextProvider) { _logger = logger; _certificate = certificate; var fileSystem = new FileSystem(); var consolePasswordReader = new ConsolePasswordReader(userOutput, new ConsoleUserInput()); var passwordManager = new PasswordManager(consolePasswordReader, passwordRegistry); var cryptoContext = new FfiWrapper(); var hashProvider = new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("keccak-256")); var peerSettings = Substitute.For <IPeerSettings>(); peerSettings.NetworkType.Returns(signingContextProvider.NetworkType); var localKeyStore = new LocalKeyStore(passwordManager, cryptoContext, fileSystem, hashProvider, _logger); var keyRegistry = new KeyRegistry(); var keySigner = new KeySigner(localKeyStore, cryptoContext, keyRegistry); var memoryCacheOptions = new MemoryCacheOptions(); var memoryCache = new MemoryCache(memoryCacheOptions); var changeTokenProvider = new TtlChangeTokenProvider(10000); var messageCorrelationManager = new RpcMessageCorrelationManager(memoryCache, _logger, changeTokenProvider); var peerIdValidator = new PeerIdValidator(cryptoContext); var nodeRpcClientChannelFactory = new RpcClientChannelFactory(keySigner, messageCorrelationManager, peerIdValidator, peerSettings); var eventLoopGroupFactoryConfiguration = new EventLoopGroupFactoryConfiguration { TcpClientHandlerWorkerThreads = 4 }; var tcpClientEventLoopGroupFactory = new TcpClientEventLoopGroupFactory(eventLoopGroupFactoryConfiguration); var handlers = new List <IRpcResponseObserver> { new BroadcastRawTransactionResponseObserver(_logger), new GetVersionResponseObserver(_logger) }; _rpcClientFactory = new RpcClientFactory(nodeRpcClientChannelFactory, tcpClientEventLoopGroupFactory, handlers); //PeerId for RPC/TCP is currently redundant. var publicKey = keyRegistry.GetItemFromRegistry(KeyRegistryTypes.DefaultKey).GetPublicKey().Bytes; _senderPeerId = publicKey.BuildPeerIdFromPublicKey(IPAddress.Any, 1026); }
private ISignature Sign(byte[] data, SigningContext signingContext, KeyRegistryTypes keyIdentifier) { var privateKey = _keyRegistry.GetItemFromRegistry(keyIdentifier); if (privateKey == null && !TryPopulateRegistryFromKeyStore(keyIdentifier, out privateKey)) { throw new SignatureException("The signature cannot be created because the key does not exist"); } return(Sign(data, signingContext, privateKey)); }
private SHA1CryptoServiceProvider GenerateHash(SigningContext signingContext) { var sha1 = new SHA1CryptoServiceProvider(); byte[] dataBuffer = Encoding.ASCII.GetBytes(signingContext.SignatureBase); var cs = new CryptoStream(Stream.Null, sha1, CryptoStreamMode.Write); cs.Write(dataBuffer, 0, dataBuffer.Length); cs.Close(); return sha1; }
public void KeySigner_Cant_Verify_An_Incorrect_Signature() { var toSign = Encoding.UTF8.GetBytes("sign this plz"); var signature = _keySigner.Sign(toSign, new SigningContext()); var signingContext = new SigningContext { NetworkType = NetworkType.Mainnet, SignatureType = SignatureType.ProtocolRpc }; _keySigner.Verify(signature, toSign, signingContext).Should().BeFalse(); }
protected virtual SigningContext CreateSignatureContextForConsumer(IOAuthContext context) { var signingContext = new SigningContext { ConsumerSecret = _consumerStore.GetConsumerSecret(context) }; if (SignatureMethodRequiresCertificate(context.SignatureMethod)) { X509Certificate2 cert = _consumerStore.GetConsumerCertificate(context); signingContext.Algorithm = cert.PublicKey.Key; } return signingContext; }
SHA1CryptoServiceProvider GenerateHash(SigningContext signingContext) { var sha1 = new SHA1CryptoServiceProvider(); byte[] dataBuffer = Encoding.ASCII.GetBytes(signingContext.SignatureBase); var cs = new CryptoStream(Stream.Null, sha1, CryptoStreamMode.Write); cs.Write(dataBuffer, 0, dataBuffer.Length); cs.Close(); return(sha1); }
public void KeySigner_Can_Verify_A_Signature_With_Non_Default_Context() { var toSign = Encoding.UTF8.GetBytes("sign this plz"); var signingContext = new SigningContext { NetworkType = NetworkType.Mainnet, SignatureType = SignatureType.ProtocolRpc }; var signature = _keySigner.Sign(toSign, signingContext); _keySigner.Verify(signature, toSign, signingContext).Should().BeTrue(); }
protected virtual SigningContext CreateSignatureContextForConsumer(IOAuthContext context) { var signingContext = new SigningContext { ConsumerSecret = _consumerStore.GetConsumerSecret(context) }; if (SignatureMethodRequiresCertificate(context.SignatureMethod)) { signingContext.Algorithm = _consumerStore.GetConsumerPublicKey(context); } return(signingContext); }
SHA1 GenerateHash(SigningContext signingContext) { var sha1 = SHA1.Create();// new SHA1Managed(); //CryptoServiceProvider(); byte[] dataBuffer = Encoding.ASCII.GetBytes(signingContext.SignatureBase); using (var cs = new CryptoStream(Stream.Null, sha1, CryptoStreamMode.Write)) { cs.Write(dataBuffer, 0, dataBuffer.Length); cs.Close(); } return sha1; }
public void ValidateWithTrailingAmpersand_ForUrl() { string url = "http://demo.devdefined.com/OpenSocial/HelloWorld.aspx?oauth_nonce=c39f4e3e6c309988763eb8af85fcb74b&oauth_timestamp=1221992254&oauth_consumer_key=friendster.com&synd=friendster&container=default&opensocial_owner_id=82474146&opensocial_viewer_id=82474146&opensocial_app_id=52ae97f7aa8a7e7565dd40a4e00eb0f5&oauth_token=&xoauth_signature_publickey=http%3A%2F%2Fwww.fmodules.com%2Fpublic080813.crt&oauth_signature_method=RSA-SHA1&oauth_signature=PLOkRKwLLeJRZz18PsAVQgL5y9Rdf0AW5eicdT0xwauRe3bE2NTDFHoMsUtO6UMHEY0v9GRcKbvkgEWEGGtiGA%3D%3D&"; IOAuthContext context = new OAuthContextBuilder().FromUrl("GET", url); var signer = new OAuthContextSigner(); var signingContext = new SigningContext { Algorithm = FriendsterCertificate.PublicKey.Key }; Assert.True(signer.ValidateSignature(context, signingContext)); }
public bool ValidateSignature(OAuthContext authContext, SigningContext signingContext) { if (signingContext.Algorithm == null) throw Error.AlgorithmPropertyNotSetOnSigningContext(); SHA1CryptoServiceProvider sha1 = GenerateHash(signingContext); var deformatter = new RSAPKCS1SignatureDeformatter(signingContext.Algorithm); deformatter.SetHashAlgorithm("MD5"); byte[] signature = Convert.FromBase64String(authContext.Signature); return deformatter.VerifySignature(sha1, signature); }
private string GenerateSignature(OAuthContext authContext, SigningContext signingContext) { if (signingContext.Algorithm == null) throw Error.AlgorithmPropertyNotSetOnSigningContext(); SHA1CryptoServiceProvider sha1 = GenerateHash(signingContext); var formatter = new RSAPKCS1SignatureFormatter(signingContext.Algorithm); formatter.SetHashAlgorithm("MD5"); byte[] signature = formatter.CreateSignature(sha1); return Convert.ToBase64String(signature); }
public bool ValidateSignature(IOAuthContext authContext, SigningContext signingContext) { foreach (var signatureBase in authContext.GenerateSignatureBase()) { signingContext.SignatureBase = signatureBase; if (FindImplementationForAuthContext(authContext).ValidateSignature(authContext, signingContext)) { return(true); } } return(false); }
public void Init() { _fakeContext = Substitute.For <IChannelHandlerContext>(); _keySigner = Substitute.For <FakeKeySigner>(); _signingContext = DevNetPeerSigningContext.Instance; var signatureBytes = ByteUtil.GenerateRandomByteArray(new FfiWrapper().SignatureLength); var publicKeyBytes = ByteUtil.GenerateRandomByteArray(new FfiWrapper().PublicKeyLength); var peerId = PeerIdHelper.GetPeerId(publicKeyBytes); _protocolMessageSigned = new PingRequest() .ToSignedProtocolMessage(peerId, signatureBytes, _signingContext) .ToSignedProtocolMessage(peerId, signatureBytes, _signingContext); }
static string GenerateSignature(IToken authContext, SigningContext signingContext) { string consumerSecret = (signingContext.ConsumerSecret != null) ? UriUtility.UrlEncode(signingContext.ConsumerSecret) : ""; string tokenSecret = (authContext.TokenSecret != null) ? UriUtility.UrlEncode(authContext.TokenSecret) : null; string hashSource = string.Format("{0}&{1}", consumerSecret, tokenSecret); var hashAlgorithm = new HMACSHA1 {Key = Encoding.ASCII.GetBytes(hashSource)}; return ComputeHash(hashAlgorithm, signingContext.SignatureBase); }
public PeerClientChannelFactory(IKeySigner keySigner, IPeerMessageCorrelationManager correlationManager, IPeerIdValidator peerIdValidator, IPeerSettings peerSettings, IScheduler scheduler = null) { _scheduler = scheduler ?? Scheduler.Default; _keySigner = keySigner; _correlationManager = correlationManager; _peerIdValidator = peerIdValidator; _signingContext = new SigningContext { NetworkType = peerSettings.NetworkType, SignatureType = SignatureType.ProtocolPeer }; }
public void TestVerifyingForMessagesMethodEquivalence() { var privateKey = _wrapper.GeneratePrivateKey(); var message1 = new PublicEntry {Nonce = 123}; var context = new SigningContext {NetworkType = NetworkType.Mainnet}; var signature = _wrapper.Sign(privateKey, message1.ToByteArray(), context.ToByteArray()); var expected = _wrapper.Verify(signature, message1.ToByteArray(), context.ToByteArray()); var actual = _wrapper.Verify(signature, message1, context); actual.Should().Be(expected); }
private static Signature GeneratePublicEntrySignature(PublicEntry publicEntry, ICryptoContext cryptoContext, IPrivateKey privateKey, SigningContext context) { publicEntry.Signature = null; var signatureBytes = cryptoContext.Sign(privateKey, publicEntry.ToByteArray(), context.ToByteArray()).SignatureBytes; return(new Signature { RawBytes = signatureBytes.ToByteString(), SigningContext = context }); }
public static ProtocolMessage ToSignedProtocolMessage(this IMessage proto, PeerId senderId = default, byte[] signature = default, SigningContext signingContext = default, ICorrelationId correlationId = default) { var peerId = senderId ?? PeerIdHelper.GetPeerId("sender"); var protocolMessage = proto.ToProtocolMessage(peerId, correlationId ?? CorrelationId.GenerateCorrelationId()); var newSignature = SignatureHelper.GetSignature(signature, signingContext); protocolMessage.Signature = newSignature; return(protocolMessage); }
public static PublicEntry Sign(this PublicEntry publicEntry, ICryptoContext cryptoContext, IPrivateKey privateKey, SigningContext context) { var clone = publicEntry.Clone(); if (publicEntry.Signature?.RawBytes.Length == cryptoContext.SignatureLength) { Logger.Debug("The transaction was already signed, returning a clone."); return(clone); } clone.Signature = GeneratePublicEntrySignature(clone, cryptoContext, privateKey, context); return(clone); }
public TokenBase GrantRequestToken(OAuthContext context) { SigningContext signingContext = CreateSignatureContextForAuthContext(context); if (!_signer.ValidateSignature(context, signingContext)) { throw Error.FailedToValidateSignature(); } return(new TokenBase { ConsumerKey = context.ConsumerKey, Token = "requestkey", TokenSecret = "requestsecret" }); }
static string GenerateSignature(IToken authContext, SigningContext signingContext) { string consumerSecret = (signingContext.ConsumerSecret != null) ? UriUtility.UrlEncode(signingContext.ConsumerSecret) : ""; string tokenSecret = (authContext.TokenSecret != null) ? UriUtility.UrlEncode(authContext.TokenSecret) : null; string hashSource = string.Format("{0}&{1}", consumerSecret, tokenSecret); var hashAlgorithm = new HMACSHA1 { Key = Encoding.ASCII.GetBytes(hashSource) }; return(ComputeHash(hashAlgorithm, signingContext.SignatureBase)); }
private bool IsOAuthValid(string secret) { try { var context = new OAuthContextBuilder().FromHttpRequest(Request); IOAuthContextSigner signer = new OAuthContextSigner(); SigningContext signingContext = new SigningContext { ConsumerSecret = secret }; return(signer.ValidateSignature(context, signingContext)); } catch (OAuthException) { return(false); } }
public bool ValidateSignature(IOAuthContext authContext, SigningContext signingContext) { return authContext.Signature.EqualsInConstantTime(GenerateSignature(authContext, signingContext)); }
public void SignContext(IOAuthContext authContext, SigningContext signingContext) { authContext.Signature = GenerateSignature(authContext, signingContext); }
public bool ValidateSignature(IOAuthContext authContext, SigningContext signingContext) { return (authContext.Signature == GenerateSignature(authContext, signingContext)); }
public bool ValidateSignature(IOAuthContext authContext, SigningContext signingContext) { signingContext.SignatureBase = authContext.GenerateSignatureBase(); return FindImplementationForAuthContext(authContext).ValidateSignature(authContext, signingContext); }
string GenerateSignature(IOAuthContext authContext, SigningContext signingContext) { return string.Format("{0}&{1}", signingContext.ConsumerSecret, authContext.TokenSecret); }
public void SignContext(IOAuthContext authContext, SigningContext signingContext) { signingContext.SignatureBase = authContext.GenerateSignatureBase(); FindImplementationForAuthContext(authContext).SignContext(authContext, signingContext); }
static string GenerateSignature(IToken authContext, SigningContext signingContext) { return UriUtility.UrlEncode(string.Format("{0}&{1}", signingContext.ConsumerSecret, authContext.TokenSecret)); }