protected static ByteString NewTokenId(ByteString salt) { StorageContext context = Storage.CurrentContext; byte[] key = new byte[] { Prefix_TokenId }; ByteString id = Storage.Get(context, key); Storage.Put(context, key, (BigInteger)id + 1); if (id is not null) { salt += id; } return(CryptoLib.Sha256(salt)); }
public static void CreateSale(UInt160 seller, BigInteger amount, BigInteger price, string description, ByteString?saleId) { if (amount != price * 2) { throw new Exception("seller deposit must be 2x price"); } var token = Runtime.CallingScriptHash; if (saleId != null) { if (saleId.Length != 16) { throw new Exception("sale ID must be 16 bytes long"); } } else { var saleHash = new List <object>(); saleHash.Add(seller); saleHash.Add(price); saleHash.Add(description); saleHash.Add(Runtime.GetRandom()); saleId = CryptoLib.Sha256(StdLib.Serialize(saleHash)); } StorageMap salesMap = new(Storage.CurrentContext, Prefix_Sales); var serializedSale = salesMap.Get(saleId); if (serializedSale != null) { throw new Exception("specified saleId already exists"); } var saleInfo = new SaleInfo(); saleInfo.Seller = seller; saleInfo.Description = description; saleInfo.Price = price; saleInfo.Token = token; saleInfo.State = SaleState.New; salesMap.Put(saleId, StdLib.Serialize(saleInfo)); StorageMap accountMap = new(Storage.CurrentContext, Prefix_AccountSales); accountMap.Put(seller + saleId, 0); OnNewSale(saleId, seller, description, token, price); }
protected static ByteString NewTokenId() { StorageContext context = Storage.CurrentContext; byte[] key = new byte[] { Prefix_TokenId }; ByteString id = Storage.Get(context, key); Storage.Put(context, key, (BigInteger)id + 1); ByteString data = Runtime.ExecutingScriptHash; if (id is not null) { data += id; } return(CryptoLib.Sha256(data)); }
public dynamic SendEtherToExchange(dynamic transactionDto, dynamic walletDto, string toAddress) { try { dynamic obj = null; string url = GetRPCUrl(walletDto.Network); string mKey = CryptoLib.Decrypt(walletDto.MasterKey); string mneumonicWords = CryptoLib.Decrypt(walletDto.Mnemonic); string passphrase = CryptoLib.Decrypt(walletDto.PassPhrase); var account = GetAccount(mneumonicWords, passphrase, transactionDto.AddressIndex); Web3 web3 = new Web3(account, url); var gasPrice = Nethereum.Signer.Transaction.DEFAULT_GAS_PRICE; // var gasPrice = Web3.Convert.ToWei(1.5, UnitConversion.EthUnit.Gwei); var gasLimit = Nethereum.Signer.Transaction.DEFAULT_GAS_LIMIT; var balance = web3.Eth.GetBalance.SendRequestAsync(account.Address).Result; //TODO: Check fee and use default fee var fee = gasPrice * gasLimit; var maxfee = Web3.Convert.ToWei(transactionDto.MaxFee.GetValueOrDefault(), UnitConversion.EthUnit.Ether); if (fee >= maxfee) { fee = Web3.Convert.ToWei(transactionDto.DefaultFees.GetValueOrDefault(), UnitConversion.EthUnit.Ether); } var amountToSend = balance - fee; var amountToSendInEther = UnitConversion.Convert.FromWei(amountToSend, 18); TransactionReceipt receipt = web3.Eth.GetEtherTransferService().TransferEtherAndWaitForReceiptAsync(toAddress, amountToSendInEther, UnitConversion.Convert.FromWei(gasPrice, 9), gasLimit).Result; if (receipt != null) { if (receipt.Status.Value == 1) { obj = new ExpandoObject(); obj.TransactionHash = receipt.TransactionHash; obj.Fees = UnitConversion.Convert.FromWei(fee, 18); obj.Amount = amountToSendInEther; obj.TotalAmount = UnitConversion.Convert.FromWei(balance, 18); } } return(obj); } catch (Exception ex) { throw new Exception(); } }
public PcrSelection PcrBank(PcrSelection[] pcrBanks, TpmAlgId hashAlg) { // The hash algorithm is not supported by Tpm2Tester if (!CryptoLib.IsSupported(hashAlg)) { return(null); } foreach (var pb in pcrBanks) { if (pb.hash == hashAlg) { return(pb); } } Globs.Throw("No PCR bank for hash algorithm " + hashAlg); return(null); }
public override Task <bool> Delete(string thumbprint) { lock (m_lock) { try { // Create a handle based on the hash of the cert thumbprint ushort slotIndex = BitConverter.ToUInt16(CryptoLib.HashData(TpmAlgId.Sha256, Encoding.UTF8.GetBytes(thumbprint)), 0); TpmHandle nvHandle = TpmHandle.NV(slotIndex); // Delete hash of thumbprint from NV storage m_tpm[m_ownerAuth]._AllowErrors().NvUndefineSpace(TpmHandle.RhOwner, nvHandle); } catch (Exception e) { Utils.Trace(e, "Could not delete application certificate thumprint from TPM NV storage!"); } } return(base.Delete(thumbprint)); }
public static bool crossChain(BigInteger toChainID, byte[] toChainAddress, byte[] functionName, byte[] args, byte[] caller) { var tx = (Transaction)Runtime.ScriptContainer; var IdAsByte = toChainID.ToByteArray(); CrossChainTxParameter para = new CrossChainTxParameter { toChainID = IdAsByte, toContract = toChainAddress, method = functionName, args = args, txHash = (byte[])tx.Hash, crossChainID = (byte[])CryptoLib.Sha256((ByteString)((byte[])Runtime.ExecutingScriptHash).Concat((byte[])tx.Hash)), fromContract = caller }; BigInteger requestId = getRequestID(IdAsByte); var resquestKey = putRequest(IdAsByte, requestId, para); //event CrossChainLockEvent(caller, para.fromContract, toChainID, resquestKey, para.args); return(true); }
public string GetHardwareDeviceId() { TpmHandle srkHandle = new TpmHandle(SRK_HANDLE); string hardwareDeviceId = ""; Byte[] name; Byte[] qualifiedName; try { // Open the TPM Tpm2Device tpmDevice = new TbsDevice(); tpmDevice.Connect(); var tpm = new Tpm2(tpmDevice); // Read the URI from the TPM TpmPublic srk = tpm.ReadPublic(srkHandle, out name, out qualifiedName); // Dispose of the TPM tpm.Dispose(); } catch { return(hardwareDeviceId); } // Calculate the hardware device id for this logical device byte[] deviceId = CryptoLib.HashData(TpmAlgId.Sha256, BitConverter.GetBytes(logicalDeviceId), name); // Produce the output string foreach (byte n in deviceId) { hardwareDeviceId += n.ToString("x2"); } return(hardwareDeviceId); }
public static bool Secp256k1VerifySignatureWithMessage(byte[] message, ECPoint pubkey, byte[] signature) { return(CryptoLib.VerifyWithECDsa((ByteString)message, pubkey, (ByteString)signature, NamedCurve.secp256k1)); }
static bool runTests(string[] args) { Logging.log(LogSeverity.info, "Running Tests:"); // Create a crypto lib CryptoLib crypto_lib = new CryptoLib(new CryptoLibs.BouncyCastle()); IxianKeyPair kp = crypto_lib.generateKeys(CoreConfig.defaultRsaKeySize); Logging.log(LogSeverity.info, String.Format("Public Key base64: {0}", kp.publicKeyBytes)); Logging.log(LogSeverity.info, String.Format("Private Key base64: {0}", kp.privateKeyBytes)); /// ECDSA Signature test // Generate a new signature byte[] signature = crypto_lib.getSignature(Encoding.UTF8.GetBytes("Hello There!"), kp.publicKeyBytes); Logging.log(LogSeverity.info, String.Format("Signature: {0}", signature)); // Verify the signature if (crypto_lib.verifySignature(Encoding.UTF8.GetBytes("Hello There!"), kp.publicKeyBytes, signature)) { Logging.log(LogSeverity.info, "SIGNATURE IS VALID"); } // Try a tamper test if (crypto_lib.verifySignature(Encoding.UTF8.GetBytes("Hello Tamper!"), kp.publicKeyBytes, signature)) { Logging.log(LogSeverity.info, "SIGNATURE IS VALID AND MATCHES ORIGINAL TEXT"); } else { Logging.log(LogSeverity.info, "TAMPERED SIGNATURE OR TEXT"); } // Generate a new signature for the same text byte[] signature2 = crypto_lib.getSignature(Encoding.UTF8.GetBytes("Hello There!"), kp.privateKeyBytes); Logging.log(LogSeverity.info, String.Format("Signature Again: {0}", signature2)); // Verify the signature again if (crypto_lib.verifySignature(Encoding.UTF8.GetBytes("Hello There!"), kp.publicKeyBytes, signature2)) { Logging.log(LogSeverity.info, "SIGNATURE IS VALID"); } Logging.log(LogSeverity.info, "-------------------------"); // Generate a mnemonic hash from a 64 character string. If the result is always the same, it works correctly. Mnemonic mnemonic_addr = new Mnemonic(Wordlist.English, Encoding.ASCII.GetBytes("hahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahaha")); Logging.log(LogSeverity.info, String.Format("Mnemonic Hashing Test: {0}", mnemonic_addr)); Logging.log(LogSeverity.info, "-------------------------"); // Create an address from the public key Address addr = new Address(kp.publicKeyBytes); Logging.log(LogSeverity.info, String.Format("Address generated from public key above: {0}", addr)); Logging.log(LogSeverity.info, "-------------------------"); // Testing sqlite wrapper var db = new SQLite.SQLiteConnection("storage.dat"); // Testing internal data structures db.CreateTable <Block>(); Block new_block = new Block(); db.Insert(new_block); IEnumerable <Block> block_list = db.Query <Block>("select * from Block"); if (block_list.OfType <Block>().Count() > 0) { Block first_block = block_list.FirstOrDefault(); Logging.log(LogSeverity.info, String.Format("Stored genesis block num is: {0}", first_block.blockNum)); } Logging.log(LogSeverity.info, "Tests completed successfully.\n\n"); return(true); }
// Initialize with a specific crypto library public static void initLib(ICryptoLib crypto_lib) { lib = new CryptoLib(crypto_lib); }
public static void initLib() { lib = new CryptoLib(new CryptoLibs.BouncyCastle()); }
public static ByteString Hash256(ByteString value) { return(CryptoLib.Sha256(CryptoLib.Sha256(value))); }
public static ByteString Hash160(ByteString value) { return(CryptoLib.ripemd160(CryptoLib.Sha256(value))); }
/// <summary> /// Tested, 对子节点进行Hash计算 /// </summary> /// <param name="v"></param> /// <param name="hash"></param> /// <returns></returns> public static byte[] hashChildren(byte[] v, byte[] hash) { byte[] prefix = new byte[] { 1 }; return((byte[])CryptoLib.Sha256((ByteString)prefix.Concat(v).Concat(hash))); }
/// <summary> /// Tested, 对叶节点进行Hash计算 /// </summary> /// <param name="value"></param> /// <returns></returns> public static byte[] hashLeaf(byte[] value) { byte[] prefix = new byte[] { 0x00 }; return((byte[])CryptoLib.Sha256((ByteString)prefix.Concat(value))); }
public static byte[] Murmur32(byte[] value, uint seed) { return((byte[])CryptoLib.Murmur32((ByteString)value, seed)); }
public static byte[] RIPEMD160(byte[] value) { return((byte[])CryptoLib.Ripemd160((ByteString)value)); }
public static byte[] Hash160(byte[] message) { return((byte[])CryptoLib.ripemd160(CryptoLib.Sha256((ByteString)message))); }
public static byte[] SHA256(byte[] value) { return((byte[])CryptoLib.Sha256((ByteString)value)); }
/// <summary> /// Performs the following operations: /// - Generates in software (using TSS.net helpers) a key with the given template, /// - Creates TPM-compatible dupliction blob for the given TPM based parent key, /// - Import the duplication blob into TPM /// - Loads the imported key into the TPM /// - Makes sure that the imported key works. /// </summary> /// <param name="tpm">TPM instance to use</param> /// <param name="keyPub">Template for the software generated key.</param> /// <param name="hParent">Intended TPM based parent key for the software generated key.</param> /// <param name="innerSymDef">Specification of the optional inner wrapper for the duplication blob.</param> static void GenerateAndImport(Tpm2 tpm, TpmPublic keyPub, TpmHandle hParent, SymDefObject innerSymDef = null) { // // Create a software key with the given template // // Generate a random auth value for the key to be created (though we could // use an empty buffer, too). var keyAuth = AuthValue.FromRandom(CryptoLib.DigestSize(keyPub.nameAlg)); // Generate the key TssObject swKey = TssObject.Create(keyPub, keyAuth); // // Create duplication blob for the new key with the SRK as the new parent // // Create a symmetric software key if an inner wrapper is requested. var innerWrapKey = innerSymDef == null ? null : SymCipher.Create(innerSymDef); // Retrieve the public area of the intended parent key from the TPM // We do not need the name (and qualified name) of the key here, but // the TPM command returns them anyway. // NOTE - Alternatively we could get the public area from the overloaded // form of the CreateRsaPrimaryStorageKey() helper used to create the parent // key, as all TPM key creation commands (TPM2_CreatePrimary(), TPM2_Create() // and TPM2_CreateLoaded()) return it. byte[] name, qname; TpmPublic pubParent = tpm.ReadPublic(hParent, out name, out qname); byte[] encSecret; TpmPrivate dupBlob = swKey.GetDuplicationBlob(pubParent, innerWrapKey, out encSecret); // Import the duplication blob into the TPM TpmPrivate privImp = tpm.Import(hParent, innerWrapKey, swKey.Public, dupBlob, encSecret, innerSymDef ?? new SymDefObject()); // Load the imported key ... TpmHandle hKey = tpm.Load(hParent, privImp, swKey.Public) .SetAuth(swKey.Sensitive.authValue); // ... and validate that it works byte[] message = Globs.GetRandomBytes(32); if (keyPub.objectAttributes.HasFlag(ObjectAttr.Decrypt)) { // Encrypt something if (keyPub.type == TpmAlgId.Symcipher) { // Only need software symcypher here to query IV size. // Normally, when you use a fixed algorithm, you can hardcode it. var swSym = SymCipher.Create(keyPub.parameters as SymDefObject); byte[] ivIn = Globs.GetRandomBytes(swSym.IVSize), ivOut = null; byte[] cipher = swKey.Encrypt(message, ref ivIn, out ivOut); // Not all TPMs implement TPM2_EncryptDecrypt() command tpm._ExpectResponses(TpmRc.Success, TpmRc.TbsCommandBlocked); byte[] decrypted = tpm.EncryptDecrypt(hKey, 1, TpmAlgId.Null, ivIn, cipher, out ivOut); if (tpm._LastCommandSucceeded()) { bool decOk = Globs.ArraysAreEqual(message, decrypted); Console.WriteLine("Imported symmetric key validation {0}", decOk ? "SUCCEEDED" : "FAILED"); } } } else { // Sign something (works for both asymmetric and MAC keys) string keyType = keyPub.type == TpmAlgId.Rsa ? "RSA" : keyPub.type == TpmAlgId.Keyedhash ? "HMAC" : "UNKNOWN"; // Should not happen in this sample TpmAlgId sigHashAlg = GetSchemeHash(keyPub); TpmHash toSign = TpmHash.FromData(sigHashAlg, message); var proofx = new TkHashcheck(TpmRh.Null, null); ISignatureUnion sig = tpm.Sign(hKey, toSign, null, proofx); bool sigOk = swKey.VerifySignatureOverHash(toSign, sig); Console.WriteLine("Imported {0} key validation {1}", keyType, sigOk ? "SUCCEEDED" : "FAILED"); } // Free TPM resources taken by the loaded imported key tpm.FlushContext(hKey); } // GenerateAndImport