public byte[] GetScript() { ECPoint[] pubkeys = textBox1.Lines.Select(p => ECPoint.Parse(p, ECCurve.Secp256r1)).ToArray(); using ScriptBuilder sb = new ScriptBuilder(); sb.EmitAppCall(NativeContract.NEO.Hash, "vote", new ContractParameter { Type = ContractParameterType.Hash160, Value = script_hash }, new ContractParameter { Type = ContractParameterType.Array, Value = pubkeys.Select(p => new ContractParameter { Type = ContractParameterType.PublicKey, Value = p }).ToArray() }); return(sb.ToArray()); }
public void Json_CustomGroups() { var attr = new Cosigner() { Scopes = WitnessScope.CustomGroups, AllowedGroups = new[] { ECPoint.Parse("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c", ECCurve.Secp256r1) }, Account = UInt160.Zero }; var json = "{\"account\":\"0x0000000000000000000000000000000000000000\",\"scopes\":\"CustomGroups\",\"allowedGroups\":[\"03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c\"]}"; attr.ToJson().ToString().Should().Be(json); var copy = Cosigner.FromJson(JObject.Parse(json)); Assert.AreEqual(attr.Scopes, copy.Scopes); CollectionAssert.AreEqual(attr.AllowedGroups, copy.AllowedGroups); Assert.AreEqual(attr.Account, copy.Account); }
public void Serialize_Deserialize_CustomGroups() { var attr = new Signer() { Scopes = WitnessScope.CustomGroups, AllowedGroups = new[] { ECPoint.Parse("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c", ECCurve.Secp256r1) }, Account = UInt160.Zero }; var hex = "0000000000000000000000000000000000000000200103b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c"; attr.ToArray().ToHexString().Should().Be(hex); var copy = hex.HexToBytes().AsSerializable <Signer>(); Assert.AreEqual(attr.Scopes, copy.Scopes); CollectionAssert.AreEqual(attr.AllowedGroups, copy.AllowedGroups); Assert.AreEqual(attr.Account, copy.Account); }
public void SetValue(string text) { switch (Type) { case ContractParameterType.Signature: byte[] signature = text.HexToBytes(); if (signature.Length != 64) { throw new FormatException(); } Value = signature; break; case ContractParameterType.Boolean: Value = string.Equals(text, bool.TrueString, StringComparison.OrdinalIgnoreCase); break; case ContractParameterType.Integer: Value = BigInteger.Parse(text); break; case ContractParameterType.Hash160: Value = UInt160.Parse(text); break; case ContractParameterType.Hash256: Value = UInt256.Parse(text); break; case ContractParameterType.ByteArray: Value = text.HexToBytes(); break; case ContractParameterType.PublicKey: Value = ECPoint.Parse(text, ECCurve.Secp256r1); break; case ContractParameterType.String: Value = text; break; } }
/// <summary> /// Converts the signer from a JSON object. /// </summary> /// <param name="json">The signer represented by a JSON object.</param> /// <returns>The converted signer.</returns> public static Signer FromJson(JObject json) { Signer signer = new(); signer.Account = UInt160.Parse(json["account"].GetString()); signer.Scopes = Enum.Parse <WitnessScope>(json["scopes"].GetString()); if (signer.Scopes.HasFlag(WitnessScope.CustomContracts)) { signer.AllowedContracts = ((JArray)json["allowedcontracts"]).Select(p => UInt160.Parse(p.GetString())).ToArray(); } if (signer.Scopes.HasFlag(WitnessScope.CustomGroups)) { signer.AllowedGroups = ((JArray)json["allowedgroups"]).Select(p => ECPoint.Parse(p.GetString(), ECCurve.Secp256r1)).ToArray(); } if (signer.Scopes.HasFlag(WitnessScope.WitnessRules)) { signer.Rules = ((JArray)json["rules"]).Select(p => WitnessRule.FromJson((JObject)p)).ToArray(); } return(signer); }
private void button1_Click(object sender, EventArgs e) { RegisterTransaction antshare = new RegisterTransaction { AssetType = AssetType.AntShare, #if TESTNET Name = "[{'lang':'zh-CN','name':'小蚁股(测试)'},{'lang':'en','name':'AntShare(TestNet)'}]", #else Name = "[{'lang':'zh-CN','name':'小蚁股'},{'lang':'en','name':'AntShare'}]", #endif Amount = Fixed8.FromDecimal(numericUpDown1.Value), Issuer = ECPoint.Parse(textBox1.Text, ECCurve.Secp256r1), Admin = Wallet.ToScriptHash(textBox2.Text), Attributes = new TransactionAttribute[0], Inputs = new TransactionInput[0], Outputs = new TransactionOutput[0] }; SignatureContext context = new SignatureContext(antshare); InformationBox.Show(context.ToString(), "小蚁股签名上下文:"); }
public void Json_From() { Signer signer = new() { Account = UInt160.Zero, Scopes = WitnessScope.CustomContracts | WitnessScope.CustomGroups | WitnessScope.WitnessRules, AllowedContracts = new[] { UInt160.Zero }, AllowedGroups = new[] { ECPoint.Parse("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c", ECCurve.Secp256r1) }, Rules = new WitnessRule[] { new() { Action = WitnessRuleAction.Allow, Condition = new BooleanCondition { Expression = true } } } }; var json = signer.ToJson(); var new_signer = Signer.FromJson(json); Assert.IsTrue(new_signer.Account.Equals(signer.Account)); Assert.IsTrue(new_signer.Scopes == signer.Scopes); Assert.AreEqual(1, new_signer.AllowedContracts.Length); Assert.IsTrue(new_signer.AllowedContracts[0].Equals(signer.AllowedContracts[0])); Assert.AreEqual(1, new_signer.AllowedGroups.Length); Assert.IsTrue(new_signer.AllowedGroups[0].Equals(signer.AllowedGroups[0])); }
/// <summary> /// Constructor /// </summary> public MainService() : base() { RegisterCommandHander <string, long>(false, (str) => long.Parse(str)); RegisterCommandHander <string, uint>(false, (str) => uint.Parse(str)); RegisterCommandHander <string, UInt160>(false, (str) => { switch (str.ToLowerInvariant()) { case "neo": return(NativeContract.NEO.Hash); case "gas": return(NativeContract.GAS.Hash); } // Try to parse as UInt160 if (UInt160.TryParse(str, out var addr)) { return(addr); } // Accept wallet format return(str.ToScriptHash()); }); RegisterCommandHander <string, UInt256>(false, (str) => UInt256.Parse(str)); RegisterCommandHander <string[], UInt256[]>((str) => str.Select(u => UInt256.Parse(u.Trim())).ToArray()); RegisterCommandHander <string[], UInt160[]>((arr) => arr.Select(str => StringToAddress(str)).ToArray()); RegisterCommandHander <string, ECPoint>((str) => ECPoint.Parse(str.Trim(), ECCurve.Secp256r1)); RegisterCommandHander <string[], ECPoint[]>((str) => str.Select(u => ECPoint.Parse(u.Trim(), ECCurve.Secp256r1)).ToArray()); RegisterCommandHander <string, JObject>((str) => JObject.Parse(str)); RegisterCommandHander <string, decimal>((str) => decimal.Parse(str, CultureInfo.InvariantCulture)); RegisterCommandHander <JObject, JArray>((obj) => (JArray)obj); RegisterCommand(this); }
/// <summary> /// vote for consensus node /// </summary> /// <returns></returns> public async Task <object> VoteCN(UInt160 account, string[] pubkeys) { if (CurrentWallet == null) { return(Error(ErrorCode.WalletNotOpen)); } if (account == null || pubkeys.IsEmpty()) { return(Error(ErrorCode.ParameterIsNull)); } ECPoint publicKey = null; //ECPoint[] publicKeys = null; try { //publicKeys = pubkeys.Select(p => ECPoint.Parse(p, ECCurve.Secp256r1)).ToArray(); publicKey = ECPoint.Parse(pubkeys.FirstOrDefault(), ECCurve.Secp256r1); } catch (Exception e) { return(Error(ErrorCode.InvalidPara)); } using ScriptBuilder sb = new ScriptBuilder(); sb.EmitDynamicCall(NativeContract.NEO.Hash, "vote", new ContractParameter { Type = ContractParameterType.Hash160, Value = account }, new ContractParameter { Type = ContractParameterType.PublicKey, Value = publicKey }); return(await SignAndBroadcastTx(sb.ToArray(), account)); }
public static ContractParametersContext FromJson(JObject json) { IVerifiable verifiable = typeof(ContractParametersContext).GetTypeInfo().Assembly.CreateInstance(json["type"].AsString()) as IVerifiable; if (verifiable == null) { throw new FormatException(); } using (MemoryStream ms = new MemoryStream(json["hex"].AsString().HexToBytes(), false)) using (BinaryReader reader = new BinaryReader(ms, Encoding.UTF8)) { verifiable.DeserializeUnsigned(reader); } return(new ContractParametersContext(verifiable) { Script = json["script"]?.AsString().HexToBytes(), Parameters = ((JArray)json["parameters"])?.Select(p => ContractParameter.FromJson(p)).ToArray(), Signatures = json["signatures"]?.Properties.Select(p => new { PublicKey = ECPoint.Parse(p.Key, ECCurve.Secp256r1), Signature = p.Value.AsString().HexToBytes() }).ToDictionary(p => p.PublicKey, p => p.Signature) }); }
public void TestContract_CreateStandardAccount() { ECPoint pubkey = ECPoint.Parse("024b817ef37f2fc3d4a33fe36687e592d9f30fe24b3e28187dc8f12b3b3b2b839e", ECCurve.Secp256r1); ApplicationEngine.CreateStandardAccount(pubkey).ToArray().ToHexString().Should().Be("c44ea575c5f79638f0e73f39d7bd4b3337c81691"); }
/** * is the value that the user has entered/selected valid for the type */ private static bool paramHasValidFormat(ContractParameterType selectedItem, string userParamValue) { switch (selectedItem) { case ContractParameterType.Array: break; case ContractParameterType.Signature: case ContractParameterType.ByteArray: case ContractParameterType.String: if (userParamValue.Trim().Length <= 0) { return(false); } try { byte[] byteResult = userParamValue.HexToBytes(); } catch (FormatException) { return(false); } break; case ContractParameterType.Boolean: bool selectedVal = userParamValue.Equals("true"); break; case ContractParameterType.Integer: if (!BigInteger.TryParse(userParamValue, out BigInteger intResult)) { return(false); } break; case ContractParameterType.Hash160: if (!UInt160.TryParse(userParamValue, out UInt160 hash160Result)) { return(false); } break; case ContractParameterType.Hash256: if (!UInt256.TryParse(userParamValue, out UInt256 hash256Result)) { return(false); } break; case ContractParameterType.PublicKey: try { byte[] ecPoint = ECPoint.Parse(userParamValue, ECCurve.Secp256r1).EncodePoint(true); } catch (Exception) { return(false); } break; default: return(false); } return(true); }
/// <summary> /// Constructor /// </summary> public MainService() : base() { RegisterCommandHander <string, UInt160>(false, (str) => { switch (str.ToLowerInvariant()) { case "neo": return(SmartContract.Native.NativeContract.NEO.Hash); case "gas": return(SmartContract.Native.NativeContract.GAS.Hash); } // Try to parse as UInt160 if (UInt160.TryParse(str, out var addr)) { return(addr); } // Accept wallet format return(str.ToScriptHash()); }); RegisterCommandHander <string, UInt256>(false, (str) => UInt256.Parse(str)); RegisterCommandHander <string[], UInt256[]>((str) => str.Select(u => UInt256.Parse(u.Trim())).ToArray()); RegisterCommandHander <string[], UInt160[]>((arr) => { return(arr.Select(str => { switch (str.ToLowerInvariant()) { case "neo": return SmartContract.Native.NativeContract.NEO.Hash; case "gas": return SmartContract.Native.NativeContract.GAS.Hash; } // Try to parse as UInt160 if (UInt160.TryParse(str, out var addr)) { return addr; } // Accept wallet format return str.ToScriptHash(); }) .ToArray()); }); RegisterCommandHander <string[], ECPoint[]>((str) => str.Select(u => ECPoint.Parse(u.Trim(), ECCurve.Secp256r1)).ToArray()); RegisterCommandHander <string, JObject>((str) => JObject.Parse(str)); RegisterCommandHander <JObject, JArray>((obj) => (JArray)obj); RegisterCommand(this); foreach (var plugin in Plugin.Plugins) { // Register plugins commands RegisterCommand(plugin, plugin.Name); } }
public void TestToStackItem() { ContractParameter byteParameter = new ContractParameter { Type = ContractParameterType.ByteArray, Value = "00e057eb481b".HexToBytes() }; Assert.AreEqual(30000000000000L, (long)byteParameter.ToStackItem().GetBigInteger()); ContractParameter boolParameter = new ContractParameter { Type = ContractParameterType.Boolean, Value = false }; Assert.AreEqual(false, boolParameter.ToStackItem().GetBoolean()); ContractParameter intParameter = new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1000) }; Assert.AreEqual(1000, intParameter.ToStackItem().GetBigInteger()); ContractParameter h160Parameter = new ContractParameter { Type = ContractParameterType.Hash160, Value = UInt160.Zero }; Assert.AreEqual(0, h160Parameter.ToStackItem().GetBigInteger()); ContractParameter h256Parameter = new ContractParameter { Type = ContractParameterType.Hash256, Value = UInt256.Zero }; Assert.AreEqual(0, h256Parameter.ToStackItem().GetBigInteger()); ContractParameter pkParameter = new ContractParameter { Type = ContractParameterType.PublicKey, Value = ECPoint.Parse("02f9ec1fd0a98796cf75b586772a4ddd41a0af07a1dbdf86a7238f74fb72503575", ECCurve.Secp256r1) }; Assert.AreEqual("02f9ec1fd0a98796cf75b586772a4ddd41a0af07a1dbdf86a7238f74fb72503575", pkParameter.ToStackItem().GetByteArray().ToHexString()); ContractParameter strParameter = new ContractParameter { Type = ContractParameterType.String, Value = "test😂👍" }; Assert.AreEqual("test😂👍", Encoding.UTF8.GetString(strParameter.ToStackItem().GetByteArray())); ContractParameter interopParameter = new ContractParameter { Type = ContractParameterType.InteropInterface }; Assert.AreEqual(null, interopParameter.ToStackItem()); ContractParameter arrayParameter = new ContractParameter { Type = ContractParameterType.Array, Value = new[] { byteParameter, boolParameter, intParameter, h160Parameter, h256Parameter, pkParameter, strParameter, interopParameter }.ToList() }; Assert.AreEqual(1000, ((VM.Types.Array)arrayParameter.ToStackItem())[2].GetBigInteger()); ContractParameter mapParameter = new ContractParameter { Type = ContractParameterType.Map, Value = new[] { new KeyValuePair <ContractParameter, ContractParameter>(byteParameter, pkParameter) } }; Assert.AreEqual(30000000000000L, (long)((VM.Types.Map)mapParameter.ToStackItem()).Keys.First().GetBigInteger()); }
/// <summary> /// vote for consensus node /// </summary> /// <returns></returns> public async Task <object> VoteCN(UInt160 account, string[] pubkeys) { if (CurrentWallet == null) { return(Error(ErrorCode.WalletNotOpen)); } if (account == null || pubkeys.IsEmpty()) { return(Error(ErrorCode.ParameterIsNull)); } ECPoint[] publicKeys = null; try { publicKeys = pubkeys.Select(p => ECPoint.Parse(p, ECCurve.Secp256r1)).ToArray(); } catch (Exception e) { return(Error(ErrorCode.InvalidPara)); } using ScriptBuilder sb = new ScriptBuilder(); sb.EmitAppCall(NativeContract.NEO.Hash, "vote", new ContractParameter { Type = ContractParameterType.Hash160, Value = account }, new ContractParameter { Type = ContractParameterType.Array, Value = publicKeys.Select(p => new ContractParameter { Type = ContractParameterType.PublicKey, Value = p }).ToArray() }); Transaction tx = null; try { tx = CurrentWallet.InitTransaction(sb.ToArray(), account); } catch (InvalidOperationException) { return(Error(ErrorCode.EngineFault)); } catch (Exception ex) { if (ex.Message.Contains("Insufficient GAS")) { return(Error(ErrorCode.GasNotEnough)); } throw; } var(signSuccess, context) = CurrentWallet.TrySignTx(tx); if (!signSuccess) { return(Error(ErrorCode.SignFail, context.SafeSerialize())); } var result = new VoteResultModel(); await tx.Broadcast(); result.TxId = tx.Hash; return(result); }
public static Signer ToSigner(this JObject json, byte addressVersion) { Signer signer = new(); var address = json["account"].AsString(); signer.Account = address.ToUInt160(addressVersion); WitnessScope scopes = json["scopes"].TryGetEnum <WitnessScope>(); signer.Scopes = scopes; if (scopes == WitnessScope.CustomContracts) { signer.AllowedContracts = (json["allowedcontracts"] as JArray).ToList().Select(p => UInt160.Parse(p.AsString())).ToArray(); } if (scopes == WitnessScope.CustomGroups) { signer.AllowedGroups = (json["allowedgroups"] as JArray).ToList().Select(p => ECPoint.Parse(p.AsString(), ECCurve.Secp256r1)).ToArray(); } return(signer); }
private ContractParameter[] GetParameters(int depth) { Console.Write(new String(' ', depth) + "[Parameter Types]> "); string[] types = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries); Console.Write(new String(' ', depth) + "[Parameters]> "); string[] values = Console.ReadLine().Split(' '); ContractParameter[] parameters = new ContractParameter[types.Length]; for (int i = 0; i < types.Length; i++) { switch (Convert.ToByte(types[i], 16)) { case (byte)ContractParameterType.Array: parameters[i] = new ContractParameter { Type = ContractParameterType.Array, Value = GetParameters(depth + 1) }; break; case (byte)ContractParameterType.Boolean: parameters[i] = new ContractParameter { Type = ContractParameterType.Boolean, Value = Boolean.Parse(values[i]) }; break; case (byte)ContractParameterType.ByteArray: parameters[i] = new ContractParameter { Type = ContractParameterType.ByteArray, Value = values[i].HexToBytes() }; break; case (byte)ContractParameterType.PublicKey: parameters[i] = new ContractParameter { Type = ContractParameterType.PublicKey, Value = ECPoint.Parse(values[i], ECCurve.Secp256r1) }; break; case (byte)ContractParameterType.Hash160: parameters[i] = new ContractParameter { Type = ContractParameterType.Hash160, Value = UInt160.Parse(values[i]) }; break; case (byte)ContractParameterType.Hash256: parameters[i] = new ContractParameter { Type = ContractParameterType.Hash256, Value = UInt256.Parse(values[i]) }; break; case (byte)ContractParameterType.Integer: if (long.TryParse(values[i], out long num)) { parameters[i] = new ContractParameter { Type = ContractParameterType.Integer, Value = num } } ; else if (BigInteger.TryParse(values[i].Substring(2), NumberStyles.AllowHexSpecifier, null, out BigInteger bi)) { parameters[i] = new ContractParameter { Type = ContractParameterType.Integer, Value = bi } } ; break; case (byte)ContractParameterType.String: parameters[i] = new ContractParameter { Type = ContractParameterType.String, Value = values[i] }; break; case (byte)ContractParameterType.Void: case (byte)ContractParameterType.InteropInterface: case (byte)ContractParameterType.Map: case (byte)ContractParameterType.Signature: default: throw new FormatException(); } } return(parameters); }
/// <summary> /// apply for new validator /// </summary> /// <param name="pubkey"></param> /// <returns></returns> public async Task <object> ApplyForValidator(string pubkey) { if (CurrentWallet == null) { return(Error(ErrorCode.WalletNotOpen)); } if (pubkey.IsNull()) { return(Error(ErrorCode.ParameterIsNull)); } ECPoint publicKey = null; try { publicKey = ECPoint.Parse(pubkey, ECCurve.Secp256r1); } catch (Exception e) { return(Error(ErrorCode.InvalidPara)); } using var snapshot = Blockchain.Singleton.GetSnapshot(); var validators = NativeContract.NEO.GetRegisteredValidators(snapshot); if (validators.Any(v => v.PublicKey.ToString() == pubkey)) { return(Error(ErrorCode.ValidatorAlreadyExist)); } VerificationContract contract = new VerificationContract { Script = SmartContract.Contract.CreateSignatureRedeemScript(publicKey), ParameterList = new[] { ContractParameterType.Signature } }; var account = contract.ScriptHash; using ScriptBuilder sb = new ScriptBuilder(); sb.EmitAppCall(NativeContract.NEO.Hash, "registerValidator", publicKey); Transaction tx = null; try { tx = CurrentWallet.InitTransaction(sb.ToArray(), account); } catch (InvalidOperationException) { return(Error(ErrorCode.EngineFault)); } catch (Exception ex) { if (ex.Message.Contains("Insufficient GAS")) { return(Error(ErrorCode.GasNotEnough)); } throw; } var(signSuccess, context) = CurrentWallet.TrySignTx(tx); if (!signSuccess) { return(Error(ErrorCode.SignFail, context.SafeSerialize())); } var result = new VoteResultModel(); await tx.Broadcast(); result.TxId = tx.Hash; return(result); }
private protected override void ParseJson(JObject json) { Group = ECPoint.Parse(json["group"].GetString(), ECCurve.Secp256r1); }
/// <summary> /// Read private key parameters. /// </summary> /// <param name="passphrase">passphrase for decrypt the key file</param> /// <param name="keyPair">key pair</param> /// <param name="comment">comment or empty if it didn't exist</param> public void Load(string passphrase, out KeyPair keyPair, out string comment) { PEMKeyType keyType; String base64Text; bool encrypted = false; CipherAlgorithm?encryption = null; byte[] iv = null; int keySize = 0; int ivSize = 0; using (StreamReader sreader = GetStreamReader()) { string line = sreader.ReadLine(); if (line == null) { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected eof)"); } if (line == PrivateKeyFileHeader.SSH2_OPENSSH_HEADER_RSA) { keyType = PEMKeyType.RSA; } else if (line == PrivateKeyFileHeader.SSH2_OPENSSH_HEADER_DSA) { keyType = PEMKeyType.DSA; } else if (line == PrivateKeyFileHeader.SSH2_OPENSSH_HEADER_ECDSA) { keyType = PEMKeyType.ECDSA; } else { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected key type)"); } string footer = line.Replace("BEGIN", "END"); StringBuilder buf = new StringBuilder(); comment = String.Empty; while (true) { line = sreader.ReadLine(); if (line == null) { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected eof)"); } if (line == footer) { break; } if (line.IndexOf(':') >= 0) { if (line.StartsWith("Proc-Type:")) { string[] w = line.Substring("Proc-Type:".Length).Trim().Split(','); if (w.Length < 1) { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid Proc-Type)"); } if (w[0] != "4") { throw new SSHException(Strings.GetString("UnsupportedPrivateKeyFormat") + " (" + Strings.GetString("Reason_UnsupportedProcType") + ")"); } if (w.Length >= 2 && w[1] == "ENCRYPTED") { encrypted = true; } } else if (line.StartsWith("DEK-Info:")) { string[] w = line.Substring("DEK-Info:".Length).Trim().Split(','); if (w.Length < 2) { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid DEK-Info)"); } switch (w[0]) { case "DES-EDE3-CBC": encryption = CipherAlgorithm.TripleDES; ivSize = 8; keySize = 24; break; case "AES-128-CBC": encryption = CipherAlgorithm.AES128; ivSize = 16; keySize = 16; break; default: throw new SSHException(Strings.GetString("UnsupportedPrivateKeyFormat") + " (" + Strings.GetString("Reason_UnsupportedEncryptionType") + ")"); } iv = HexToByteArray(w[1]); if (iv == null || iv.Length != ivSize) { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid IV)"); } } } else { buf.Append(line); } } base64Text = buf.ToString(); } byte[] keydata = Base64.Decode(Encoding.ASCII.GetBytes(base64Text)); if (encrypted) { if (!encryption.HasValue || iv == null) { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (missing encryption type or IV)"); } byte[] key = PassphraseToKey(passphrase, iv, keySize); Cipher cipher = CipherFactory.CreateCipher(SSHProtocol.SSH2, encryption.Value, key, iv); if (keydata.Length % cipher.BlockSize != 0) { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid key data size)"); } cipher.Decrypt(keydata, 0, keydata.Length, keydata, 0); } using (MemoryStream keyDataStream = new MemoryStream(keydata, false)) { BERReader reader = new BERReader(keyDataStream); if (!reader.ReadSequence()) { throw new SSHException(Strings.GetString("WrongPassphrase")); } if (keyType == PEMKeyType.RSA) { /* from OpenSSL rsa_asn1.c * * ASN1_SIMPLE(RSA, version, LONG), * ASN1_SIMPLE(RSA, n, BIGNUM), * ASN1_SIMPLE(RSA, e, BIGNUM), * ASN1_SIMPLE(RSA, d, BIGNUM), * ASN1_SIMPLE(RSA, p, BIGNUM), * ASN1_SIMPLE(RSA, q, BIGNUM), * ASN1_SIMPLE(RSA, dmp1, BIGNUM), * ASN1_SIMPLE(RSA, dmq1, BIGNUM), * ASN1_SIMPLE(RSA, iqmp, BIGNUM) */ BigInteger v, n, e, d, p, q, dmp1, dmq1, iqmp; if (!reader.ReadInteger(out v) || !reader.ReadInteger(out n) || !reader.ReadInteger(out e) || !reader.ReadInteger(out d) || !reader.ReadInteger(out p) || !reader.ReadInteger(out q) || !reader.ReadInteger(out dmp1) || !reader.ReadInteger(out dmq1) || !reader.ReadInteger(out iqmp)) { throw new SSHException(Strings.GetString("WrongPassphrase")); } BigInteger u = p.ModInverse(q); // inverse of p mod q keyPair = new RSAKeyPair(e, d, n, u, p, q); } else if (keyType == PEMKeyType.DSA) { /* from OpenSSL dsa_asn1.c * * ASN1_SIMPLE(DSA, version, LONG), * ASN1_SIMPLE(DSA, p, BIGNUM), * ASN1_SIMPLE(DSA, q, BIGNUM), * ASN1_SIMPLE(DSA, g, BIGNUM), * ASN1_SIMPLE(DSA, pub_key, BIGNUM), * ASN1_SIMPLE(DSA, priv_key, BIGNUM) */ BigInteger v, p, q, g, y, x; if (!reader.ReadInteger(out v) || !reader.ReadInteger(out p) || !reader.ReadInteger(out q) || !reader.ReadInteger(out g) || !reader.ReadInteger(out y) || !reader.ReadInteger(out x)) { throw new SSHException(Strings.GetString("WrongPassphrase")); } keyPair = new DSAKeyPair(p, g, q, y, x); } else if (keyType == PEMKeyType.ECDSA) { /* from OpenSSL ec_asn1.c * * ASN1_SIMPLE(EC_PRIVATEKEY, version, LONG), * ASN1_SIMPLE(EC_PRIVATEKEY, privateKey, ASN1_OCTET_STRING), * ASN1_EXP_OPT(EC_PRIVATEKEY, parameters, ECPKPARAMETERS, 0), * ------ * ASN1_SIMPLE(ECPKPARAMETERS, value.named_curve, ASN1_OBJECT), * ------ * ASN1_EXP_OPT(EC_PRIVATEKEY, publicKey, ASN1_BIT_STRING, 1) */ int len; byte[] privateKey; byte[] publicKey; string namedCurve; BigInteger v; if (!reader.ReadInteger(out v) || !reader.ReadOctetString(out privateKey) || !reader.ReadTag(BERReader.TagClass.ContextSpecific, true, 0, out len) || !reader.ReadObjectIdentifier(out namedCurve) || !reader.ReadTag(BERReader.TagClass.ContextSpecific, true, 1, out len) || !reader.ReadBitString(out publicKey)) { throw new SSHException(Strings.GetString("WrongPassphrase")); } EllipticCurve curve = EllipticCurve.FindByOID(namedCurve); if (curve == null) { throw new SSHException(Strings.GetString("UnsupportedEllipticCurveInKeyPair")); } ECPoint ecPublicKeyPoint; if (!ECPoint.Parse(publicKey, curve, out ecPublicKeyPoint)) { throw new SSHException(Strings.GetString("KeysAreBroken")); } var ecKeyPair = new ECDSAKeyPair(curve, new ECDSAPublicKey(curve, ecPublicKeyPoint), new BigInteger(privateKey)); if (!ecKeyPair.CheckKeyConsistency()) { throw new SSHException(Strings.GetString("KeysAreBroken")); } keyPair = ecKeyPair; } else { throw new SSHException("Unknown file type. This should not happen."); } } }
/// <summary> /// Read PuTTY SSH2 private key parameters. /// </summary> /// <param name="passphrase">passphrase for decrypt the key file</param> /// <param name="keyPair">key pair</param> /// <param name="comment">comment or empty if it didn't exist</param> public void Load(string passphrase, out KeyPair keyPair, out string comment) { if (keyFile == null) { throw new SSHException("A key file is not loaded yet"); } int version; string keyTypeName; KeyType keyType; string encryptionName; CipherAlgorithm?encryption; byte[] publicBlob; byte[] privateBlob; string privateMac; string privateHash; using (StreamReader sreader = GetStreamReader()) { //*** Read header and key type ReadHeaderLine(sreader, out version, out keyTypeName); if (keyTypeName == "ssh-rsa") { keyType = KeyType.RSA; } else if (keyTypeName == "ssh-dss") { keyType = KeyType.DSA; } else if (keyTypeName.StartsWith("ecdsa-sha2-")) { keyType = KeyType.ECDSA; } else if (keyTypeName == "ssh-ed25519") { keyType = KeyType.ED25519; } else { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected key type)"); } //*** Read encryption ReadItemLine(sreader, "Encryption", out encryptionName); if (encryptionName == "aes256-cbc") { encryption = CipherAlgorithm.AES256; } else if (encryptionName == "none") { encryption = null; passphrase = ""; // prevent HMAC error } else { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected encryption)"); } //*** Read comment ReadItemLine(sreader, "Comment", out comment); //*** Read public lines string publicLinesStr; ReadItemLine(sreader, "Public-Lines", out publicLinesStr); int publicLines; if (!Int32.TryParse(publicLinesStr, out publicLines) || publicLines < 0) { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid public lines)"); } ReadBlob(sreader, publicLines, out publicBlob); //*** Read private lines string privateLinesStr; ReadItemLine(sreader, "Private-Lines", out privateLinesStr); int privateLines; if (!Int32.TryParse(privateLinesStr, out privateLines) || privateLines < 0) { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid private lines)"); } ReadBlob(sreader, privateLines, out privateBlob); //*** Read private MAC ReadPrivateMACLine(sreader, version, out privateMac, out privateHash); } if (encryption.HasValue) { byte[] key = PuTTYPassphraseToKey(passphrase); byte[] iv = new byte[16]; Cipher cipher = CipherFactory.CreateCipher(SSHProtocol.SSH2, encryption.Value, key, iv); if (privateBlob.Length % cipher.BlockSize != 0) { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid key data size)"); } cipher.Decrypt(privateBlob, 0, privateBlob.Length, privateBlob, 0); } bool verified = Verify(version, privateMac, privateHash, passphrase, keyTypeName, encryptionName, comment, publicBlob, privateBlob); if (!verified) { if (encryption.HasValue) { throw new SSHException(Strings.GetString("WrongPassphrase")); } else { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (HMAC verification failed)"); } } if (keyType == KeyType.RSA) { SSH2DataReader reader = new SSH2DataReader(publicBlob); string magic = reader.ReadString(); if (magic != "ssh-rsa") { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (missing magic)"); } BigInteger e = reader.ReadMPInt(); BigInteger n = reader.ReadMPInt(); reader = new SSH2DataReader(privateBlob); BigInteger d = reader.ReadMPInt(); BigInteger p = reader.ReadMPInt(); BigInteger q = reader.ReadMPInt(); BigInteger iqmp = reader.ReadMPInt(); BigInteger u = p.ModInverse(q); keyPair = new RSAKeyPair(e, d, n, u, p, q); } else if (keyType == KeyType.DSA) { SSH2DataReader reader = new SSH2DataReader(publicBlob); string magic = reader.ReadString(); if (magic != "ssh-dss") { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (missing magic)"); } BigInteger p = reader.ReadMPInt(); BigInteger q = reader.ReadMPInt(); BigInteger g = reader.ReadMPInt(); BigInteger y = reader.ReadMPInt(); reader = new SSH2DataReader(privateBlob); BigInteger x = reader.ReadMPInt(); keyPair = new DSAKeyPair(p, g, q, y, x); } else if (keyType == KeyType.ECDSA) { SSH2DataReader reader = new SSH2DataReader(publicBlob); string algorithmName = reader.ReadString(); string curveName = reader.ReadString(); byte[] publicKeyPt = reader.ReadByteString(); reader = new SSH2DataReader(privateBlob); BigInteger privateKey = reader.ReadMPInt(); EllipticCurve curve = EllipticCurve.FindByName(curveName); if (curve == null) { throw new SSHException(Strings.GetString("UnsupportedEllipticCurve") + " : " + curveName); } ECPoint publicKey; if (!ECPoint.Parse(publicKeyPt, curve, out publicKey)) { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (parsing public key failed)"); } keyPair = new ECDSAKeyPair(curve, new ECDSAPublicKey(curve, publicKey), privateKey); if (!((ECDSAKeyPair)keyPair).CheckKeyConsistency()) { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid key pair)"); } } else if (keyType == KeyType.ED25519) { SSH2DataReader reader = new SSH2DataReader(publicBlob); string algorithmName = reader.ReadString(); byte[] publicKey = reader.ReadByteString(); reader = new SSH2DataReader(privateBlob); byte[] privateKey = reader.ReadByteString(); EdwardsCurve curve = EdwardsCurve.FindByAlgorithm(PublicKeyAlgorithm.ED25519); if (curve == null) { throw new SSHException(Strings.GetString("UnsupportedEllipticCurve")); } keyPair = new EDDSAKeyPair(curve, new EDDSAPublicKey(curve, publicKey), privateKey); if (!((EDDSAKeyPair)keyPair).CheckKeyConsistency()) { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid key pair)"); } } else { throw new SSHException("Unknown file type. This should not happen."); } }
private void button1_Click(object sender, EventArgs e) { if (listView1.SelectedIndices.Count == 0) { return; } ContractParameter parameter = (ContractParameter)listView1.SelectedItems[0].Tag; switch (parameter.Type) { case ContractParameterType.Signature: try { byte[] signature = textBox2.Text.HexToBytes(); if (signature.Length != 64) { return; } parameter.Value = signature; } catch (FormatException) { return; } break; case ContractParameterType.Boolean: parameter.Value = string.Equals(textBox2.Text, bool.TrueString, StringComparison.OrdinalIgnoreCase); break; case ContractParameterType.Integer: parameter.Value = BigInteger.Parse(textBox2.Text); break; case ContractParameterType.Hash160: { UInt160 hash; if (!UInt160.TryParse(textBox2.Text, out hash)) { return; } parameter.Value = hash; } break; case ContractParameterType.Hash256: { UInt256 hash; if (!UInt256.TryParse(textBox2.Text, out hash)) { return; } parameter.Value = hash; } break; case ContractParameterType.ByteArray: try { parameter.Value = textBox2.Text.HexToBytes(); } catch (FormatException) { return; } break; case ContractParameterType.PublicKey: try { parameter.Value = ECPoint.Parse(textBox2.Text, ECCurve.Secp256r1); } catch (FormatException) { return; } break; } listView1.SelectedItems[0].SubItems["value"].Text = GetValueString(parameter.Value); textBox1.Text = listView1.SelectedItems[0].SubItems["value"].Text; textBox2.Clear(); }
public static ContractParameter JsonToContractParameter(JObject json) { ContractParameter parameter = new ContractParameter { Type = json["type"].TryGetEnum <ContractParameterType>() }; if (json["value"] == null) { return(parameter); } if (json["type"].AsString() == "Address") { parameter.Type = ContractParameterType.Hash160; parameter.Value = json["value"].AsString().ToScriptHash(); return(parameter); } switch (parameter.Type) { case ContractParameterType.Signature: case ContractParameterType.ByteArray: parameter.Value = Convert.FromBase64String(json["value"].AsString()); break; case ContractParameterType.Boolean: parameter.Value = json["value"].AsBoolean(); break; case ContractParameterType.Integer: parameter.Value = BigInteger.Parse(json["value"].AsString()); break; case ContractParameterType.Hash160: parameter.Value = UInt160.Parse(json["value"].AsString()); break; case ContractParameterType.Hash256: parameter.Value = UInt256.Parse(json["value"].AsString()); break; case ContractParameterType.PublicKey: parameter.Value = ECPoint.Parse(json["value"].AsString(), ECCurve.Secp256r1); break; case ContractParameterType.String: parameter.Value = json["value"].AsString(); break; case ContractParameterType.Array: parameter.Value = ((JArray)json["value"]).Select(p => JsonToContractParameter(p)).ToList(); break; case ContractParameterType.Map: parameter.Value = ((JArray)json["value"]).Select(p => new KeyValuePair <ContractParameter, ContractParameter>(JsonToContractParameter(p["key"]), JsonToContractParameter(p["value"]))).ToList(); break; default: throw new ArgumentException(); } return(parameter); }