예제 #1
0
        /// <summary>
        ///   Computes the message that accepts the handshake.
        /// </summary>
        /// <remark>
        ///   Here the server computes a signature of the network key, the
        ///   signature of the long term client's public key and a sha 256 of
        ///   the shared ab secret. This is signed with the server's long term
        ///   private key.
        ///
        ///   This signature is encrypted using a sha 256 of the network key
        ///   and all of the derived secrets.
        /// </remark>
        /// <returns>
        ///   A byte array of length 80 consisting of the message.
        /// </returns>
        public byte[] Accept()
        {
            var detached_signature = PublicKeyAuth.SignDetached(
                Utils.Concat(
                    _network_key,
                    detached_signature_A,
                    _longterm_client_pk,
                    CryptoHash.Sha256(_shared_ab)
                    ),
                _longterm_server_keypair.PrivateKey
                );

            // A nonce consisting of 24 zeros
            var nonce = new byte[NONCE_SIZE];

            nonce.Initialize();

            var key = CryptoHash.Sha256(
                Utils.Concat(_network_key, _shared_ab, _shared_aB, _shared_Ab)
                );

            var msg = SecretBox.Create(detached_signature, nonce, key);

            return(msg);
        }
예제 #2
0
        /// <summary>
        ///   Crafts the client Authenticate message
        /// </summary>
        /// <remark>
        ///   Consists of a signature of the network identifier, the server's
        ///   long term public key and a sha 256 of the derived secret ab,
        ///   concatenated with the client's long term public key. All
        ///   encrypted using the network identifier and the derived secrets
        ///   ab and aB.
        ///
        ///   This sets the object's <see cref="detached_signature_A"/>
        /// </remark>
        /// <returns>
        ///   The client Authenticate message
        /// </returns>
        public byte[] Authenticate()
        {
            var hash_ab = CryptoHash.Sha256(this._shared_ab);

            // Concatenate the network identifier, the server's public key and
            // the hash of the derived secret.
            var to_sign = Utils.Concat(
                _network_key, _longterm_server_pk, hash_ab
                );

            // Sign the first portion of the message and save it in the object
            // state for later use in the server accept verification.
            detached_signature_A = PublicKeyAuth.SignDetached(
                to_sign, _longterm_client_keypair.PrivateKey
                );

            // Create the plaintext message
            var plaintext = Utils.Concat(
                detached_signature_A, _longterm_client_keypair.PublicKey
                );

            // Create the key from the network key and the shared secrets
            var box_key = Utils.Concat(
                _network_key, _shared_ab, _shared_aB
                );

            // A nonce consisting of 24 zeros
            var nonce = new byte[NONCE_SIZE];

            nonce.Initialize();

            var msg = SecretBox.Create(plaintext, nonce, CryptoHash.Sha256(box_key));

            return(msg);
        }
        protected override void OnBeforeRequest(RestClient client, IRestRequest request, Proxy proxy = null)
        {
            request.AddHeader("X-Sign-Date", DateTimeOffset.Now.ToUnixTimeSeconds().ToString());

            var patchString = request.Resource;

            var qParamas = request.Parameters
                           .Where(w => w.Type == ParameterType.QueryString)
                           .Select(s => s.ToString())
                           .ToList();

            var bParamas = request.Parameters
                           .Where(w => w.Type == ParameterType.RequestBody)
                           .Select(s => s.ToString())
                           .ToList();

            if (qParamas.Any())
            {
                patchString += $"?{string.Join("&", qParamas.Select(s => s.ToString()))}";
            }

            if (bParamas.Any())
            {
                patchString += JsonConvert.SerializeObject(request.Parameters
                                                           .Where(w => w.Type == ParameterType.RequestBody)
                                                           .ToDictionary(d => d.Name, d => d.Value));
            }

            var sigString = request.Method + patchString + DateTimeOffset.Now.ToUnixTimeSeconds();
            var sig       = Utilities.BinaryToHex(PublicKeyAuth.SignDetached(sigString, Utilities.HexToBinary(_privateKey)));

            request.AddHeader("X-Request-Sign", $"dmar ed25519 {sig}");
        }
예제 #4
0
 /// <summary>
 /// Generated a detached signature from the provided data
 /// </summary>
 /// <param name="data">String payload to sign</param>
 /// <returns>byte[] of the detached signature</returns>
 public byte[] Sign(String data)
 {
     try {
         return(PublicKeyAuth.SignDetached(data, this.signatureSecretKey));
     } catch (Exception e) {
         throw new SigningException("Unable to sign message", e);
     }
 }
예제 #5
0
        public void SimpleAuthDetachedTest()
        {
            var expected = Utilities.HexToBinary("8d5436accbe258a6b252c1140f38d7b8dc6196619945818b72512b6a8019d86dfeeb56f40c4d4b983d97dfeed37948527256c3567d6b253757fcfb32bef56f0b");
            var actual   = PublicKeyAuth.SignDetached(Encoding.UTF8.GetBytes("Adam Caudill"),
                                                      Utilities.HexToBinary("89dff97c131434c11809c3341510ce63c85e851d3ba62e2f810016bbc67d35144ffda13c11d61d2b9568e54bec06ea59368e84874883087645e64e5e9653422e"));

            CollectionAssert.AreEqual(expected, actual);
        }
예제 #6
0
        /// <summary>
        /// Create static proof for disco peer
        /// </summary>
        /// <remarks>
        /// StaticPublicKeyProof sometimes required
        /// for peers that are sending their static public key at some
        /// point during the handshake
        /// </remarks>
        /// <param name="sodiumPrivateKey"></param>
        /// <param name="publicKey"></param>
        /// <returns>Static proof as byte array</returns>
        public static byte[] CreateStaticPublicKeyProof(byte[] sodiumPrivateKey, byte[] publicKey)
        {
            if (publicKey.Length != Asymmetric.DhLen)
            {
                throw new Exception($"disco: length of public key passed is incorrect (should be {Asymmetric.DhLen})");
            }

            return(PublicKeyAuth.SignDetached(publicKey, sodiumPrivateKey));
        }
예제 #7
0
        public void GenerateKeyVerifySignedDataTest()
        {
            var actual = PublicKeyAuth.GenerateKeyPair();

            byte[] randomArray = SodiumCore.GetRandomBytes(255);
            var    sign        = PublicKeyAuth.SignDetached(randomArray, actual.PrivateKey);

            Assert.IsTrue(PublicKeyAuth.VerifyDetached(sign, randomArray, actual.PublicKey));
        }
예제 #8
0
파일: Transaction.cs 프로젝트: velas/NVelas
        /// <summary>
        /// </summary>
        /// <param name="unspents"></param>
        /// <param name="amount"></param>
        /// <param name="key"></param>
        /// <param name="fromAddress"></param>
        /// <param name="to"></param>
        /// <param name="commission"></param>
        public Transaction(PreviousOutput[] unspents, ulong amount, Hd key, string fromAddress, string to, ulong commission)
        {
            ulong totalin = 0;

            foreach (var previousOutput in unspents)
            {
                totalin += previousOutput.Value;
            }

            var index = 0;

            TxIns = new List <TxIn>();

            // Comission
            TxOuts = new List <TxOut>();
            TxOuts.Add(new TxOut
            {
                Index           = index++,
                PublicKeyScript = "",
                Value           = commission
            });

            // Dest address
            TxOuts.Add(new TxOut
            {
                Index           = index++,
                PublicKeyScript = Base58.Bitcoin.Decode(to).ToArray().ToHex(),
                Value           = amount
            });

            var change = totalin - amount - commission;

            if (change > 0)
            {
                // My address
                TxOuts.Add(new TxOut
                {
                    Index           = index,
                    PublicKeyScript = Base58.Bitcoin.Decode(fromAddress).ToArray().ToHex(),
                    Value           = change
                });
            }

            foreach (var previousOutput in unspents)
            {
                var sigMsg = MsgForSign(previousOutput.Hash, previousOutput.Index);
                var sig    = PublicKeyAuth.SignDetached(sigMsg, key.PrivateKey);
                TxIns.Add(new TxIn
                {
                    PublicKey      = key.PublicKey,
                    Sequence       = 1,
                    PreviousOutput = previousOutput,
                    SigScript      = sig.ToHex()
                });
            }
        }
        public string SignJson(JObject jsonObject)
        {
            jsonObject.Remove("signatures");
            jsonObject.Remove("unsigned");
            var ordered = SortPropertiesAlphabetically(jsonObject);
            var json    = JsonConvert.SerializeObject(ordered, CanonicalSettings);
            var b64     = Convert.ToBase64String(PublicKeyAuth.SignDetached(json, Pair.PrivateKey));

            return(b64.TrimEnd('='));
        }
예제 #10
0
        public void SignAuthDetachedBadKey()
        {
            //Don`t copy bobSk for other tests (bad key)!
            //30 byte
            var bobSk = new byte[] {
                0x5d, 0xab, 0x08, 0x7e, 0x62, 0x4a, 0x8a, 0x4b,
                0x79, 0xe1, 0x7f, 0x8b, 0x83, 0x80, 0x0e, 0xe6,
                0x6f, 0x3b, 0xb1, 0x29, 0x26, 0x18, 0xb6, 0xfd,
                0x1c, 0x2f, 0x8b, 0x27, 0xff, 0x88
            };

            PublicKeyAuth.SignDetached(Encoding.UTF8.GetBytes("Adam Caudill"), bobSk);
        }
예제 #11
0
        public void Sign(string privateKey)
        {
            var signedBytes = PublicKeyAuth.SignDetached(GetRawHash(), privateKey.HexToByteArray());

            byte[] publicKey = new byte[32];
            Array.Copy(privateKey.HexToByteArray(), 32, publicKey, 0, 32);
            var signatureLength = signedBytes.Length + publicKey.Length;

            byte[] signatureArray = new byte[signatureLength];
            AionUtils.SetBytes(publicKey, signatureArray, 0);
            AionUtils.SetBytes(signedBytes, signatureArray, publicKey.Length);
            Signature = signatureArray;
        }
        public void SignAuthDetachedBadKey()
        {
            //Don`t copy bobSk for other tests (bad key)!
            //30 byte
            var bobSk = new byte[] {
                0x5d, 0xab, 0x08, 0x7e, 0x62, 0x4a, 0x8a, 0x4b,
                0x79, 0xe1, 0x7f, 0x8b, 0x83, 0x80, 0x0e, 0xe6,
                0x6f, 0x3b, 0xb1, 0x29, 0x26, 0x18, 0xb6, 0xfd,
                0x1c, 0x2f, 0x8b, 0x27, 0xff, 0x88
            };
            var message = Encoding.UTF8.GetBytes("Adam Caudill");

            Assert.Throws <KeyOutOfRangeException>(
                () => PublicKeyAuth.SignDetached(message, bobSk));
        }
예제 #13
0
        public bool SignData(byte[] publicKey, byte[] data, out byte[] result)
        {
            var key = _Keys.Find(t => t.Public.SequenceEqual(publicKey));

            if (key == null)
            {
                result = null;
                return(false);
            }
            else
            {
                result = PublicKeyAuth.SignDetached(data, key.Private);
                return(true);
            }
        }
예제 #14
0
        public SignMessageDialog(Key key)
        {
            this.Build();

            textview1.Buffer.Text = Convert.ToBase64String(key.Public);

            buttonSign.Clicked += delegate
            {
                try
                {
                    var message = Convert.FromBase64String(textview1.Buffer.Text);
                    var signed  = PublicKeyAuth.SignDetached(message, key.Private);
                    textview1.Buffer.Text = Convert.ToBase64String(signed);
                } catch (Exception e)
                {
                    textview1.Buffer.Text = "Error: " + e.Message;
                }
            };
        }
        public void DetachedSignTest()
        {
            var    kp      = PublicKeyAuth.GenerateKeyPair();
            string message = "Hello, World!";

            byte[] byteMessage = System.Text.Encoding.UTF8.GetBytes(message);

            var sig1 = PublicKeyAuth.SignDetached(message, kp.Secret);
            var sig2 = PublicKeyAuth.SignDetached(byteMessage, kp.Secret);

            Assert.AreEqual(Convert.ToBase64String(sig1), Convert.ToBase64String(sig2));
            Assert.AreEqual(64, sig1.Length);
            Assert.AreEqual(64, sig2.Length);

            Assert.IsTrue(PublicKeyAuth.VerifyDetached(sig1, byteMessage, kp.Public));
            Assert.IsTrue(PublicKeyAuth.VerifyDetached(sig1, message, kp.Public));
            Assert.IsTrue(PublicKeyAuth.VerifyDetached(sig2, byteMessage, kp.Public));
            Assert.IsTrue(PublicKeyAuth.VerifyDetached(sig2, message, kp.Public));

            var kp2 = PublicKeyAuth.GenerateKeyPair();

            Assert.IsFalse(PublicKeyAuth.VerifyDetached(sig2, message, kp2.Public));
            Assert.IsFalse(PublicKeyAuth.VerifyDetached(sig2, "Invalid message test", kp.Public));
        }
예제 #16
0
 public static byte[] Sign(byte[] payload, byte[] privateKey) =>
 PublicKeyAuth.SignDetached(payload, privateKey);
예제 #17
0
 /// <summary>
 /// Sign the specified message.
 /// </summary>
 /// <returns>The sign.</returns>
 /// <param name="message">Message.</param>
 /// <param name="sk">Sk.</param>
 public static byte[] Sign(byte[] message, byte[] sk) => PublicKeyAuth.SignDetached(message, sk);
예제 #18
0
 static string LibsodiumSignDetachedToBase64(byte[] privateKey, string dataToSign)
 {
     byte[] data      = System.Text.Encoding.UTF8.GetBytes(dataToSign);
     byte[] signature = PublicKeyAuth.SignDetached(data, privateKey);
     return(Base64Encoding(signature));
 }
예제 #19
0
파일: Key.cs 프로젝트: SonoCoin/sonolib-net
 public static IEnumerable <byte> Sign(byte[] msg, byte[] privateKey)
 {
     return(PublicKeyAuth.SignDetached(msg, privateKey));
 }
예제 #20
0
 private static byte[] ComputeGlobalSignature(byte[] signatureFileBytes, byte[] privateKey)
 {
     return(PublicKeyAuth.SignDetached(signatureFileBytes, privateKey));
 }
예제 #21
0
 private static byte[] ComputeFileSignature(string filePath, bool preHash, byte[] privateKey)
 {
     byte[] fileBytes = GetFileBytes(filePath, preHash);
     return(PublicKeyAuth.SignDetached(fileBytes, privateKey));
 }
 public override byte[] Sign(byte[] input)
 => PublicKeyAuth.SignDetached(input, ((SodiumSecurityKey)Key).PrivateKey);
예제 #23
0
        /// <summary>
        ///     Sign a file with a MinisignPrivateKey.
        /// </summary>
        /// <param name="fileToSign">The full path to the file.</param>
        /// <param name="minisignPrivateKey">A valid MinisignPrivateKey to sign.</param>
        /// <param name="untrustedComment">An optional untrusted comment.</param>
        /// <param name="trustedComment">An optional trusted comment.</param>
        /// <param name="outputFolder">The folder to write the signature (optional).</param>
        /// <returns>The full path to the signed file.</returns>
        /// <exception cref="FileNotFoundException"></exception>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <exception cref="OverflowException"></exception>
        /// <exception cref="DirectoryNotFoundException"></exception>
        /// <exception cref="IOException"></exception>
        /// <exception cref="UnauthorizedAccessException"></exception>
        /// <exception cref="SecurityException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="PathTooLongException"></exception>
        /// <exception cref="NotSupportedException"></exception>
        public static string Sign(string fileToSign, MinisignPrivateKey minisignPrivateKey, string untrustedComment = "",
                                  string trustedComment = "", string outputFolder = "")
        {
            if (fileToSign != null && !File.Exists(fileToSign))
            {
                throw new FileNotFoundException("could not find fileToSign");
            }

            if (minisignPrivateKey == null)
            {
                throw new ArgumentException("missing minisignPrivateKey input", nameof(minisignPrivateKey));
            }

            if (string.IsNullOrEmpty(untrustedComment))
            {
                untrustedComment = DefaultComment;
            }

            if (string.IsNullOrEmpty(trustedComment))
            {
                var timestamp = GetTimestamp();
                var filename  = Path.GetFileName(fileToSign);
                trustedComment = "timestamp: " + timestamp + " file: " + filename;
            }

            if ((CommentPrefix + untrustedComment).Length > CommentMaxBytes)
            {
                throw new ArgumentOutOfRangeException(nameof(untrustedComment), "untrustedComment too long");
            }

            if ((TrustedCommentPrefix + trustedComment).Length > TrustedCommentMaxBytes)
            {
                throw new ArgumentOutOfRangeException(nameof(trustedComment), "trustedComment too long");
            }

            if (string.IsNullOrEmpty(outputFolder))
            {
                outputFolder = Path.GetDirectoryName(fileToSign);
            }

            //validate the outputFolder
            if (string.IsNullOrEmpty(outputFolder) || !Directory.Exists(outputFolder))
            {
                throw new DirectoryNotFoundException("outputFolder must exist");
            }

            if (outputFolder.IndexOfAny(Path.GetInvalidPathChars()) > -1)
            {
                throw new ArgumentException("The given path to the output folder contains invalid characters!");
            }

            var file = LoadMessageFile(fileToSign);

            var minisignSignature = new MinisignSignature
            {
                KeyId = minisignPrivateKey.KeyId,
                SignatureAlgorithm = Encoding.UTF8.GetBytes(Sigalg)
            };
            var signature = PublicKeyAuth.SignDetached(file, minisignPrivateKey.SecretKey);

            minisignSignature.Signature = signature;

            var binarySignature = ArrayHelpers.ConcatArrays(
                minisignSignature.SignatureAlgorithm,
                minisignSignature.KeyId,
                minisignSignature.Signature
                );

            // sign the signature and the trusted comment with a global signature
            var globalSignature =
                PublicKeyAuth.SignDetached(
                    ArrayHelpers.ConcatArrays(minisignSignature.Signature, Encoding.UTF8.GetBytes(trustedComment)),
                    minisignPrivateKey.SecretKey);

            // prepare the file lines
            var signatureFileContent = new[]
            {
                CommentPrefix + untrustedComment,
                Convert.ToBase64String(binarySignature),
                TrustedCommentPrefix + trustedComment,
                Convert.ToBase64String(globalSignature)
            };

            var outputFile = fileToSign + SigSuffix;

            File.WriteAllLines(outputFile, signatureFileContent);
            return(outputFile);
        }