23 Kasım 2022

CIDR (Classless Inter-Domain Routing) Notation


{8Bits}. {8Bits}. {8Bits}. {8Bits} / {Allocated Bits}

00000000 = 0

11111111 = 255

 Example: 102.123.149.240 / 24

 

Allocated Bits To Address         Allocated For Range

102.123.149                                .240 / 24                       => 102.123.149.000 - 102.123.149.255

102.123                                       .149.240 / 16                => 102.123.000.000 - 102.123.255.255

102.123                                       .149.240 / 20                => 102.123.144.000 - 102.123.159.255 

 

Algorithm For 102.123.149/20

102.123 => 8+8 => 16 Bits Used Remained 4

149 => 1 0 0 1 0 1 0 1 => 1 + 4 + 16 +128 

First 4 are allocated we will use remained ones

1 0 0 1 0 0 0 0  to 1 0 0 1 1 1 1 1

=> 128+16 to 128+16+8+4+2+1

=> 144 to 159

Thus =>

102.123.144.000 - 102.123.159.255  

 

3 Kasım 2022

RSA C#

  internal class Program

    {

        static void Main(string[] args)

        {

            

            IRSAEncryption rsa = new RSAEncryption();

            // Use only one time for generating keys

            //rsa.GenerateKeys("mx.pub","px.pem");


            var text = "Fıstıkçı Şahap 2";

            var encryptedText = rsa.Encrypt(text, "mx.pub");

            Console.WriteLine($"Encrpyted: {encryptedText}");

            //var decryptedText = rsa.Decrypt(encryptedText, "mx.pem");

            //Console.WriteLine($"Decrypted: {decryptedText}");



        }


    }


public interface IRSAEncryption

    {

        public void GenerateKeys(string pathPublicKey, string pathPrivateKey);

        public string Encrypt(string plainText, string pathPublicKey);

        public string Decrypt(string encrpyedText, string pathPrivateKey);

    }


public class RSAEncryption : IRSAEncryption

    {

        private string ByteArrayToString(byte[] bytes)

        {

            var sb = new StringBuilder(bytes.Length * 2);

            foreach (var b in bytes)

            {

                sb.AppendFormat("{0:x2}", b);

            }

            return sb.ToString();

        }


        public static byte[] StringToByteArray(String hex)

        {

            int NumberChars = hex.Length;

            byte[] bytes = new byte[NumberChars / 2];

            for (int i = 0; i < NumberChars; i += 2)

                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);

            return bytes;

        }


        private RSAParameters ImportKey(string path)

        {

            var serializer = new XmlSerializer(typeof(RSAParameters));

            using (var fs = new FileStream(path, FileMode.Open))

            {

                return (RSAParameters)serializer.Deserialize(fs);

            }

        }


        private void ExportKey(RSAParameters parameters, string path)

        {

            var serializer = new XmlSerializer(typeof(RSAParameters));

            using (var fs = new FileStream(path, FileMode.CreateNew))

            using (var sw = new StreamWriter(fs, Encoding.UTF8))

            {

                serializer.Serialize(sw, parameters);

            }

        }



        public string Decrypt(string encrpyedText, string pathPrivateKey)

        {

            using (var rsa = new RSACryptoServiceProvider())

            {

                var pubKey = ImportKey(pathPrivateKey);

                rsa.ImportParameters(pubKey);

                var data = StringToByteArray(encrpyedText);

                var cypher = rsa.Decrypt(data, false);

                return Encoding.UTF8.GetString(cypher);

            }

        }


        public string Encrypt(string plainText, string pathPublicKey)

        {

            using (var rsa = new RSACryptoServiceProvider())

            {

                var pubKey = ImportKey(pathPublicKey);

                rsa.ImportParameters(pubKey);

                var data = Encoding.UTF8.GetBytes(plainText);

                var cypher = rsa.Encrypt(data, false);

                return ByteArrayToString(cypher);

            }

        }


        public void GenerateKeys(string pathPublicKey, string pathPrivateKey)

        {

            using (var rsa = new RSACryptoServiceProvider(2048))

            {

                var pem = rsa.ExportParameters(true);

                var pub = rsa.ExportParameters(false);

                ExportKey(pem, "mx.pem");

                ExportKey(pub, "mx.pub");

            }

        }

    }

15 Ekim 2022

PostgreSql PgAdmin Docker Çalıştırma

 docker-compose.yaml dosyası aşağıdaki gibidir.

services:
  pgadmin:
    environment:
      PGADMIN_DEFAULT_EMAIL: PGAdminMail@mail.com
      PGADMIN_DEFAULT_PASSWORD: PGAdminPassword
    image: dpage/pgadmin4
    ports:
    - published: 5080
      target: 80
  postgres:
    environment:
      POSTGRES_DB: PostgresDefaultDB
      POSTGRES_PASSWORD: PostgresDefaultPassword
      POSTGRES_USER: PostgresDefaultUsername
    image: postgres
    ports:
    - published: 5432
      target: 5432
version: '3.9'

 

docker-compose config ile config kontrol edilir hata varsa güncel bilgilere göre google dan aratıp düzeltin.

docker compose up --build ile çalıştırılır

 

http://localhost:5080/ adresinden yaml da yazdığınız kullanıcı adı ve şifre ile PG Amin'e giriş yapınız.

terminal de
docker ps 

yazarak postgres in ContainerID sini alalım benim örnekte  44b778e8e612

daha sonra docker inspect 44b yazarak işlemin IP adresini bulalım

Benim örnek te

"IPAddress": "172.19.0.3",

IP adres ve YAML a girilen bilgilerdeki kullanıcı adı şifre ile Postgres e bağlanabilirsiniz.




19 Eylül 2022

Types Of Cloud Services and Types of Clouds

 

Types of Cloud Services

IaaS

Infrastructure as a Service

The cloud provides the underlying platforms

  • Compute

  • Networking

  • Storage

The client handles and is responsible for all the rest. In other words, the cloud provides minimum infrastructure and we the clients of cloud are expected to take care of all the rest.

The most common example of IaaS is Virtual Machines.

The clouds provide the host machine, networking and disks.

The client creates the virtual machine, installs software on it, patches it, maintains it etc. So it is the responsibility of the client to make sure that the virtual machine is up and running, and the cloud has nothing to do with it.



PaaS

Platform as a Service

The cloud provides a platform for running apps.

Including Compute, networking, storage, runtime environment, scaling redundancy, security, updates, patching, maintenance etc.

The client just needs to bring the code to run

As a developer we just write the codes and upload it to cloud and the cloud takes care of all the rest.

Most common examples: Web Apps

The cloud provides the runtime for running web apps

The client uploads the code, and it just runs

The client has no access to the underlying virtual machines





SaaS

Software as a Service

A software running completely in the cloud.

The user doesn’t need to install anything on premises or on his machine

The provider of the software takes care of updates, patches, redundancy, scalability etc.

Common Examples: Office 365, SalesForce

We have no idea what is the infrastructure that Office 365 and Salesforce are running on

What are the virtual machines, what language are they developed in, what is a database and so on.



Types of Clouds

Public Cloud

The cloud is set up in the public network

Managed by large companies

Accessible through the internet

Available to all clients and users

Clients have no access to underlying infrastructure

Examples: AWS, Azure, Google Clouds, IBM Clouds



Private Cloud

A cloud set up in an organization’s premises

Managed by the organization’s IT team

Accessible only in the organization’s network

Available to users from the organizations

Uses private cloud infrastructure and engines

Contains a subset of the public cloud’s capabilities

Examples VMWare Cloud, Red Hat OpenShift Container Platform, Azure Stack

Used for privacy and security issues





Hybrid Cloud

A cloud set up in organization’s premises but also connected to the public cloud

Workload can be separated between the two clouds. For instance, sensitive data in the organization’s premises, public data in the public cloud.

So, for example, the organization can decide that the usernames, passwords and credit cards of its users will be stored inside the organization’s premises, but for example the professional profile of its users, such as the ones in LinkedIn will be stored in the public cloud.

Examples: Azure Arc, AWS Outposts

23 Mayıs 2022

Python PyJWT Equivelent in C#

using System.Security.Cryptography; using System.Text; public class PyJwt { public static string Encode(string clientId, string secret) { var algorithm = "{\"typ\":\"JWT\",\"alg\":\"HS256\"}"; var data = "{\"clientID\":\"" + clientId + "\"}"; var header = Convert.ToBase64String(Encoding.UTF8.GetBytes(algorithm)); var payload = Convert.ToBase64String(Encoding.UTF8.GetBytes(data)); var key = Convert.ToBase64String(Encoding.UTF8.GetBytes(secret)); string signature = string.Empty; using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key))) { var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes($"{header}.{payload}")); signature = Convert.ToBase64String(hash) .Replace("+", "-") .Replace("/", "_") .Replace("=", ""); } return $"{header}.{payload}.{signature}"; } }

31 Mart 2022

Online Base64 Encoder





24 Mart 2022

SignedString Sınıfı

 Dışarıya açık dosya paylaşmada URL i zaman bazlı kısıtlamak için oluşturulmuş kod parçaları.

EncryptTool.cs

using System;

using System.Security.Cryptography;

using System.Text;


namespace SampleSigner

{

    public static class EncryptTool 

    {

        public static byte[] EncryptSha5126(string plainText)

        {

            if (string.IsNullOrEmpty(plainText))

            {

                throw new ArgumentNullException(nameof(plainText));


            }

            using (var sha = SHA512.Create())

                return sha.ComputeHash(Encoding.UTF8.GetBytes(plainText));

        }


        /// <summary>

        /// 

        /// </summary>

        /// <param name="plainText"> Not Null</param>

        /// <param name="key">byte[64] random bytes</param>

        /// <returns></returns>

        public static byte[] HmacSha256(string plainText, byte[] key)

        {

            if (key == null)

                throw new ArgumentNullException(nameof(key));

            if (key.Length != 64)

                throw new ArgumentException("key.length must be 64");

            if (string.IsNullOrEmpty(plainText))

                throw new ArgumentNullException(nameof(plainText));


            using (HMACSHA256 hmac = new HMACSHA256(key))

            {

                return hmac.ComputeHash(Encoding.UTF8.GetBytes(plainText));

            }

        } 

    }

}



// SignedStringSettings.cs

using System;

namespace SampleSigner
{
    public class SignedStringSettings
    {
        /// <summary>
        /// Key olarak proje her başlatıldığında key değişsin diye dinamik guid üretilmiştir.
        /// İsteyen gömülü key kullanabilir. 
        /// Ben dosya paylaşım süresini uzun tutmayacağım için Guid benim için sorun değil
        /// </summary>
        private SignedStringSettings()
            :this(Guid.NewGuid().ToString())
        {

        }
        private SignedStringSettings(string key)
        {
            var bytes = EncryptTool.EncryptSha5126(key);
            byte[] data = new byte[64];
            Array.Copy(bytes, 0, data, 0, 64);
            Key = data;
        }

        public static readonly Lazy<SignedStringSettings> _instance
            = new Lazy<SignedStringSettings>(() => new SignedStringSettings());

        public static SignedStringSettings Instance => _instance.Value;

        public byte[] Key { get; private set; }

    }
}


// SignedString.cs

using System;
using System.Security.Cryptography;
using System.Text;

namespace SampleSigner
{
    public class SignedString
    {
        private string _text { get; set; }
        private long _validUntil { get; set; }

        private SignedString(string text, DateTimeOffset validUntil)
        {
            _validUntil = validUntil.ToUnixTimeSeconds();
            _text = Sign(text, _validUntil);
        }

        private SignedString(string text)
        {
            _text = text;
        }



        public static SignedString CreateNew(string text, DateTimeOffset to)
        {
            return new SignedString(text, to);
        }
        public static SignedString CreateNew(string text, TimeSpan time)
        {
            return new SignedString(text, DateTimeOffset.UtcNow.Add(time));
        }

        public static SignedString Load(string text)
        {
            return new SignedString(text);
        }



        private string Sign(string text, long validUntil)
        {
            var plainText = Convert.ToBase64String(Encoding.UTF8.GetBytes(text));
            plainText += $".{validUntil}";
            var computedHash = EncryptTool.HmacSha256(plainText, SignedStringSettings.Instance.Key);
            return $"{plainText}.{Convert.ToBase64String(computedHash)}";
        }

        private bool Verify(string signedText, byte[] key)
        {
            if (string.IsNullOrWhiteSpace(signedText))
                throw new ArgumentNullException(nameof(signedText));

            var parts = signedText.Split('.');

            if (parts.Length != 3
                || string.IsNullOrWhiteSpace(parts[0])
                || string.IsNullOrWhiteSpace(parts[1])
                || string.IsNullOrWhiteSpace(parts[2]))
                throw new ArgumentException("Invalid String");

            
           

            byte[] computedBytes = null;
            using (HMACSHA256 hmac = new HMACSHA256(key))
            {
                var checkText = signedText.Substring(0, signedText.LastIndexOf("."));
                computedBytes = EncryptTool.HmacSha256(checkText, SignedStringSettings.Instance.Key);
            }
            var signBytes = Convert.FromBase64String(parts[2]);

            if (computedBytes == null
                || (computedBytes.Length != signBytes.Length))
                return false;

            for (int i = 0; i < computedBytes.Length; i++)
            {
                if (computedBytes[i] != signBytes[i])
                {
                    return false;
                };
            }
            var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
            var until = Convert.ToInt64(parts[1]);

            return now < until;
        }

        public override string ToString()
        {
            return _text;
        }

        public bool IsValid => Verify(_text, SignedStringSettings.Instance.Key);

        public string ToUnsignedString()
        {
            if (IsValid)
            {
                var parts = _text.Split(".");
                var byteText = Convert.FromBase64String(parts[0]);
                return Encoding.UTF8.GetString(byteText);
            }
            else return string.Empty;
        }
    }
}

// Program.cs

using System;
using System.Threading;

namespace SampleSigner
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var plainUrl = "https://www.muharrembarkin.com/";
            var sample = SignedString.CreateNew(plainUrl, TimeSpan.FromSeconds(5));
            // Url is valid 5 seconds
            var signedUrl = sample.ToString();
            Console.WriteLine($"Signed Url: {sample}");

            Console.WriteLine();

            //  1 second later  valid
            Thread.Sleep(1000);
            var sample2 = SignedString.Load(signedUrl);
            Console.WriteLine($"Is Valid after 1 seconds: {sample2.IsValid}");
            Console.WriteLine();
            Console.WriteLine("1 Second later Unsigned Url: " + sample2.ToUnsignedString());
            Console.WriteLine();
            //  6 second later not valid
            Thread.Sleep(5000);
            Console.WriteLine($"Is Valid after 6 seconds: {sample2.IsValid}");
            Console.WriteLine();
            Console.WriteLine("6 Second later Unsigned Url: " + sample2.ToUnsignedString());

            Console.WriteLine();
            var sample3 = SignedString.CreateNew(plainUrl, TimeSpan.FromSeconds(30));
            Console.WriteLine($"Signed Url: {sample3}");
            Console.WriteLine();
            Console.WriteLine("lets change one character of signed url");
            var signedUrl2 = sample3.ToString();
            signedUrl2 = signedUrl2.Substring(0, signedUrl2.Length - 1) + "a";
            Console.WriteLine("Changed Url: " + signedUrl2);
            Console.WriteLine();
            var sample4 = SignedString.Load(signedUrl2);
            Console.WriteLine($"Is valid changed url: {sample4.IsValid}");
            Console.WriteLine();
            Console.WriteLine($"UnsignedString changed url: {sample4.ToUnsignedString()}");
            Console.WriteLine();
            Console.WriteLine("Re test original url");
            var sample5 = SignedString.Load(sample3.ToString());
            Console.WriteLine($"IsValid: {sample5.IsValid}");
            Console.WriteLine($"UnsignedString: {sample5.ToUnsignedString()}");

        }
    }
}

30 Aralık 2021

HTML Loader Vanilla JS

//amagiloader.js 


const AmagiLoader = {

    __loader: null,

    show: function () {


        if (this.__loader == null) {

            var divContainer = document.createElement('div');

            divContainer.style.position = 'absolute';

            divContainer.style.left = '0';

            divContainer.style.top = '0';

            divContainer.style.width = '100vw';

            divContainer.style.height = '100vh';

            divContainer.style.backgroundColor = 'rgba(250, 250, 250, 0.80)';


            var div = document.createElement('div');

            div.style.position = 'absolute';

            div.style.left = '50%';

            div.style.top = '50%';

            div.style.zIndex = '9999';

            div.style.height = '64px';

            div.style.width = '64px';

            div.style.margin = '-76px 0 0 -76px';

            div.style.border = '8px solid #e1e1e1';

            div.style.borderRadius = '50%';

            div.style.borderTop = '8px solid #F36E21';

            div.animate([

                { transform: 'rotate(0deg)' },

                { transform: 'rotate(360deg)' }

              ], {

                duration: 2000,

                iterations: Infinity

              });

            divContainer.appendChild(div);

            this.__loader = divContainer

            document.body.appendChild(this.__loader);

        }

        this.__loader.style.display="";

    },

    hide: function(){

        if(this.__loader!=null)

        {

            this.__loader.style.display="none";

        }

    }

}



Usage //index.html


<html>

<head></head>

<body>

<p>asdsadasd

asdsadasdd

asdasdasd</p>


<script src="amagiloader.js"></script>

<script>

 AmagiLoader.show();

 setTimeout(() => {

    AmagiLoader.hide();

 }, 3000);

</script>


</body>

</html>

22 Kasım 2021

PostgreSQL Sequence Set


ERROR: duplicate key value violates unique constraint "pkey"

DETAIL: Key (id)=(1503) already exists. SQL state: 23505



SELECT MAX(the_primary_key) FROM the_table;   
SELECT nextval('the_primary_key_sequence');


Get Sequence Name

 select pg_get_serial_sequence('tableName','columnName')


Set Sequence Name
SELECT setval('the_primary_key_sequence', (SELECT MAX(the_primary_key) FROM the_table)+1);

VEYA
SELECT setval(pg_get_serial_sequence('tableName','columnName'), (SELECT MAX(columnName) FROM tableName)+1);




5 Kasım 2021

PHP - .NET Uyumlu AES Şifreleme

 C#

using System.Security.Cryptography;

using System.Text;


namespace ConsoleApp16

{

    public class Program

    {

        public static void Main()

        {

            var plain = "Lorem Ipsum";

            var encryptSettings = new EncryptSettings();

            var encryptTools = new EncryptTools(encryptSettings);

            var encrypted = encryptTools.AesEncrypt(plain);

            Console.WriteLine("Encrypted");

            Console.WriteLine(encrypted);

            Console.WriteLine();

            Console.WriteLine("Decrypted");

            var text = encryptTools.AesDecrypt(encrypted);

            Console.WriteLine(text);

        }

    }

    public class EncryptSettings

    {

        public string Key { get; set; }


        public EncryptSettings()

        {

            Key = "passwordstring";

        }

    }


    public class EncryptTools

    {

        private readonly EncryptSettings encryptSettings;


        public EncryptTools(EncryptSettings encryptSettings)

        {

            this.encryptSettings = encryptSettings;

        }


        private byte[] key => Sha256Byte(encryptSettings.Key);

        private byte[] iv => new byte[16] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };


        public string AesEncrypt(string plainText)

        {

            if (plainText == null || plainText.Length <= 0)

                throw new ArgumentNullException("plainText");

            if (key == null || key.Length <= 0)

                throw new ArgumentNullException("Key");

            if (iv == null || iv.Length <= 0)

                throw new ArgumentNullException("IV");

            byte[] encrypted;


            using (var aes = Aes.Create())

            {

                aes.Mode = CipherMode.CBC;

                aes.Key = key;

                aes.IV = iv;


                using (var ms = new MemoryStream())

                {

                    using (ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV))

                    using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))

                    using (StreamWriter swEncrypt = new StreamWriter(cs))

                    {

                        swEncrypt.Write(plainText);

                    }

                    encrypted = ms.ToArray();

                }

            }

            return Convert.ToBase64String(encrypted);

        }


        public string AesDecrypt(string encryptedText)

        {

            var cipherText = Convert.FromBase64String(encryptedText);


            if (cipherText == null || cipherText.Length <= 0)

                throw new ArgumentNullException("cipherText");

            if (key == null || key.Length <= 0)

                throw new ArgumentNullException("Key");

            if (iv == null || iv.Length <= 0)

                throw new ArgumentNullException("IV");


            string plaintext = null;


            using (Aes aes = Aes.Create())

            {

                aes.Mode = CipherMode.CBC;

                aes.Key = key;

                aes.IV = iv;


                using (MemoryStream msDecrypt = new MemoryStream(cipherText))

                using (ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV))

                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))

                using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                {

                    plaintext = srDecrypt.ReadToEnd();

                }

            }


            return plaintext;

        }


        public byte[] Sha256Byte(string plainText)

        {

            byte[] bytes = null;

            using (SHA256 sha256Hash = SHA256.Create())

            {

                bytes = sha256Hash.ComputeHash(Encoding.ASCII.GetBytes(plainText));

            }

            return bytes;

        }

    }


}

PHP

<?php

function encrypt_decrypt($string, $action = 'encrypt')
{
$encrypt_method = "aes-256-cbc";
$secret_key = 'passwordstring'; // user define private key
$key = substr(hash('sha256', $secret_key, true), 0, 32);
$iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);
if ($action == 'encrypt') {
$output = openssl_encrypt($string, $encrypt_method, $key, OPENSSL_RAW_DATA, $iv);
$output = base64_encode($output);
} else if ($action == 'decrypt') {
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, OPENSSL_RAW_DATA, $iv);
}
return $output;
}
echo encrypt_decrypt('CSBx7hQRszpDKM9Vfxy8qQ==', 'decrypt');

?>