private static void ReadPCRs(TPMWrapper tpm) { uint i = 0; ILog log = LogManager.GetLogger("ReadPCRs"); Parameters param = new Parameters(); param.AddPrimitiveType("capArea", CapabilityData.TPMCapabilityArea.TPM_CAP_PROPERTY); param.AddPrimitiveType("subCap", CapabilityData.TPMSubCapProperty.TPM_CAP_PROP_PCR); TPMCommandRequest request = new TPMCommandRequest(TPMCommandNames.TPM_CMD_GetCapability, param); TPMCommandResponse response = tpm.Process(request); uint maxPcrs = response.Parameters.GetValueOf <uint>(CapabilityData.PARAM_PROP_PCR); for (i = 0; i < maxPcrs; ++i) { param = new Parameters(); param.AddPrimitiveType("pcrnum", i); TPMCommandRequest req = new TPMCommandRequest(TPMCommandNames.TPM_CMD_PCRRead, param); TPMCommandResponse resp = tpm.Process(req); byte[] val = resp.Parameters.GetValueOf <byte[]>("value"); log.InfoFormat("Answer for PCR {0} is: 0x{1}", resp.Parameters.GetValueOf <UInt32>("pcrnum"), ByteHelper.ByteArrayToHexString(val)); } // TPMCommandRequest req = new TPMCommandRequest(TPMCommandNames.TPM_CMD_PCRRead, null); // TPMCommand com = TPMCommandFactory.Create(req); // com.Init(param, tpm); // com.Process(); //Console.WriteLine ("Hello World!"); }
private void LoadData(GundamInfo gundam) { if (gundam != null) { txtName.Text = gundam.GundamName; txtAddress.Text = ByteHelper.ByteArrayToHexString(ByteHelper.Int2Bytes(gundam.Index)); txtHP.Text = gundam.HP.ToString(); txtEN.Text = gundam.EN.ToString(); txtAct.Text = gundam.ACT.ToString(); txtDef.Text = gundam.DEF.ToString(); txtSpd.Text = gundam.SPD.ToString(); txtMove.Text = gundam.Move.ToString(); txtSize.Text = gundam.Size.ToString(); txtTeamSize.Text = gundam.TeamSize.ToString(); string shiyin = gundam.Earch; cboE1.SelectedValue = shiyin[0].ToString(); cboE2.SelectedValue = shiyin[1].ToString(); cboE3.SelectedValue = shiyin[2].ToString(); cboE4.SelectedValue = shiyin[3].ToString(); cboE5.SelectedValue = shiyin[4].ToString(); cboSkill1.SelectedValue = gundam.Skill1.ToString(); cboSkill2.SelectedValue = gundam.Skill2.ToString(); cboSkill3.SelectedValue = gundam.Skill3.ToString(); cboSkill4.SelectedValue = gundam.Skill4.ToString(); cboSkill5.SelectedValue = gundam.Skill5.ToString(); btnSave.Enabled = true; } else { txtName.Text = null; txtAddress.Text = null; txtHP.Text = null; txtEN.Text = null; txtAct.Text = null; txtDef.Text = null; txtSpd.Text = null; txtMove.Text = null; txtSize.Text = null; txtTeamSize.Text = null; cboE1.SelectedValue = "-1"; cboE2.SelectedValue = "-1"; cboE3.SelectedValue = "-1"; cboE4.SelectedValue = "-1"; cboE5.SelectedValue = "-1"; cboSkill1.SelectedValue = "-1"; cboSkill2.SelectedValue = "-1"; cboSkill3.SelectedValue = "-1"; cboSkill4.SelectedValue = "-1"; cboSkill5.SelectedValue = "-1"; btnSave.Enabled = false; } }
public void SessionIdTest() { var guid = new Guid("ea0fd556-801c-4bee-a9fe-672a6837dabf"); var bytes = ByteHelper.HexStringToByteArray(guid.ToString().Replace("-", "")); var bytesAsString = BitConverter.ToString(bytes).Replace("-", ""); var newGuid = new Guid(ByteHelper.ByteArrayToHexString(bytes)); Console.WriteLine(bytesAsString + " @ " + guid.ToString()); Assert.AreEqual(guid, newGuid); }
private void LoadData(MasterInfo master) { if (master != null) { txtName.Text = master.MasterName; txtAddress.Text = ByteHelper.ByteArrayToHexString(ByteHelper.Int2Bytes(master.Index)); txtSheJi.Text = master.SheJi.ToString(); txtGeDou.Text = master.GeDou.ToString(); txtShouBei.Text = master.ShouBei.ToString(); txtFanYin.Text = master.FanYin.ToString(); txtJueXin.Text = master.JueXin.ToString(); txtZhiHui.Text = master.ZhiHui.ToString(); txtFuZuo.Text = master.FuZuo.ToString(); txtTongXun.Text = master.TongXun.ToString(); txtCaoDuo.Text = master.CaoDuo.ToString(); txtWeiXiu.Text = master.WeiXiu.ToString(); txtMeiLi.Text = master.MeiLi.ToString(); txtJinYan.Text = master.JinYan.ToString(); txtChenZhang.Text = master.ChengZhang.ToString(); cboGuYou1.SelectedValue = master.GuYou1; cboGuYou2.SelectedValue = master.GuYou2; cboGuYou3.SelectedValue = master.GuYou3; btnSave.Enabled = true; } else { txtName.Text = null; txtSheJi.Text = null; txtGeDou.Text = null; txtShouBei.Text = null; txtFanYin.Text = null; txtJueXin.Text = null; txtZhiHui.Text = null; txtFuZuo.Text = null; txtTongXun.Text = null; txtCaoDuo.Text = null; txtWeiXiu.Text = null; txtMeiLi.Text = null; txtJinYan.Text = null; txtChenZhang.Text = null; cboGuYou1.SelectedValue = -1; cboGuYou2.SelectedValue = -1; cboGuYou3.SelectedValue = -1; btnSave.Enabled = false; } }
public static void Main(string[] args) { string quoteMe = "Hallo IAIK!"; byte[] quoteMeBytes = System.Text.Encoding.ASCII.GetBytes(quoteMe); // Establish Connections IDictionary <string, TPMSession> sessions = XMLConfiguration.EstablischConnection(base_path + "ClientConfigXml/UnixSocketDeviceLin.xml"); // Create one keystore per opened session foreach (TPMSession tpmSes in sessions.Values) { tpmSes.Keystore = new InMemoryKeystore(); } TPMSession sessionToUse = sessions["local0"]; sessionToUse.SetRequestSecretCallback(RequestSecret); ClientKeyHandle myFirstSignKey = sessionToUse.KeyClient.GetSrkKeyHandle().CreateKey("my_first_sign_key", TPMKeyUsage.TPM_KEY_SIGNING); ISigner signer = myFirstSignKey.CreateSigner(); signer.Init(true, null); signer.BlockUpdate(quoteMeBytes, 0, quoteMeBytes.Length); byte[] quote = signer.GenerateSignature(); Console.WriteLine("Sign of \"Hallo IAIK\" is:\n" + ByteHelper.ByteArrayToHexString(quote)); Console.WriteLine(); Console.WriteLine("Now we would verify this sign."); signer.Reset(); signer.Init(false, null); signer.BlockUpdate(quoteMeBytes, 0, quoteMeBytes.Length); if (signer.VerifySignature(quote) == true) { Console.WriteLine("Sign is OK!"); } else { Console.WriteLine("UUUUPPPPSSS something went wrong!"); } }
private void btnBatchImport_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); //dialog.RestoreDirectory = true; dialog.Filter = "机体数据|*.machine"; dialog.Multiselect = true; if (dialog.ShowDialog() == DialogResult.OK && dialog.FileNames.Length > 0) { txtSearch.Text = null; foreach (string fileName in dialog.FileNames) { byte[] data = File.ReadAllBytes(fileName); byte[] bt = new byte[GGCRStaticConfig.GundamUIDLength]; Array.Copy(data, 0, bt, 0, bt.Length); string uid = ByteHelper.ByteArrayToHexString(bt).Trim(); GundamInfo select = null; foreach (GundamInfo info in gundams) { if (info.UUID == uid) { select = info; break; } } if (select != null) { short nameId = select.UnitNameTblIndex; select.Replace(data); select.UnitNameTblIndex = nameId; select.Save(); } } lsGundam.SelectedItem = null; bindAll(); MessageBox.Show("导入成功,已自动保存", "操作提示"); // lsGundam.SelectedIndex = 0; } }
private void btnSave_Click(object sender, EventArgs e) { WeaponInfo weapon = lsGundam.SelectedItem as WeaponInfo; if (weapon != null) { btnSave.Enabled = false; txtName.Text = weapon.WeaponName; txtAddress.Text = ByteHelper.ByteArrayToHexString(ByteHelper.Int2Bytes(weapon.Index)); txtPower.Text = weapon.POWER.ToString(); txtEN.Text = weapon.EN.ToString(); txtMP.Text = weapon.MP.ToString(); txtActEarth.Text = weapon.ACTEarth.ToString(); txtMoveAct.Text = weapon.MoveACT.ToString(); txtIco1.Text = weapon.ICO.ToString(); txtIco2.Text = weapon.ICO2.ToString(); txtSpec.Text = weapon.Spec.ToString(); txtMpLimit.Text = weapon.MPLimit.ToString(); txtUseEarth.Text = weapon.UseEarth.ToString(); txtRange.Text = weapon.Range.ToString(); txtHitRate.Text = weapon.HitRate.ToString(); txtCT.Text = weapon.CT.ToString(); txtHitCount.Text = weapon.HitCount.ToString(); weapon.POWER = int.Parse(txtPower.Text); weapon.EN = short.Parse(txtEN.Text); weapon.MP = short.Parse(txtMP.Text); weapon.ACTEarth = short.Parse(txtActEarth.Text); weapon.MoveACT = byte.Parse(txtMoveAct.Text); weapon.ICO = byte.Parse(txtIco1.Text); weapon.ICO2 = byte.Parse(txtIco2.Text); weapon.Spec = byte.Parse(txtSpec.Text); weapon.MPLimit = short.Parse(txtMpLimit.Text); weapon.UseEarth = short.Parse(txtUseEarth.Text); weapon.Range = short.Parse(txtRange.Text); weapon.HitRate = byte.Parse(txtHitRate.Text); weapon.CT = byte.Parse(txtCT.Text); weapon.HitCount = byte.Parse(txtHitCount.Text); gundamFile.Save(); } }
private void button1_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); //dialog.RestoreDirectory = true; dialog.Filter = "机体数据|*.machine"; if (dialog.ShowDialog() == DialogResult.OK) { txtSearch.Text = null; byte[] data = File.ReadAllBytes(dialog.FileName); byte[] bt = new byte[GGCRStaticConfig.GundamUIDLength]; Array.Copy(data, 0, bt, 0, bt.Length); string uid = ByteHelper.ByteArrayToHexString(bt).Trim(); GundamInfo select = null; foreach (GundamInfo info in gundams) { if (info.UUID == uid) { select = info; break; } } if (select == null) { MessageBox.Show("该机体不存在,无法导入", "导入失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { short nameId = select.UnitNameTblIndex; select.Replace(data); select.UnitNameTblIndex = nameId; lsGundam.SelectedItem = null; lsGundam.SelectedItem = select; tsmiLblState.Text = "请保存"; tsmiLblState.ForeColor = Color.Red; } } }
public static XElement ToXElement(this IDICOMElement el) { var xel = new XElement("DICOMElement"); xel.Add(new XAttribute("VR", VRDictionary.GetAbbreviationFromType(el))); xel.Add(new XAttribute("Tag", el.Tag.CompleteID)); xel.Add(new XAttribute("Description", TagDictionary.GetDescription(el.Tag.CompleteID))); //Recursively add data if seq if (el.IsVR(VR.Sequence)) { var seq = el as Sequence; for (var i = 0; i < seq.Items.Count; i++) { var item = new XElement("Item"); foreach (var it in seq.Items[i].Elements) { item.Add(it.ToXElement()); } xel.Add(item); } } else // Just add data { if (el.DatType != typeof(byte)) { foreach (var d in el.DData_) { xel.Add(new XElement("Data", d)); } } else { //If data type is byte, write hex string var array = (el.DData_ as List <byte>).ToArray(); var hex = ByteHelper.ByteArrayToHexString(array); xel.Add(new XElement("Data", hex)); } } return(xel); }
private void LoadData(WeaponInfo weapon) { if (weapon != null) { txtName.Text = weapon.WeaponName; txtAddress.Text = ByteHelper.ByteArrayToHexString(ByteHelper.Int2Bytes(weapon.Index)); txtPower.Text = weapon.POWER.ToString(); txtEN.Text = weapon.EN.ToString(); txtMP.Text = weapon.MP.ToString(); txtActEarth.Text = weapon.ACTEarth.ToString(); txtMoveAct.Text = weapon.MoveACT.ToString(); txtIco1.Text = weapon.ICO.ToString(); txtIco2.Text = weapon.ICO2.ToString(); txtSpec.Text = weapon.Spec.ToString(); txtMpLimit.Text = weapon.MPLimit.ToString(); txtUseEarth.Text = weapon.UseEarth.ToString(); txtRange.Text = weapon.Range.ToString(); txtHitRate.Text = weapon.HitRate.ToString(); txtCT.Text = weapon.CT.ToString(); txtHitCount.Text = weapon.HitCount.ToString(); btnSave.Enabled = true; } else { txtName.Text = null; txtAddress.Text = null; txtPower.Text = null; txtEN.Text = null; txtMP.Text = null; txtActEarth.Text = null; txtMoveAct.Text = null; txtIco1.Text = null; txtIco2.Text = null; txtSpec.Text = null; btnSave.Enabled = false; } }
/// <summary> /// Transmit support for TpmMemoryStreams. /// </summary> /// <param name="instm"></param> /// <param name="writeSize"></param> /// <returns></returns> public TPMBlob Transmit(TPMBlob instm, bool writeSize) { if (writeSize) { instm.WriteCmdSize(); } byte[] inblob = instm.GetBuffer(); if (_debug) { _logger.DebugFormat("send --> 0x{0}", ByteHelper.ByteArrayToHexString(instm.ToArray(), " ")); } byte[] outblob = Transmit(inblob, (int)instm.Length); if (_debug) { _logger.DebugFormat("received --> 0x{0}", ByteHelper.ByteArrayToHexString(outblob, " ")); } return(new TPMBlob(outblob)); }
public override void Execute(string[] commandline) { if (commandline.Length < 2) { _console.Out.WriteLine("Error: [local_session_alias] not specified"); return; } else if (commandline.Length < 3) { _console.Out.WriteLine("Error: [command] not specified"); return; } ClientContext ctx = _console.GetValue <ClientContext> ("client_context", null); if (ctx == null) { _console.Out.WriteLine("No active connection was found"); return; } string localAlias = commandline[1]; IDictionary <string, TPMSession> tpmSessions = _console.GetValue <IDictionary <string, TPMSession> > ("tpm_sessions", null); if (tpmSessions == null || tpmSessions.ContainsKey(localAlias) == false) { _console.Out.WriteLine("Error: Specified local alias was not found"); return; } if (tpmSessions[localAlias].Keystore == null) { _console.Out.WriteLine("Error: No keystore was opened"); return; } string subCommand = commandline[2]; IDictionary <string, string> arguments = _console.SplitArguments(commandline[3], 0); if (arguments.ContainsKey("name") == false) { _console.Out.WriteLine("Error: no key name was specified"); return; } // if(arguments.ContainsKey("pcr") == false) // { // _console.Out.WriteLine("Error: no pcr values where specified"); // return; // } if (arguments.ContainsKey("data_input") == false) { _console.Out.WriteLine("Error: no data input source specified"); return; } DataInputMode dataInputMode; try { dataInputMode = (DataInputMode)Enum.Parse(typeof(DataInputMode), arguments["data_input"], true); } catch (Exception) { _console.Out.WriteLine("Error: Invalid data input source"); return; } DataFormat inputDataFormat = DataFormat.Raw; if (arguments.ContainsKey("input_data_format")) { try { inputDataFormat = (DataFormat)Enum.Parse(typeof(DataFormat), arguments["input_data_format"], true); } catch (Exception) { _console.Out.WriteLine("Error: Invalid input data format"); return; } } if (dataInputMode == DataInputMode.File && arguments.ContainsKey("file") == false) { _console.Out.WriteLine("Error: data_input=file requires file argument!"); return; } ClientKeyHandle keyHandle = tpmSessions[localAlias].KeyClient.GetKeyHandleByFriendlyName(arguments["name"]); Stream inputStream = null; if (dataInputMode == DataInputMode.Console) { inputStream = new TextReaderStream(_console.In); } else if (dataInputMode == DataInputMode.Embedded) { if (commandline.Length <= 3) { _console.Out.WriteLine("Error: no embedded data"); return; } StringBuilder embeddedData = new StringBuilder(); for (int i = 3; i < commandline.Length; i++) { embeddedData.Append(commandline[i]); if (i + 1 < commandline.Length) { embeddedData.Append(" "); } } inputStream = new TextReaderStream(new StringReader(embeddedData.ToString())); } else if (dataInputMode == DataInputMode.File) { inputStream = new FileStream(arguments["file"], FileMode.Open, FileAccess.Read); } if (inputDataFormat == DataFormat.Hex) { inputStream = new HexFilterStream(inputStream); } ISigner signatureGenerator = null; if (subCommand == "verify") { signatureGenerator = keyHandle.CreateSigner(); signatureGenerator.Init(false, null); } else if (subCommand == "generate") { signatureGenerator = keyHandle.CreateSigner(); signatureGenerator.Init(true, null); } else if (subCommand == "generate_quote" || subCommand == "verify_quote") { if (arguments.ContainsKey("pcr") == false) { _console.Out.WriteLine("Error: No pcrs specified!"); return; } TPMPCRSelection pcrSelection = tpmSessions[localAlias].CreateEmptyPCRSelection(); foreach (string pcr in arguments["pcr"].Split('|')) { int pcrValue = int.Parse(pcr); pcrSelection.PcrSelection.SetBit(pcrValue - 1, true); } signatureGenerator = keyHandle.CreateQuoter(pcrSelection); signatureGenerator.Init(subCommand == "generate_quote", null); } byte[] buffer = new byte[1024]; int read = 0; do { read = inputStream.Read(buffer, 0, buffer.Length); signatureGenerator.BlockUpdate(buffer, 0, read); }while(read > 0); _console.Out.WriteLine(ByteHelper.ByteArrayToHexString(signatureGenerator.GenerateSignature())); _console.Out.WriteLine(); inputStream.Dispose(); }
public override void Execute(string[] commandline) { if (commandline.Length < 2) { _console.Out.WriteLine("Error: [local_alias] not specified"); } else if (commandline.Length < 3) { _console.Out.WriteLine("Error: [pcr_subcommand] not specified"); } ClientContext ctx = _console.GetValue <ClientContext> ("client_context", null); if (ctx == null) { _console.Out.WriteLine("No active connection was found"); return; } string localAlias = commandline[1]; string pcrCommand = commandline[2]; IDictionary <string, TPMSession> tpmSessions = _console.GetValue <IDictionary <string, TPMSession> > ("tpm_sessions", null); if (tpmSessions == null || tpmSessions.ContainsKey(localAlias) == false) { _console.Out.WriteLine("Error: Specified local alias was not found"); return; } if (pcrCommand == "report") { uint pcrCount = tpmSessions[localAlias].CapabilityClient.GetPCRCount(); for (uint i = 0; i < pcrCount; i++) { _console.Out.WriteLine("#{0}: {1}", i, ByteHelper.ByteArrayToHexString(tpmSessions[localAlias].IntegrityClient.PCRValue(i))); } } else if (pcrCommand == "extend") { if (commandline.Length < 4) { _console.Out.WriteLine("Error: 'extend' requires some arguments"); return; } IDictionary <string, string> arguments = _console.SplitArguments(commandline[3], 0); if (arguments.ContainsKey("pcr") == false) { _console.Out.WriteLine("Error: 'extend' requires parameter 'pcr' to be specified"); return; } uint pcr = 0; if (uint.TryParse(arguments["pcr"], out pcr) == false) { _console.Out.WriteLine("Error: 'pcr' could not be parsed, is it a valid pcr specified?"); return; } if (arguments.ContainsKey("data_input") == false) { _console.Out.WriteLine("Error: 'extend' requires parameter 'data_input' to be specified"); return; } TPMSessionSealCommand.DataInputMode dataInput = (TPMSessionSealCommand.DataInputMode)Enum.Parse(typeof(TPMSessionSealCommand.DataInputMode), arguments["data_input"], true); if (dataInput != TPMSessionSealCommand.DataInputMode.Embedded && dataInput != TPMSessionSealCommand.DataInputMode.File) { _console.Out.WriteLine("Error: 'data_input' has an invalid value"); return; } byte[] digest; if (dataInput == TPMSessionSealCommand.DataInputMode.File && arguments.ContainsKey("file") == false) { _console.Out.WriteLine("Error: file-data_input require 'file' argument to be specified"); return; } else if (dataInput == TPMSessionSealCommand.DataInputMode.File) { FileInfo myFile = new FileInfo(arguments["file"]); using (FileStream src = myFile.OpenRead()) { digest = new HashProvider().Hash( new HashStreamDataProvider(src, null, null, false)); } } else if (dataInput == TPMSessionSealCommand.DataInputMode.Embedded) { using (Stream src = new HexFilterStream(new TextReaderStream(new StringReader(commandline[4])))) { digest = new byte[20]; if (src.Length != 20) { throw new ArgumentException("Error: The embedded digest must be 20 bytes long"); } src.Read(digest, 0, 20); } } else { throw new ArgumentException(String.Format("data input mode '{0}' is not supported", dataInput)); } _console.Out.WriteLine("Doing extension with digest: '{0}'", ByteHelper.ByteArrayToHexString(digest)); byte[] newDigest = tpmSessions[localAlias].IntegrityClient.Extend(pcr, digest); _console.Out.WriteLine("Extension successful, new pcr value: {0}", ByteHelper.ByteArrayToHexString(newDigest)); } else if (pcrCommand == "quote") { if (commandline.Length < 4) { _console.Out.WriteLine("Error: 'quote' requires some arguments"); return; } IDictionary <string, string> arguments = _console.SplitArguments(commandline[3], 0); if (arguments.ContainsKey("pcr") == false) { _console.Out.WriteLine("Error: 'quote' requires parameter 'pcr' to be specified"); return; } if (arguments.ContainsKey("name") == false) { _console.Out.WriteLine("Error: no key name was specified"); return; } ClientKeyHandle keyHandle = tpmSessions[localAlias].KeyClient.GetKeyHandleByFriendlyName(arguments["name"]); TPMPCRSelection pcrSelection = tpmSessions[localAlias].CreateEmptyPCRSelection(); foreach (string pcr in arguments["pcr"].Split('|')) { int pcrValue = int.Parse(pcr); pcrSelection.PcrSelection.SetBit(pcrValue - 1, true); } TPMPCRComposite quoted = keyHandle.SimpleQuote(pcrSelection); IList <int> selectedPCRs = quoted.PCRSelection.SelectedPCRs; for (int i = 0; i < selectedPCRs.Count; i++) { _console.Out.WriteLine("#{0}: {1}", selectedPCRs[i], ByteHelper.ByteArrayToHexString(quoted.PCRValues[i])); } } else { _console.Out.WriteLine("Error, unknown pcr_subcommand '{0}'", commandline[1]); } }
protected override TPMCommandResponse InternalProcess() { // Unencrypted authorization values, they need to be XOR-Encrypted with // XOR(auth, SHA-1(OSAP shared secret | session nonce)) // // OSAP_shared_secret = HMAC(key=usage secret of key handle, nonce even osap | nonce odd osap) AuthHandle auth1OSAP = _commandAuthHelper.AssureOSAPSharedSecret(this, AuthSessionNum.Auth1); _usageAuth = _params.GetValueOf <byte[]> ("usage_auth"); _migrationAuth = _params.GetValueOf <byte[]> ("migration_auth"); byte[] xorKey = new HashProvider().Hash( new HashByteDataProvider(auth1OSAP.SharedSecret), new HashByteDataProvider(auth1OSAP.NonceEven)); ByteHelper.XORBytes(_usageAuth, xorKey); ByteHelper.XORBytes(_migrationAuth, xorKey); //Load parent key if not loaded _keyManager.LoadKey(_params.GetValueOf <string>("parent")); TPMBlob requestBlob = new TPMBlob(); requestBlob.WriteCmdHeader(TPMCmdTags.TPM_TAG_RQU_AUTH1_COMMAND, TPMOrdinals.TPM_ORD_CreateWrapKey); //parent key handle gets inserted later, it may be not available now requestBlob.WriteUInt32(0); requestBlob.Write(_usageAuth, 0, 20); requestBlob.Write(_migrationAuth, 0, 20); _tpmKey.WriteToTpmBlob(requestBlob); using (_keyManager.AcquireLock()) { AuthorizeMe(requestBlob); requestBlob.SkipHeader(); if (_params.GetValueOf <string>("parent") == KeyHandle.KEY_SRK) { requestBlob.WriteUInt32((uint)TPMKeyHandles.TPM_KH_SRK); } else { requestBlob.WriteUInt32(_keyManager.IdentifierToHandle(_params.GetValueOf <string>("parent")).Handle); } _responseBlob = TransmitMe(requestBlob); } CheckResponseAuthInfo(); _responseBlob.SkipHeader(); TPMKeyCore newKey = new TPMKeyCore(_responseBlob); _responseParameters = new Parameters(); //Build and save the key identifier //The key identifier is the hex-string representation of the hash of the newly created key _responseParameters.AddPrimitiveType("key_identifier", ByteHelper.ByteArrayToHexString( new HashProvider().Hash( new HashByteDataProvider( ByteHelper.SerializeToBytes(newKey) ) ), "")); _responseParameters.AddPrimitiveType("key_data", ByteHelper.SerializeToBytes(newKey)); return(new TPMCommandResponse(true, TPMCommandNames.TPM_CMD_CreateWrapKey, _responseParameters)); }
public void Listening() { log("SynchronusSoketLinstner port[" + port + "] start !!!"); byte[] arrSendBytes = new Byte[iSendBufferSize]; byte[] arrReceiveBytes = new Byte[iReceiveBufferSize]; IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipAddress = IPAddress.Any; IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port); log("LISTENER Socket port[" + port + "] create "); Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); listener.SendTimeout = 10 * 1000; listener.ReceiveTimeout = 10 * 1000; listener.Bind(localEndPoint); log("LISTENER Socket port[" + port + "] Bind ..."); listener.Listen(2); log("LISTENER Socket port[" + port + "] Listen ..."); //Socket To Client Socket handler = null; while (true) { try { log("--------------------------AC DEVICE EMULATION COMMUNICATION BEGIN port[" + port + "] --------------------------"); log("LISTENER Socket BEFORE ACCEPT port[" + port + "] "); handler = listener.Accept(); handler.NoDelay = true; log("LISTENER Socket Accepted port[" + port + "]... "); string strIsOkBefore = "OK"; while (true) { log("##############################AC DEVICE START SEND port[" + port + "] ############################## "); if (strIsOkBefore == "OK") { //read next arrSendBytes = new byte[] { 0x0002 // STX : 1byte 20H , 0x0032, 0x0031 // 품번 : 2byte , 0x0050 // 등급 U:55H / P:50H / O:4FH , 0x0031, 0x0032, 0x0033, 0x002E, 0x0031, 0x0032 // 판정중량 6byte 소수점:2EH 1~9 : 31H~39H , 0x0003 // ETX:03H }; Random r = new Random((int)DateTime.Now.Ticks); //50 Kg 정상 / 40Kg Under/ 60Kg Over/ 그 외 Pass double dblWeight = 50 + (r.NextDouble() - 0.5) * 25; if (dblWeight < 40) { arrSendBytes[3] = 0x55; } else if (dblWeight > 60) { arrSendBytes[3] = 0x4F; } else { arrSendBytes[3] = 0x50; } string fmtWeight = dblWeight.ToString("00.000"); arrSendBytes[4] = (byte)fmtWeight[0]; arrSendBytes[5] = (byte)fmtWeight[1]; arrSendBytes[6] = (byte)fmtWeight[2]; arrSendBytes[7] = (byte)fmtWeight[3]; arrSendBytes[8] = (byte)fmtWeight[4]; arrSendBytes[9] = (byte)fmtWeight[5]; log("Setted LISTENER Socket Send ByteArray port[" + port + "] "); } else { log("Previous stat NAK, using old arrSendeBytes port[" + port + "]"); } int iSendedLength = handler.Send(arrSendBytes); log("LISTENER Socket port[" + port + "] Sent Length : " + iSendedLength); log("LISTENER Socket port[" + port + "] Sent Bytes(String) : " + Encoding.ASCII.GetString(arrSendBytes)); log("LISTENER Socket port[" + port + "] Sent Bytes(HEX) : " + ByteHelper.ByteArrayToHexString(arrSendBytes, ",")); int iReceivedLength = handler.Receive(arrReceiveBytes); if (iReceivedLength == 0) { log("Socket Disconnected . Reconnect Procedure starts"); break; } log("LISTENER Socket port[" + port + "] Received Length : " + iReceivedLength); log("LISTENER Socket port[" + port + "] Received Bytes(String) : " + Encoding.ASCII.GetString(arrReceiveBytes)); log("LISTENER Socket port[" + port + "] Received Bytes(HEX) : " + ByteHelper.ByteArrayToHexString(arrReceiveBytes, ",")); // STX : 1byte 02H | ACK : 1byte 06H / NAK : 1byte 15H | ETX : 1byte 03H if (arrReceiveBytes[1] == 0x0006) { log("LISTENER Socket port[" + port + "] receive msg : ACK"); strIsOkBefore = "OK"; } else { log("LISTENER Socket port[" + port + "] receive msg : NAK"); strIsOkBefore = "NG"; } log("##############################AC DEVICE START END port[" + port + "] ############################## "); //스크롤 너무 빨리 되는 것을 방지 하기 위해서 강제뢰 쉼 //실제 운영시는 필요하지 않을 것으로 예상함 Thread.Sleep(30 * 1000); //실제와 비슷 하도록 30초 쉬고 전송 } } catch (SocketException se) { if (se.ErrorCode == 0x00002746) { log("Socket Close : " + se.ToString()); } else { log("상대방과 통신할 수 없습니다. (상대방 HOST 와의 연결 종료 : Client Disconnect : " + se.ToString() + ")"); } } catch (Exception e) { log(e); } finally { if (handler != null) { try{ handler.Close(); }catch (Exception e) {} handler = null; } } log("--------------------------AC DEVICE EMULATION COMMUNICATION ENDS HERE port[" + port + "]--------------------------"); } }
public override void Execute(string[] commandline) { if (commandline.Length < 2) { _console.Out.WriteLine("Error: [local_alias] not specified"); } else if (commandline.Length < 3) { _console.Out.WriteLine("Error: [cap_type] not specified"); } ClientContext ctx = _console.GetValue <ClientContext> ("client_context", null); if (ctx == null) { _console.Out.WriteLine("No active connection was found"); return; } string localAlias = commandline[1]; string capCommand = commandline[2]; IDictionary <string, TPMSession> tpmSessions = _console.GetValue <IDictionary <string, TPMSession> > ("tpm_sessions", null); if (tpmSessions == null || tpmSessions.ContainsKey(localAlias) == false) { _console.Out.WriteLine("Error: Specified local alias was not found"); return; } if (capCommand == "tpm_version") { CapabilityData.TPMCapVersionInfo versionInfo = tpmSessions[localAlias].CapabilityClient.GetTPMVersion(); _console.Out.WriteLine("major: {0}, minor: {1}, rev major: {2}, rev minor: {3}", versionInfo.Version.Major, versionInfo.Version.Minor, versionInfo.Version.RevMajor, versionInfo.Version.RevMinor); _console.Out.WriteLine("Speclevel: {0} errataRev: {1}", versionInfo.SpecLevel, versionInfo.ErrataRev); _console.Out.WriteLine("VendorId: {0}", Encoding.ASCII.GetString(versionInfo.TpmVendorId)); _console.Out.WriteLine("Vendor specific (size #{0} bytes): {1}", versionInfo.VendorSpecific.Length, ByteHelper.ByteArrayToHexString(versionInfo.VendorSpecific)); } else if (capCommand == "pcr_count") { uint pcrCount = tpmSessions[localAlias].CapabilityClient.GetPCRCount(); _console.Out.WriteLine("TPM '{0}' claims to support #{1} pcr registers", localAlias, pcrCount); } else if (capCommand == "max_authsess") { uint maxAuthSess = tpmSessions[localAlias].CapabilityClient.GetMaxAuthorizationSessions(); _console.Out.WriteLine("TPM '{0}' supports #{1} authorization sessions", localAlias, maxAuthSess); } else if (capCommand == "max_transess") { uint maxTranSess = tpmSessions[localAlias].CapabilityClient.GetMaxAuthorizationSessions(); _console.Out.WriteLine("TPM '{0}' supports #{1} transport sessions", localAlias, maxTranSess); } else if (capCommand == "max_sessions") { uint maxSessions = tpmSessions[localAlias].CapabilityClient.GetMaxSessions(); _console.Out.WriteLine("TPM '{0}' supports #{1} sessions", localAlias, maxSessions); } else if (capCommand == "max_keys") { uint maxKeys = tpmSessions[localAlias].CapabilityClient.GetMaxKeys(); _console.Out.WriteLine("TPM '{0}' supports #{1} keys", localAlias, maxKeys); } else { _console.Out.WriteLine("Error, unknown cap_type '{0}'", commandline[1]); } }
public static void Main(string[] args) { string[] sealMe = { "Hallo", "IAIK!" }; // Establish Connections IDictionary <string, TPMSession> sessions = XMLConfiguration.EstablischConnection(base_path + "ClientConfigXml/UnixSocketDeviceLin.xml"); // Create one keystore per opened session foreach (TPMSession tpmSes in sessions.Values) { tpmSes.Keystore = new InMemoryKeystore(); } TPMSession sessionToUse = sessions["local0"]; sessionToUse.SetRequestSecretCallback(RequestSecret); Console.WriteLine("Create Cipher Key"); ClientKeyHandle myFirstSealKey = sessionToUse.KeyClient.GetSrkKeyHandle().CreateKey("my_first_seal_key", TPMKeyUsage.TPM_KEY_STORAGE); Console.WriteLine("Key: {0}\n{1}", myFirstSealKey.FriendlyName, myFirstSealKey.PublicKey); Console.WriteLine("---------------------------------\n"); sessionToUse.IntegrityClient.Extend(0, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); sessionToUse.IntegrityClient.Extend(1, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); sessionToUse.IntegrityClient.Extend(2, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); TPMPCRSelection pcrselect = sessionToUse.CreateEmptyPCRSelection(); pcrselect.PcrSelection[0] = true; pcrselect.PcrSelection[1] = true; pcrselect.PcrSelection[2] = true; Console.WriteLine("Create Cipher, init and cipher"); IAsymmetricBlockCipher cipher = myFirstSealKey.CreateSealBlockCipher(pcrselect); cipher.Init(true, null); byte[][] cipherText = new byte[sealMe.Length][]; int i = 0; foreach (string msg in sealMe) { byte[] block = System.Text.ASCIIEncoding.ASCII.GetBytes(msg); cipherText[i] = cipher.ProcessBlock(block, 0, block.Length); i++; } Console.WriteLine("Original vs. CiperText:"); for (i = 0; i < sealMe.Length; i++) { Console.WriteLine("{0} --> {1}", sealMe[i], ByteHelper.ByteArrayToHexString(cipherText[i])); } Console.WriteLine("---------------------------------\n"); Console.WriteLine("Init and decode"); cipher.Init(false, null); byte[][] decode = new byte[sealMe.Length][]; i = 0; foreach (byte[] msg in cipherText) { decode[i] = cipher.ProcessBlock(msg, 0, msg.Length); i++; } Console.WriteLine("Does it work?:"); for (i = 0; i < sealMe.Length; i++) { Console.WriteLine("{0}: {1}", sealMe[i] == System.Text.ASCIIEncoding.ASCII.GetString(decode[i])?"Y":"N", System.Text.ASCIIEncoding.ASCII.GetString(decode[i])); } Console.WriteLine("---------------------------------\n"); Console.WriteLine("Changing PCR Values"); sessionToUse.IntegrityClient.Extend(0, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); Console.WriteLine("Decode, now an TPMRequest Exception should be thrown, with Error Code (0x18): TPM_WRONGPCRVAL"); decode = new byte[sealMe.Length][]; i = 0; foreach (byte[] msg in cipherText) { try { decode[i] = cipher.ProcessBlock(msg, 0, msg.Length); Console.WriteLine("UUUUUPPPPSSSS, something went wrong!"); } catch (TPMRequestException e) { Console.WriteLine(e.ToString()); } i++; } }
public override string ToString() { return(ByteHelper.ByteArrayToHexString(_pubkey)); }
public override string ToString() { return(string.Format("KeyLength: {0} bits\nNumPrimes: {1}\nExponent: {2}", KeyLength, NumPrimes, Exponent == null?"<null>":ByteHelper.ByteArrayToHexString(Exponent))); }
public static void Main(string[] args) { string[] bindMe = { "Hallo", "IAIK!" }; // Establish Connections IDictionary <string, TPMSession> sessions = XMLConfiguration.EstablischConnection(base_path + "ClientConfigXml/UnixSocketDeviceLin.xml"); // Create one keystore per opened session foreach (TPMSession tpmSes in sessions.Values) { tpmSes.Keystore = new InMemoryKeystore(); } TPMSession sessionToUse = sessions["local0"]; sessionToUse.SetRequestSecretCallback(RequestSecret); Console.WriteLine("Create Cipher Key"); ClientKeyHandle myFirstBindKey = sessionToUse.KeyClient.GetSrkKeyHandle().CreateKey("my_first_bind_key", TPMKeyUsage.TPM_KEY_BIND); Console.WriteLine("Key: {0}\n{1}", myFirstBindKey.FriendlyName, myFirstBindKey.PublicKey); Console.WriteLine("---------------------------------\n"); Console.WriteLine("Create Cipher, init and cipher"); IAsymmetricBlockCipher cipher = myFirstBindKey.CreateBindBlockCipher(); cipher.Init(true, null); byte[][] cipherText = new byte[bindMe.Length][]; int i = 0; foreach (string msg in bindMe) { byte[] block = System.Text.ASCIIEncoding.ASCII.GetBytes(msg); cipherText[i] = cipher.ProcessBlock(block, 0, block.Length); i++; } Console.WriteLine("Original vs. CiperText:"); for (i = 0; i < bindMe.Length; i++) { Console.WriteLine("{0} --> {1}", bindMe[i], ByteHelper.ByteArrayToHexString(cipherText[i])); } Console.WriteLine("---------------------------------\n"); Console.WriteLine("Init and decode"); cipher.Init(false, null); byte[][] decode = new byte[bindMe.Length][]; i = 0; foreach (byte[] msg in cipherText) { decode[i] = cipher.ProcessBlock(msg, 0, msg.Length); i++; } Console.WriteLine("Does it work?:"); for (i = 0; i < bindMe.Length; i++) { Console.WriteLine("{0}: {1}", bindMe[i] == System.Text.ASCIIEncoding.ASCII.GetString(decode[i])?"Y":"N", System.Text.ASCIIEncoding.ASCII.GetString(decode[i])); } Console.WriteLine("---------------------------------\n"); }
public override void Execute(string[] commandline) { if (commandline.Length < 2) { _console.Out.WriteLine("Error: [local_alias] not specified"); return; } else if (commandline.Length < 3) { _console.Out.WriteLine("Error: [number of random values] not specified"); return; } ClientContext ctx = _console.GetValue <ClientContext> ("client_context", null); if (ctx == null) { _console.Out.WriteLine("No active connection was found"); return; } string localAlias = commandline[1]; string sNumberOfValues = commandline[2]; int numberOfValues = int.Parse(sNumberOfValues); IDictionary <string, TPMSession> tpmSessions = _console.GetValue <IDictionary <string, TPMSession> > ("tpm_sessions", null); if (tpmSessions == null || tpmSessions.ContainsKey(localAlias) == false) { _console.Out.WriteLine("Error: Specified local alias was not found"); return; } Random r = tpmSessions[localAlias].CreateRNG(); byte[] randomBuffer = new byte[20]; for (int i = 0; i < numberOfValues; i++) { r.NextBytes(randomBuffer); _console.Out.WriteLine("#{0}: int: {1} double: {2} bytes: {3}", i + 1, r.Next(), r.NextDouble(), ByteHelper.ByteArrayToHexString(randomBuffer)); } }
public override string ToString() { return(string.Format("[ResponseAuthHandleInfo: TpmAuthData={0}]", ByteHelper.ByteArrayToHexString(TpmAuthData))); }
private static Tag CreateTag(byte[] tag) { string tagId = ByteHelper.ByteArrayToHexString(tag); return(new Tag(tagId)); }
public static void Main(string[] args) { string quoteMe = "Hallo IAIK!"; byte[] quoteMeBytes = System.Text.Encoding.ASCII.GetBytes(quoteMe); // Establish Connections IDictionary <string, TPMSession> sessions = XMLConfiguration.EstablischConnection(base_path + "ClientConfigXml/UnixSocketDeviceLin.xml"); // Create one keystore per opened session foreach (TPMSession tpmSes in sessions.Values) { tpmSes.Keystore = new InMemoryKeystore(); } TPMSession sessionToUse = sessions["local0"]; sessionToUse.SetRequestSecretCallback(RequestSecret); ClientKeyHandle myFirstQuoteKey = sessionToUse.KeyClient.GetSrkKeyHandle().CreateKey("my_first_quote_key", TPMKeyUsage.TPM_KEY_SIGNING); sessionToUse.IntegrityClient.Extend(0, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); sessionToUse.IntegrityClient.Extend(1, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); sessionToUse.IntegrityClient.Extend(2, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); TPMPCRSelection pcrselect = sessionToUse.CreateEmptyPCRSelection(); pcrselect.PcrSelection[0] = true; pcrselect.PcrSelection[1] = true; pcrselect.PcrSelection[2] = true; ISigner signer = myFirstQuoteKey.CreateQuoter(pcrselect); signer.Init(true, null); signer.BlockUpdate(quoteMeBytes, 0, quoteMeBytes.Length); byte[] quote = signer.GenerateSignature(); Console.WriteLine("Quote of \"Hallo IAIK\" is:\n" + ByteHelper.ByteArrayToHexString(quote)); Console.WriteLine(); Console.WriteLine("Now we would verify this quote."); signer.Reset(); signer.Init(false, null); signer.BlockUpdate(quoteMeBytes, 0, quoteMeBytes.Length); if (signer.VerifySignature(quote) == true) { Console.WriteLine("Quote is OK!"); } else { Console.WriteLine("UUUUPPPPSSS something went wrong!"); } Console.WriteLine("Extending PCRs, Quote should fail now!"); sessionToUse.IntegrityClient.Extend(0, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); sessionToUse.IntegrityClient.Extend(1, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); sessionToUse.IntegrityClient.Extend(2, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }); if (signer.VerifySignature(quote) == true) { Console.WriteLine("UUUUPPPPSSS something went wrong!"); } else { Console.WriteLine("Quote is NOT OK, that's the way it should be."); } }
private static void TestKeystoreSqlite() { Dictionary <string, string> parameters = new Dictionary <string, string>(); parameters.Add("file", "test.db"); using (TPMKeystoreProvider keystore = TPMKeystoreProviders.Create("SQLiteKeystore", parameters)) { if (keystore.KeyCount == 0) { for (int i = 0; i < 1000; i++) { Console.WriteLine("Inserting {0}/1000", i); keystore.AddKey("FN" + i.ToString(), "ident" + i.ToString(), null, new byte[] { 0, 1, 2, 3, (byte)(i % 255) }); } } Console.WriteLine("FriendlyNames: "); foreach (string friendlyName in keystore.EnumerateFriendlyNames()) { Console.WriteLine("{0} - {1} - Parent: {2}, data: {3}", friendlyName, keystore.FriendlyNameToIdentifier(friendlyName), keystore.FindParentKeyByFriendlyName(friendlyName), ByteHelper.ByteArrayToHexString(keystore.GetKeyBlob(keystore.FriendlyNameToIdentifier(friendlyName)))); } Console.WriteLine("End of friendlynames\n"); Console.WriteLine("Identifiers: "); //keystore.AddKey("FriendlyName1", "ident1", null, new byte[]{0,1,2,3,4}); foreach (string ident in keystore.EnumerateIdentifiers()) { Console.WriteLine("{0} - {1}", ident, keystore.IdentifierToFriendlyName(ident)); } Console.WriteLine("End of Identifiers\n"); } }