private X509Certificate _LoadCertificate(string path, string password, out PrivateKey privateKey, out Provider provider) { X509Certificate certificate = null; provider = null; privateKey = null; KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(new BufferedInputStream(new FileInputStream(path)), password.ToCharArray()); IPKStoreManager storeManager = new KSStore(ks, new PassStoreKS(password)); List certificates = storeManager.getSignCertificates(); if (certificates.size() == 1) { certificate = (X509Certificate)certificates.get(0); privateKey = storeManager.getPrivateKey(certificate); provider = storeManager.getProvider(certificate); return certificate; } return certificate; }
/// <summary> /// Default implementation of saving a private key serializes as a JSON object. /// </summary> public virtual void SavePrivateKey(PrivateKey pk, Stream target) { using (var w = new StreamWriter(target)) { w.Write(JsonConvert.SerializeObject(pk)); } }
public KeyPair() { // 개인키 생성 RSAParameters privateParam = System.Security.Cryptography.RSA.Create().ExportParameters(true); publicKey = new PublicKey(privateParam.Modulus, privateParam.Exponent); privateKey = new PrivateKey(privateParam); }
private PrivateKeychain(PrivateKey privateKey, byte[] chainCode, byte[] fingerprint, byte depth, uint child, Network network) { PrivateKey = privateKey; ChainCode = chainCode; Fingerprint = fingerprint; Depth = depth; Child = child; Network = network; }
public override void InitSign (PrivateKey key) { try { rsa.ImportParameters (((RSAPrivateKey)key).Parameters); } catch (Exception ex) { Console.WriteLine (ex); throw; } }
public static PrivateKey GeneratePrivateKeyFromFile(string fileName) { PrivateKey key = new PrivateKey(); FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); key.X = GetElement(fs); key.P = GetElement(fs); return key; }
public static void SaveToFile(string fileName, PrivateKey key) { FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write); Console.WriteLine(key.X); byte[] byte_toWrite = Encoding.ASCII.GetBytes(key.X.ToString()).ToArray(); fs.Write(byte_toWrite, 0, byte_toWrite.Count()); fs.WriteByte((byte)','); byte_toWrite = Encoding.ASCII.GetBytes(key.P.ToString()).ToArray(); fs.Write(byte_toWrite, 0, byte_toWrite.Count()); fs.WriteByte((byte)'\n'); fs.Close(); }
private PrivateKeychain(byte[] seed, Network network, bool @unsafe) { if(seed.Length < SEED_MIN_SIZE) { throw new ArgumentException("Required seed with size 32 bytes or more"); } Depth = 0; Child = 0; var hashMAC = Hashes.HMACSHA512(HASH_KEY, seed); var vchChainCode = new byte[32]; Buffer.BlockCopy(hashMAC, 32, vchChainCode, 0, 32); ChainCode = vchChainCode; Fingerprint = new byte[4]; Network = (network ?? Network.Default); PrivateKey = new PrivateKey(hashMAC.Take(32).ToArray(), Network); }
public CompleteRequestDialog(IServiceProvider serviceProvider, CertificatesFeature feature) : base(serviceProvider) { InitializeComponent(); cbStore.SelectedIndex = 0; if (Environment.OSVersion.Version < Version.Parse("6.2")) { // IMPORTANT: WebHosting store is available since Windows 8. cbStore.Enabled = false; } if (!Helper.IsRunningOnMono()) { NativeMethods.TryAddShieldToButton(btnOK); } var container = new CompositeDisposable(); FormClosed += (sender, args) => container.Dispose(); container.Add( Observable.FromEventPattern <EventArgs>(txtName, "TextChanged") .ObserveOn(System.Threading.SynchronizationContext.Current) .Subscribe(evt => { btnOK.Enabled = !string.IsNullOrWhiteSpace(txtName.Text) && !string.IsNullOrWhiteSpace(txtPath.Text); })); container.Add( Observable.FromEventPattern <EventArgs>(btnOK, "Click") .ObserveOn(System.Threading.SynchronizationContext.Current) .Subscribe(evt => { if (!File.Exists(txtPath.Text)) { ShowMessage( string.Format( "There was an error while performing this operation.{0}{0}Details:{0}{0}Could not find file '{1}'.", Environment.NewLine, txtPath.Text), MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); return; } var p12File = DialogHelper.GetTempFileName(); var p12pwd = "test"; try { // TODO: check administrator permission. var x509 = new X509Certificate2(txtPath.Text); var filename = DialogHelper.GetPrivateKeyFile(x509.Subject); if (!File.Exists(filename)) { ShowMessage( string.Format( "There was an error while performing this operation.{0}{0}Details:{0}{0}Could not find private key for '{1}'.", Environment.NewLine, txtPath.Text), MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); return; } x509.PrivateKey = PrivateKey.CreateFromFile(filename).RSA; x509.FriendlyName = txtName.Text; var raw = x509.Export(X509ContentType.Pfx, p12pwd); File.WriteAllBytes(p12File, raw); Item = x509; } catch (Exception ex) { ShowError(ex, string.Empty, false); return; } Store = cbStore.SelectedIndex == 0 ? "Personal" : "WebHosting"; try { // add certificate using (var process = new Process()) { var start = process.StartInfo; start.Verb = "runas"; start.FileName = "cmd"; start.Arguments = string.Format("/c \"\"{4}\" /f:\"{0}\" /p:{1} /n:\"{2}\" /s:{3}\"", p12File, p12pwd, txtName.Text, cbStore.SelectedIndex == 0 ? "MY" : "WebHosting", Path.Combine(Environment.CurrentDirectory, "certificateinstaller.exe")); start.CreateNoWindow = true; start.WindowStyle = ProcessWindowStyle.Hidden; process.Start(); process.WaitForExit(); File.Delete(p12File); if (process.ExitCode == 0) { DialogResult = DialogResult.OK; } else { MessageBox.Show(process.ExitCode.ToString()); } } } catch (Win32Exception ex) { // elevation is cancelled. if (ex.NativeErrorCode != Microsoft.Web.Administration.NativeMethods.ErrorCancelled) { Rollbar.Report(ex, ErrorLevel.Error, new Dictionary <string, object> { { "native", ex.NativeErrorCode } }); // throw; } } catch (Exception ex) { Rollbar.Report(ex, ErrorLevel.Error); } })); container.Add( Observable.FromEventPattern <EventArgs>(btnBrowse, "Click") .ObserveOn(System.Threading.SynchronizationContext.Current) .Subscribe(evt => { DialogHelper.ShowOpenFileDialog(txtPath, "*.cer|*.cer|*.*|*.*"); })); container.Add( Observable.FromEventPattern <CancelEventArgs>(this, "HelpButtonClicked") .ObserveOn(System.Threading.SynchronizationContext.Current) .Subscribe(EnvironmentVariableTarget => { feature.ShowHelp(); })); }
protected abstract bool Equal(PrivateKey key);
public Sell3Test(ITestOutputHelper outputHelper) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.TestOutput(outputHelper) .CreateLogger(); _initialState = new State(); var sheets = TableSheetsImporter.ImportSheets(); foreach (var(key, value) in sheets) { _initialState = _initialState .SetState(Addresses.TableSheet.Derive(key), value.Serialize()); } _tableSheets = new TableSheets(sheets); _currency = new Currency("NCG", 2, minters: null); var goldCurrencyState = new GoldCurrencyState(_currency); var shopState = new ShopState(); _agentAddress = new PrivateKey().ToAddress(); var agentState = new AgentState(_agentAddress); _avatarAddress = new PrivateKey().ToAddress(); var rankingMapAddress = new PrivateKey().ToAddress(); _avatarState = new AvatarState( _avatarAddress, _agentAddress, 0, _tableSheets.GetAvatarSheets(), new GameConfigState(), rankingMapAddress) { worldInformation = new WorldInformation( 0, _tableSheets.WorldSheet, GameConfig.RequireClearedStageLevel.ActionsInShop), }; agentState.avatarAddresses[0] = _avatarAddress; var equipment = ItemFactory.CreateItemUsable( _tableSheets.EquipmentItemSheet.First, Guid.NewGuid(), 0); _avatarState.inventory.AddItem2(equipment); var consumable = ItemFactory.CreateItemUsable( _tableSheets.ConsumableItemSheet.First, Guid.NewGuid(), 0); _avatarState.inventory.AddItem2(consumable); var costume = ItemFactory.CreateCostume( _tableSheets.CostumeItemSheet.First, Guid.NewGuid()); _avatarState.inventory.AddItem2(costume); _initialState = _initialState .SetState(GoldCurrencyState.Address, goldCurrencyState.Serialize()) .SetState(Addresses.Shop, shopState.Serialize()) .SetState(_agentAddress, agentState.Serialize()) .SetState(_avatarAddress, _avatarState.Serialize()); }
public KeyPair (PrivateKey prk, PublicKey puk) { this.prk = prk; this.puk = puk; }
public static KeyStore Create(PrivateKey privateKey, ExternalAddress address) { return(new KeyStore(privateKey, address)); }
internal TransferTransaction(Connectivity.Connection connection, PublicKey senderPublicKey, PrivateKey senderPrivateKey, TransferTransactionData transactionData) : base(connection, transactionData.MultisigAccountKey ?? senderPublicKey, transactionData.Deadline) { SenderPublicKey = senderPublicKey; SenderPrivateKey = senderPrivateKey; Data = transactionData; Con = connection; Recipient = StringUtils.GetResultsWithoutHyphen(Data.RecipientAddress); SerializeTransferPart(); finalize(); AppendMultisig(); }
/// <summary> /// Create a certificate request. /// </summary> public void createCSR( Session aSession, PublicKey publicKey, string[] dn, string[] attributes, string[] extensions, out byte[] aCertificateRequest, PrivateKey privateKey = null ) { IntPtr lCertificateRequest; uint lCertificateRequestLength; // Private Key. uint lPrivateKeyHandle; if (privateKey == null) { lPrivateKeyHandle = 0; } else { lPrivateKeyHandle = privateKey.HObj; } // dn. uint ldnLength; if (dn == null) { ldnLength = 0; } else { ldnLength = (uint)dn.Length; } // Extensions. uint lExtensionsLength; if (extensions == null) { lExtensionsLength = 0; } else { lExtensionsLength = (uint)extensions.Length; } // Attributes. uint lAttributesLength; if (attributes == null) { lAttributesLength = 0; } else { lAttributesLength = (uint)attributes.Length; } // Call procedure. P11Module.createCSR(aSession.HSession, publicKey.HObj, dn, ldnLength, out lCertificateRequest, out lCertificateRequestLength, lPrivateKeyHandle, attributes, lAttributesLength, extensions, lExtensionsLength); // Marshal. aCertificateRequest = new byte[lCertificateRequestLength]; Marshal.Copy(lCertificateRequest, aCertificateRequest, 0, (int)lCertificateRequestLength); // Release buffer. P11Module.freeBuffer(lCertificateRequest); }
public abstract void InitSign (PrivateKey key);
// Public #region Construction / Destruction /// <summary> /// Open a file system. /// </summary> /// <param name="partition"></param> /// <param name="signatureKeys"></param> /// <param name="decryptionKey"></param> /// <param name="options"></param> public FileSystem(IBlockIO device, Dictionary <KeyThumbprint, PublicKey> signatureKeys, PrivateKey decryptionKey, Options options) { _keys = new Dictionary <Signature, CngKey>(); foreach (var p in _keys) { _keys.Add(p.Key, p.Value); } _decryptionKey = decryptionKey; _options = options; _readOnly = true; // Create IO Devices _deviceIO = device; _clusterIO = new FileSystemClusterIO(this, _deviceIO); _disposeDeviceIO = true; // Initialize Indices _freeClusterSearchStart = 0; _nextEntryID = 0; _nextDirectoryIndex = 0; _nextFileIndex = 0; _nextAccessRuleIndex = 0; _nextAuditRuleIndex = 0; // Create Indexes _directoryIndex = new Dictionary <int, int>(); _containedDirectoriesIndex = new Dictionary <int, SortedList <string, Directory> >(); _containedFilesIndex = new Dictionary <int, SortedList <string, File> >(); _fileIndex = new Dictionary <int, int>(); _accessRulesIndex = new Dictionary <int, List <int> >(); _auditRulesIndex = new Dictionary <int, List <int> >(); // Read the File System Header Cluster FileSystemHeaderCluster fileSystemHeaderCluster = new FileSystemHeaderCluster(_deviceIO.BlockSizeBytes, Guid.Empty); byte[] header = new byte[FileSystemHeaderCluster.CalculateClusterSize(_deviceIO.BlockSizeBytes)]; _deviceIO.Read(0, header, 0, header.Length); fileSystemHeaderCluster.Load(header, 0, signatureKeys, options); // Initialize values from the File System Header Cluster _geometry = new Geometry( fileSystemHeaderCluster.BytesPerDataCluster, fileSystemHeaderCluster.ClustersPerTrack, fileSystemHeaderCluster.DataClustersPerTrack, fileSystemHeaderCluster.TrackCount); _volumeName = fileSystemHeaderCluster.VolumeName; _volumeID = fileSystemHeaderCluster.VolumeID; // Initialize the Cluster State Table int entryCount = _geometry.ClustersPerTrack * _geometry.TrackCount; int clusterCount = (entryCount + ClusterStatesCluster.CalculateElementsPerCluster(_geometry.BytesPerCluster) - 1) / ClusterStatesCluster.CalculateElementsPerCluster(_geometry.BytesPerCluster); _clusterStateTable = new ClusterTable <ClusterState>( Enumerable.Range(0, clusterCount), sizeof(ClusterState), (address) => new ClusterStatesCluster(address, _geometry.BytesPerCluster, _volumeID)); _clusterStateTable.Load(_clusterIO); // Initialize the Next Cluster Address Table entryCount = _geometry.DataClustersPerTrack * _geometry.TrackCount; clusterCount = (entryCount + Int32ArrayCluster.CalculateElementsPerCluster(_geometry.BytesPerCluster) - 1) / Int32ArrayCluster.CalculateElementsPerCluster(_geometry.BytesPerCluster); _nextClusterAddressTable = new ClusterTable <int>( Enumerable.Range(_clusterStateTable.ClusterAddresses.Last() + 1, clusterCount), sizeof(int), (address) => new Int32ArrayCluster(address, _geometry.BytesPerCluster, _volumeID, ClusterType.NextClusterAddressTable)); _nextClusterAddressTable.Load(_clusterIO); // Initialize the Bytes Used Table _bytesUsedTable = new ClusterTable <int>( Enumerable.Range(_nextClusterAddressTable.ClusterAddresses.Last() + 1, clusterCount), sizeof(int), (address) => new Int32ArrayCluster(address, _geometry.BytesPerCluster, _volumeID, ClusterType.BytesUsedTable)); _bytesUsedTable.Load(_clusterIO); entryCount = _geometry.ClustersPerTrack * _geometry.TrackCount; clusterCount = (entryCount + VerifyTimesCluster.CalculateElementsPerCluster(_geometry.BytesPerCluster) - 1) / VerifyTimesCluster.CalculateElementsPerCluster(_geometry.BytesPerCluster); // Initialize the Verify Time Table _verifyTimeTable = new ClusterTable <DateTime>( Enumerable.Range(_bytesUsedTable.ClusterAddresses.Last() + 1, clusterCount), sizeof(long), (address) => new VerifyTimesCluster(address, _geometry.BytesPerCluster, _volumeID)); _verifyTimeTable.Load(_clusterIO); int l = _verifyTimeTable.ClusterAddresses.Last() + 1; int[] cl = getClusterChain(l).ToArray(); // Initialize the Directory Table _directoryTable = new MutableObjectClusterTable <Directory>( getClusterChain(_verifyTimeTable.ClusterAddresses.Last() + 1), Directory.StorageLength, (address) => Directory.CreateArrayCluster(address)); _directoryTable.Load(_clusterIO); // Initialize the File Table _fileTable = new MutableObjectClusterTable <File>( getClusterChain(_directoryTable.ClusterAddresses.First() + 1), File.StorageLength, (address) => File.CreateArrayCluster(address)); _fileTable.Load(_clusterIO); // Initialize the Access Rules Table _accessRules = new ClusterTable <SrfsAccessRule>( getClusterChain(_fileTable.ClusterAddresses.First() + 1), SrfsAccessRule.StorageLength + sizeof(bool), (address) => SrfsAccessRule.CreateArrayCluster(address)); _accessRules.Load(_clusterIO); // Initialize the Audit Rules Table _auditRules = new ClusterTable <SrfsAuditRule>( getClusterChain(_accessRules.ClusterAddresses.First() + 1), SrfsAuditRule.StorageLength + sizeof(bool), (address) => SrfsAuditRule.CreateArrayCluster(address)); _auditRules.Load(_clusterIO); // Create the Indexes for (int i = 0; i < _directoryTable.Count; i++) { Directory d = _directoryTable[i]; if (d != null) { _directoryIndex.Add(d.ID, i); _containedDirectoriesIndex.Add(d.ID, new SortedList <string, Directory>(StringComparer.OrdinalIgnoreCase)); _containedFilesIndex.Add(d.ID, new SortedList <string, File>(StringComparer.OrdinalIgnoreCase)); _accessRulesIndex.Add(d.ID, new List <int>()); _auditRulesIndex.Add(d.ID, new List <int>()); } } foreach (var d in from d in _directoryTable where d != null && d.ParentID != Constants.NoID select d) { _containedDirectoriesIndex[d.ParentID].Add(d.Name, d); } for (int i = 0; i < _fileTable.Count; i++) { File f = _fileTable[i]; if (f != null) { _fileIndex.Add(f.ID, i); _containedFilesIndex[f.ParentID].Add(f.Name, f); _accessRulesIndex.Add(f.ID, new List <int>()); _auditRulesIndex.Add(f.ID, new List <int>()); } } for (int i = 0; i < _accessRules.Count; i++) { Data.SrfsAccessRule r = _accessRules[i]; if (r != null) { _accessRulesIndex[r.ID].Add(i); } } for (int i = 0; i < _auditRules.Count; i++) { Data.SrfsAuditRule r = _auditRules[i]; if (r != null) { _auditRulesIndex[r.ID].Add(i); } } // Update the next entry ID _nextEntryID = Math.Max( _directoryIndex.Keys.Max(), _fileIndex.Count == 0 ? -1 : _fileIndex.Keys.Max()) + 1; }
// Private #region Methods private static void Create(IBlockIO deviceIO, string volumeName, Geometry geometry, Guid volumeID, PrivateKey signatureKey) { // Write the Partition Cluster FileSystemHeaderCluster fileSystemHeaderCluster = new FileSystemHeaderCluster(deviceIO.BlockSizeBytes, volumeID); fileSystemHeaderCluster.BytesPerDataCluster = geometry.BytesPerCluster; fileSystemHeaderCluster.ClustersPerTrack = geometry.ClustersPerTrack; fileSystemHeaderCluster.DataClustersPerTrack = geometry.DataClustersPerTrack; fileSystemHeaderCluster.TrackCount = geometry.TrackCount; fileSystemHeaderCluster.VolumeName = volumeName; byte[] data = new byte[fileSystemHeaderCluster.ClusterSizeBytes]; fileSystemHeaderCluster.Save(data, 0, signatureKey); deviceIO.Write(0, data, 0, data.Length); // Cluster State Table int entryCount = geometry.ClustersPerTrack * geometry.TrackCount; int clusterCount = (entryCount + ClusterStatesCluster.CalculateElementsPerCluster(geometry.BytesPerCluster) - 1) / ClusterStatesCluster.CalculateElementsPerCluster(geometry.BytesPerCluster); ClusterTable <ClusterState> clusterStateTable = new ClusterTable <ClusterState>( Enumerable.Range(0, clusterCount), sizeof(ClusterState), (address) => new ClusterStatesCluster(address, geometry.BytesPerCluster, volumeID)); // Next Cluster Address Table entryCount = geometry.DataClustersPerTrack * geometry.TrackCount; clusterCount = (entryCount + Int32ArrayCluster.CalculateElementsPerCluster(geometry.BytesPerCluster) - 1) / Int32ArrayCluster.CalculateElementsPerCluster(geometry.BytesPerCluster); ClusterTable <int> nextClusterAddressTable = new ClusterTable <int>( Enumerable.Range(clusterStateTable.ClusterAddresses.Last() + 1, clusterCount), sizeof(int), (address) => new Int32ArrayCluster(address, geometry.BytesPerCluster, volumeID, ClusterType.NextClusterAddressTable)); // Bytes Used Table ClusterTable <int> bytesUsedTable = new ClusterTable <int>( Enumerable.Range(nextClusterAddressTable.ClusterAddresses.Last() + 1, clusterCount), sizeof(int), (address) => new Int32ArrayCluster(address, geometry.BytesPerCluster, volumeID, ClusterType.BytesUsedTable)); entryCount = geometry.ClustersPerTrack * geometry.TrackCount; clusterCount = (entryCount + VerifyTimesCluster.CalculateElementsPerCluster(geometry.BytesPerCluster) - 1) / VerifyTimesCluster.CalculateElementsPerCluster(geometry.BytesPerCluster); // Verify Time Table ClusterTable <DateTime> verifyTimeTable = new ClusterTable <DateTime>( Enumerable.Range(bytesUsedTable.ClusterAddresses.Last() + 1, clusterCount), sizeof(long), (address) => new VerifyTimesCluster(address, geometry.BytesPerCluster, volumeID)); // Directory Table MutableObjectClusterTable <Directory> directoryTable = new MutableObjectClusterTable <Directory>( new int[] { verifyTimeTable.ClusterAddresses.Last() + 1 }, Directory.StorageLength, (address) => Directory.CreateArrayCluster(address)); // File Table MutableObjectClusterTable <File> fileTable = new MutableObjectClusterTable <File>( new int[] { directoryTable.ClusterAddresses.Last() + 1 }, File.StorageLength, (address) => File.CreateArrayCluster(address)); // Access Rules Table ClusterTable <SrfsAccessRule> accessRules = new ClusterTable <SrfsAccessRule>( new int[] { fileTable.ClusterAddresses.Last() + 1 }, SrfsAccessRule.StorageLength + sizeof(bool), (address) => SrfsAccessRule.CreateArrayCluster(address)); // Audit Rules Table ClusterTable <SrfsAuditRule> auditRules = new ClusterTable <SrfsAuditRule>( new int[] { accessRules.ClusterAddresses.Last() + 1 }, SrfsAuditRule.StorageLength + sizeof(bool), (address) => SrfsAuditRule.CreateArrayCluster(address)); // Initialize the tables int nDataClusters = geometry.DataClustersPerTrack * geometry.TrackCount; int nParityClusters = geometry.ParityClustersPerTrack * geometry.TrackCount; for (int i = 0; i < nDataClusters; i++) { clusterStateTable[i] = ClusterState.Data | ClusterState.Unwritten; } for (int i = nDataClusters; i < nDataClusters + nParityClusters; i++) { clusterStateTable[i] = ClusterState.Parity | ClusterState.Unwritten; } for (int i = nDataClusters + nParityClusters; i < clusterStateTable.Count; i++) { clusterStateTable[i] = ClusterState.Null; } for (int i = 0; i < clusterStateTable.Count; i++) { clusterStateTable[i] = ClusterState.None; } for (int i = 0; i < nextClusterAddressTable.Count; i++) { nextClusterAddressTable[i] = Constants.NoAddress; } for (int i = 0; i < bytesUsedTable.Count; i++) { bytesUsedTable[i] = 0; } for (int i = 0; i < verifyTimeTable.Count; i++) { verifyTimeTable[i] = DateTime.MinValue; } for (int i = 0; i < directoryTable.Count; i++) { directoryTable[i] = null; } for (int i = 0; i < fileTable.Count; i++) { fileTable[i] = null; } for (int i = 0; i < accessRules.Count; i++) { accessRules[i] = null; } for (int i = 0; i < auditRules.Count; i++) { auditRules[i] = null; } // Update the cluster state and next cluster address tables foreach (var t in new IEnumerable <int>[] { clusterStateTable.ClusterAddresses, nextClusterAddressTable.ClusterAddresses, bytesUsedTable.ClusterAddresses, verifyTimeTable.ClusterAddresses, directoryTable.ClusterAddresses, fileTable.ClusterAddresses, accessRules.ClusterAddresses, auditRules.ClusterAddresses }) { foreach (var n in t) { clusterStateTable[n] = ClusterState.System | ClusterState.Used; nextClusterAddressTable[n] = n + 1; } nextClusterAddressTable[t.Last()] = Constants.NoAddress; } // Create the root directory Directory dir = new Directory(0, ""); dir.Attributes = System.IO.FileAttributes.Directory; dir.ParentID = Constants.NoID; dir.Owner = WindowsIdentity.GetCurrent().User; dir.Group = WindowsIdentity.GetCurrent().User; directoryTable[0] = dir; accessRules[0] = new SrfsAccessRule(dir, new FileSystemAccessRule(WindowsIdentity.GetCurrent().User, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow)); SimpleClusterIO clusterIO = new SimpleClusterIO(deviceIO, fileSystemHeaderCluster.BytesPerDataCluster); clusterStateTable.Flush(clusterIO); nextClusterAddressTable.Flush(clusterIO); bytesUsedTable.Flush(clusterIO); verifyTimeTable.Flush(clusterIO); directoryTable.Flush(clusterIO); fileTable.Flush(clusterIO); accessRules.Flush(clusterIO); auditRules.Flush(clusterIO); }
internal static string EncryptKey(PrivateKey key, string password) { return(EncryptKey(key, password, new ScryptParams()).ToJson()); }
private void EditPrivateKey_Clicked(object sender, EventArgs e) { PrivateKey.IsVisible = true; PrivateKey.Text = Core.Messaging.MyPrivateKey; PrivateKey.Focus(); }
public void initSign(PrivateKey privateKey) { throw null; }
//throws XMLSecurityException /** * This will sign the XRD using the provided Private Key. The * signature will be kept in DOM. DOM will be created if it doesn't exist * already. * @param oKey - The private key to sign the descriptor with. * @throws XMLSecurityException */ public void sign(PrivateKey oKey) { // build up the DOM (stored in moElem for future use) getDOM(); // before signing, make sure that the document is properly normalized // this is separate from the XMLDSig canonicalization and is more for attributes, namespaces, etc. moElem.OwnerDocument.Normalize(); XmlElement oAssertionElem = DOMUtils.getFirstChildElement( moElem, Tags.NS_SAML, Tags.TAG_ASSERTION); if (oAssertionElem == null) { throw new XMLSecurityException( "Cannot create signature. No SAML Assertion attached to descriptor."); } XmlElement oSubjectElem = DOMUtils.getFirstChildElement( oAssertionElem, Tags.NS_SAML, Tags.TAG_SUBJECT); if (oSubjectElem == null) { throw new XMLSecurityException( "Cannot create signature. SAML Assertion has no subject."); } // make sure the id attribute is present string sID = moElem.getAttributeNS(Tags.NS_XML, Tags.ATTR_ID_LOW); if ((sID == null) || (sID.Equals(""))) { throw new XMLSecurityException( "Cannot create signature. ID is missing for " + moElem.LocalName); } // Set the DOM so that it can be signed DOM3Utils.bestEffortSetIDAttr(moElem, Tags.NS_XML, Tags.ATTR_ID_LOW); // Build the empty signature. XmlDocument oDoc = moElem.getOwnerDocument(); XMLSignature oSig = new XMLSignature( oDoc, null, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); // add all the transforms to the signature string[] oTransforms = new string[] { Transforms.TRANSFORM_ENVELOPED_SIGNATURE, Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS }; Transforms oTrans = new Transforms(oSig.getDocument()); for (int i = 0; i < oTransforms.Length; i++) { oTrans.addTransform(oTransforms[i]); } oSig.addDocument("#" + sID, oTrans); // now finally sign the thing oSig.sign(oKey); // now sub in this element XmlElement oSigElem = oSig.getElement(); // insert the signature in the right place oAssertionElem.InsertBefore(oSigElem, oSubjectElem); }
public static void Main(string[] args) { // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201408/20140830 // X:\jsc.svn\examples\javascript\appengine\Test\TestCryptoKeyGenerate\TestCryptoKeyGenerate\ApplicationWebService.cs // X:\jsc.svn\examples\java\hybrid\JVMCLRRSA\JVMCLRRSA\Program.cs #region Do a release build to create a hybrid jvmclr program. if (typeof(object).FullName != "java.lang.Object") { System.Console.WriteLine("Do a release build to create a hybrid jvmclr program."); Debugger.Break(); return; } #endregion System.Console.WriteLine("jvm ready! " + typeof(object).FullName); #if JCE try { var sw = Stopwatch.StartNew(); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); KeyPair keyPair = keyGen.generateKeyPair(); Console.WriteLine("after generateKeyPair " + new { sw.ElapsedMilliseconds }); // after generateKeyPair { ElapsedMilliseconds = 1791 } PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); //System.Console.WriteLine("Public Key - " + publicKey.ToString()); //System.Console.WriteLine("Private Key - " + privateKey.ToString()); var data = new sbyte[] { 0x02, 0x03, 0x04, 0x05 }; System.Console.WriteLine(data.Length.ToString()); Cipher rsaCipher = Cipher.getInstance("RSA"); //Encrypt rsaCipher.init(Cipher.ENCRYPT_MODE, publicKey); sbyte[] encByte = rsaCipher.doFinal(data); System.Console.WriteLine(encByte.Length.ToString()); //Decrypt rsaCipher.init(Cipher.DECRYPT_MODE, privateKey); sbyte[] decByte = rsaCipher.doFinal(encByte); System.Console.WriteLine(decByte.Length.ToString()); if (data.Length != decByte.Length) { for (int i = 0; i < data.Length; i++) { if (data[i] != decByte[i]) { System.Console.WriteLine("false"); } } } } catch (Exception ex) { System.Console.WriteLine(ex); } #endif //jvm ready! java.lang.Object //4 //256 //4 CLRProgram.CLRMain(); System.Console.WriteLine("jvm exit!"); }
public KeyPair(PublicKey @public, PrivateKey @private) { Public = @public; Private = @private; }
protected override void CompleteWizard() { // Generate the CSR X509Name subjectName; try { subjectName = new X509Name(string.Format("C={0},ST={1},L={2},O={3},OU={4},CN={5}", _wizardData.Country, _wizardData.State, _wizardData.City, _wizardData.Organization, _wizardData.Unit, _wizardData.CommonName)); } catch (ArgumentException ex) { ShowError(ex, Text, false); return; } // Generate the private/public keypair RsaKeyPairGenerator kpgen = new RsaKeyPairGenerator(); CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator(); kpgen.Init(new KeyGenerationParameters(new SecureRandom(randomGenerator), _wizardData.Length)); AsymmetricCipherKeyPair keyPair = kpgen.GenerateKeyPair(); // Generate the CSR Asn1Set attributes = new DerSet( new DerSequence( new DerObjectIdentifier("1.3.6.1.4.1.311.13.2.3"), new DerSet(new DerIA5String(Environment.OSVersion.Version.ToString()))), new DerSequence( new DerObjectIdentifier("1.3.6.1.4.1.311.21.20"), new DerSet( new DerSequence( new DerInteger(5), new DerUtf8String(Environment.MachineName), new DerUtf8String(Environment.UserName), new DerUtf8String("JexusManager.exe")))), new DerSequence( new DerObjectIdentifier("1.3.6.1.4.1.311.13.2.2"), new DerSet( new DerSequence( new DerInteger(1), new DerBmpString("Microsoft RSA SChannel Cryptographic Provider"), new DerBitString(new byte[0])))), new DerSequence( new DerObjectIdentifier("1.2.840.113549.1.9.14"), new DerSet( new DerSequence( new DerSequence( new DerObjectIdentifier("2.5.29.15"), new DerBoolean(new byte[] { 0x01 }), new DerOctetString(new byte[] { 0x03, 0x02, 0x04, 0xF0 })), new DerSequence( new DerObjectIdentifier("2.5.29.37"), new DerOctetString(new byte[] { 0x30, 0x0a, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01 })), new DerSequence( new DerObjectIdentifier("1.2.840.113549.1.9.15"), new DerOctetString(new byte[] { 0x30, 0x69, 0x30, 0x0e, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x03, 0x02, 0x02, 0x02, 0x00, 0x80, 0x30, 0x0e, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x03, 0x04, 0x02, 0x02, 0x00, 0x80, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x2a, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x2d, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x02, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x05, 0x30, 0x07, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x07, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x03, 0x07 })), new DerSequence( new DerObjectIdentifier("2.5.29.14"), new DerOctetString(new byte[] { 0x04, 0x14, 0xaa, 0x25, 0xd9, 0xa2, 0x39, 0x7e, 0x49, 0xd2, 0x94, 0x85, 0x7e, 0x82, 0xa8, 0x8f, 0x3b, 0x20, 0xf1, 0x4e, 0x65, 0xe5 })))))); var signing = new Asn1SignatureFactory("SHA256withRSA", keyPair.Private); Pkcs10CertificationRequest kpGen = new Pkcs10CertificationRequest(signing, subjectName, keyPair.Public, attributes); using (var stream = new StreamWriter(_wizardData.FileName)) { stream.WriteLine(_wizardData.UseIisStyle ? "-----BEGIN NEW CERTIFICATE REQUEST-----" : "-----BEGIN CERTIFICATE REQUEST-----"); stream.WriteLine(Convert.ToBase64String(kpGen.GetDerEncoded(), Base64FormattingOptions.InsertLineBreaks)); stream.WriteLine(_wizardData.UseIisStyle ? "-----END NEW CERTIFICATE REQUEST-----" : "-----END CERTIFICATE REQUEST-----"); } var key = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)keyPair.Private); PrivateKey pvk = new PrivateKey(); pvk.RSA = new RSACryptoServiceProvider(); pvk.RSA.ImportParameters(key); var file = DialogHelper.GetPrivateKeyFile(subjectName.ToString()); var folder = Path.GetDirectoryName(file); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } pvk.Save(file); }
public static IEnumerable <object[]> GetPeers() { var signer = new PrivateKey(); AppProtocolVersion ver = AppProtocolVersion.Sign(signer, 1); yield return(new object[] { new BoundPeer( new PublicKey(new byte[] { 0x04, 0xb5, 0xa2, 0x4a, 0xa2, 0x11, 0x27, 0x20, 0x42, 0x3b, 0xad, 0x39, 0xa0, 0x20, 0x51, 0x82, 0x37, 0x9d, 0x6f, 0x2b, 0x33, 0xe3, 0x48, 0x7c, 0x9a, 0xb6, 0xcc, 0x8f, 0xc4, 0x96, 0xf8, 0xa5, 0x48, 0x34, 0x40, 0xef, 0xbb, 0xef, 0x06, 0x57, 0xac, 0x2e, 0xf6, 0xc6, 0xee, 0x05, 0xdb, 0x06, 0xa9, 0x45, 0x32, 0xfd, 0xa7, 0xdd, 0xc4, 0x4a, 0x16, 0x95, 0xe5, 0xce, 0x1a, 0x3d, 0x3c, 0x76, 0xdb, }), new DnsEndPoint("0.0.0.0", 1234), ver, IPAddress.IPv6Loopback), }); yield return(new object[] { new BoundPeer( new PublicKey(new byte[] { 0x04, 0xb5, 0xa2, 0x4a, 0xa2, 0x11, 0x27, 0x20, 0x42, 0x3b, 0xad, 0x39, 0xa0, 0x20, 0x51, 0x82, 0x37, 0x9d, 0x6f, 0x2b, 0x33, 0xe3, 0x48, 0x7c, 0x9a, 0xb6, 0xcc, 0x8f, 0xc4, 0x96, 0xf8, 0xa5, 0x48, 0x34, 0x40, 0xef, 0xbb, 0xef, 0x06, 0x57, 0xac, 0x2e, 0xf6, 0xc6, 0xee, 0x05, 0xdb, 0x06, 0xa9, 0x45, 0x32, 0xfd, 0xa7, 0xdd, 0xc4, 0x4a, 0x16, 0x95, 0xe5, 0xce, 0x1a, 0x3d, 0x3c, 0x76, 0xdb, }), new DnsEndPoint("0.0.0.0", 1234), ver), }); yield return(new object[] { new BoundPeer( new PublicKey(new byte[] { 0x04, 0xb5, 0xa2, 0x4a, 0xa2, 0x11, 0x27, 0x20, 0x42, 0x3b, 0xad, 0x39, 0xa0, 0x20, 0x51, 0x82, 0x37, 0x9d, 0x6f, 0x2b, 0x33, 0xe3, 0x48, 0x7c, 0x9a, 0xb6, 0xcc, 0x8f, 0xc4, 0x96, 0xf8, 0xa5, 0x48, 0x34, 0x40, 0xef, 0xbb, 0xef, 0x06, 0x57, 0xac, 0x2e, 0xf6, 0xc6, 0xee, 0x05, 0xdb, 0x06, 0xa9, 0x45, 0x32, 0xfd, 0xa7, 0xdd, 0xc4, 0x4a, 0x16, 0x95, 0xe5, 0xce, 0x1a, 0x3d, 0x3c, 0x76, 0xdb, }), new DnsEndPoint("0.0.0.0", 1234), ver), }); yield return(new object[] { new Peer( new PublicKey(new byte[] { 0x04, 0xb5, 0xa2, 0x4a, 0xa2, 0x11, 0x27, 0x20, 0x42, 0x3b, 0xad, 0x39, 0xa0, 0x20, 0x51, 0x82, 0x37, 0x9d, 0x6f, 0x2b, 0x33, 0xe3, 0x48, 0x7c, 0x9a, 0xb6, 0xcc, 0x8f, 0xc4, 0x96, 0xf8, 0xa5, 0x48, 0x34, 0x40, 0xef, 0xbb, 0xef, 0x06, 0x57, 0xac, 0x2e, 0xf6, 0xc6, 0xee, 0x05, 0xdb, 0x06, 0xa9, 0x45, 0x32, 0xfd, 0xa7, 0xdd, 0xc4, 0x4a, 0x16, 0x95, 0xe5, 0xce, 0x1a, 0x3d, 0x3c, 0x76, 0xdb, }), ver), }); }
public override void InitSign(PrivateKey key) { sa.ImportParameters(((DSAPrivateKey)key).Parameters); }
public bool Compare(string expectedAddr, InputType inType, PrivateKey prv, out string message) { var pub = prv.ToPublicKey(); if (inType == InputType.AddrNested) { if (expectedAddr == Address.GetP2sh_P2wpkh(pub, 0)) { message = "The given address is derived from the given private key."; } else if (expectedAddr == Address.GetP2sh_P2wpkh(pub, 0, false)) { message = "The given address is derived from the given private key but it uses " + "uncompressed pubkey which is non-standard."; } else { message = "Can not derive the given address from this private key."; return(false); } } else { if (expectedAddr.StartsWith("bc")) { if (expectedAddr == Address.GetP2wpkh(pub, 0)) { message = "The given address is derived from the given private key."; } else if (expectedAddr == Address.GetP2wpkh(pub, 0, false)) { message = "The given address is derived from the given private key but it uses " + "uncompressed pubkey which is non-standard."; } else { message = "Can not derive the given address from this private key."; return(false); } } else if (expectedAddr.StartsWith("1")) { string comp = Address.GetP2pkh(pub); string uncomp = Address.GetP2pkh(pub, false); if (inType == InputType.AddrComp) { if (expectedAddr == comp) { message = "The given address is derived from the given private key."; } else if (expectedAddr == uncomp) { message = "The given address is derived from the given private key but uses " + "the uncompressed public key."; return(false); } else { message = "Can not derive the given address from this private key."; return(false); } } else if (inType == InputType.AddrUnComp) { if (expectedAddr == uncomp) { message = "The given address is derived from the given private key."; } else if (expectedAddr == comp) { message = "The given address is derived from the given private key but uses " + "the compressed public key."; return(false); } else { message = "Can not derive the given address from this private key."; return(false); } } else if (inType == InputType.AddrBoth && (expectedAddr == comp || expectedAddr == comp)) { message = "The given address is derived from the given private key."; } else { message = "Can not derive the given address from this private key."; return(false); } } else { message = "Possible invalid address type."; return(false); } } return(true); }
static int Main(string[] args) { if (args.Length < 1) { Header(); Console.WriteLine("ERROR: Missing output filename {0}", Environment.NewLine); Help(); return(-1); } string fileName = args [args.Length - 1]; // default values byte[] sn = Guid.NewGuid().ToByteArray(); string subject = defaultSubject; string issuer = defaultIssuer; DateTime notBefore = DateTime.Now; DateTime notAfter = new DateTime(643445675990000000); // 12/31/2039 23:59:59Z RSA issuerKey = (RSA)RSA.Create(); issuerKey.FromXmlString(MonoTestRootAgency); RSA subjectKey = (RSA)RSA.Create(); bool selfSigned = false; string hashName = "SHA1"; CspParameters subjectParams = new CspParameters(); CspParameters issuerParams = new CspParameters(); BasicConstraintsExtension bce = null; ExtendedKeyUsageExtension eku = null; string p12file = null; string p12pwd = null; X509Certificate issuerCertificate = null; Header(); try { int i = 0; while (i < args.Length) { switch (args [i++]) { // Basic options case "-#": // Serial Number sn = BitConverter.GetBytes(Convert.ToInt32(args [i++])); break; case "-n": // Subject Distinguish Name subject = args [i++]; break; case "-$": // (authenticode) commercial or individual // CRITICAL KeyUsageRestriction extension // hash algorithm string usageRestriction = args [i++].ToLower(); switch (usageRestriction) { case "commercial": case "individual": Console.WriteLine("WARNING: Unsupported deprecated certification extension KeyUsageRestriction not included"); // Console.WriteLine ("WARNING: ExtendedKeyUsage for codesigning has been included."); break; default: Console.WriteLine("Unsupported restriction " + usageRestriction); return(-1); } break; // Extended Options case "-a": // hash algorithm switch (args [i++].ToLower()) { case "sha1": hashName = "SHA1"; break; case "md5": Console.WriteLine("WARNING: MD5 is no more safe for this usage."); hashName = "MD5"; break; default: Console.WriteLine("Unsupported hash algorithm"); break; } break; case "-b": // Validity / notBefore notBefore = DateTime.Parse(args [i++] + " 23:59:59", CultureInfo.InvariantCulture); break; case "-cy": // basic constraints - autority or end-entity switch (args [i++].ToLower()) { case "authority": if (bce == null) { bce = new BasicConstraintsExtension(); } bce.CertificateAuthority = true; break; case "end": // do not include extension bce = null; break; case "both": Console.WriteLine("ERROR: No more supported in X.509"); return(-1); default: Console.WriteLine("Unsupported certificate type"); return(-1); } break; case "-d": // CN private extension ? Console.WriteLine("Unsupported option"); break; case "-e": // Validity / notAfter notAfter = DateTime.Parse(args [i++] + " 23:59:59", CultureInfo.InvariantCulture); break; case "-eku": // extendedKeyUsage extension char[] sep = { ',' }; string[] purposes = args [i++].Split(sep); if (eku == null) { eku = new ExtendedKeyUsageExtension(); } foreach (string purpose in purposes) { eku.KeyPurpose.Add(purpose); } break; case "-h": // pathLength (basicConstraints) // MS use an old basicConstrains (2.5.29.10) which // allows both CA and End-Entity. This is no // more supported with 2.5.29.19. if (bce == null) { bce = new BasicConstraintsExtension(); bce.CertificateAuthority = true; } bce.PathLenConstraint = Convert.ToInt32(args [i++]); break; case "-ic": issuerCertificate = LoadCertificate(args [i++]); issuer = issuerCertificate.SubjectName; break; case "-in": issuer = args [i++]; break; case "-iv": // TODO password PrivateKey pvk = PrivateKey.CreateFromFile(args [i++]); issuerKey = pvk.RSA; break; case "-l": // link (URL) // spcSpAgencyInfo private extension Console.WriteLine("Unsupported option"); break; case "-m": // validity period (in months) notAfter = notBefore.AddMonths(Convert.ToInt32(args [i++])); break; case "-nscp": // Netscape's private extensions - NetscapeCertType // BasicContraints - End Entity Console.WriteLine("Unsupported option"); break; case "-r": selfSigned = true; break; case "-sc": // subject certificate ? renew ? Console.WriteLine("Unsupported option"); break; // Issuer CspParameters options case "-ik": issuerParams.KeyContainerName = args [i++]; break; case "-iky": // select a key in the provider string ikn = args [i++].ToLower(); switch (ikn) { case "signature": issuerParams.KeyNumber = 0; break; case "exchange": issuerParams.KeyNumber = 1; break; default: issuerParams.KeyNumber = Convert.ToInt32(ikn); break; } break; case "-ip": issuerParams.ProviderName = args [i++]; break; case "-ir": switch (args [i++].ToLower()) { case "localmachine": issuerParams.Flags = CspProviderFlags.UseMachineKeyStore; break; case "currentuser": issuerParams.Flags = CspProviderFlags.UseDefaultKeyContainer; break; default: Console.WriteLine("Unknown key store for issuer"); return(-1); } break; case "-is": Console.WriteLine("Unsupported option"); return(-1); case "-iy": issuerParams.ProviderType = Convert.ToInt32(args [i++]); break; // Subject CspParameters Options case "-sk": subjectParams.KeyContainerName = args [i++]; break; case "-sky": // select a key in the provider string skn = args [i++].ToLower(); switch (skn) { case "signature": subjectParams.KeyNumber = 0; break; case "exchange": subjectParams.KeyNumber = 1; break; default: subjectParams.KeyNumber = Convert.ToInt32(skn); break; } break; case "-sp": subjectParams.ProviderName = args [i++]; break; case "-sr": switch (args [i++].ToLower()) { case "localmachine": subjectParams.Flags = CspProviderFlags.UseMachineKeyStore; break; case "currentuser": subjectParams.Flags = CspProviderFlags.UseDefaultKeyContainer; break; default: Console.WriteLine("Unknown key store for subject"); return(-1); } break; case "-ss": Console.WriteLine("Unsupported option"); return(-1); case "-sv": string pvkFile = args [i++]; if (File.Exists(pvkFile)) { PrivateKey key = PrivateKey.CreateFromFile(pvkFile); subjectKey = key.RSA; } else { PrivateKey key = new PrivateKey(); key.RSA = subjectKey; key.Save(pvkFile); } break; case "-sy": subjectParams.ProviderType = Convert.ToInt32(args [i++]); break; // Mono Specific Options case "-p12": p12file = args [i++]; p12pwd = args [i++]; break; // Other options case "-?": Help(); return(0); case "-!": ExtendedHelp(); return(0); default: if (i != args.Length) { Console.WriteLine("ERROR: Unknown parameter"); Help(); return(-1); } break; } } // serial number MUST be positive if ((sn [0] & 0x80) == 0x80) { sn [0] -= 0x80; } if (selfSigned) { if (subject != defaultSubject) { issuer = subject; issuerKey = subjectKey; } else { subject = issuer; subjectKey = issuerKey; } } if (subject == null) { throw new Exception("Missing Subject Name"); } X509CertificateBuilder cb = new X509CertificateBuilder(3); cb.SerialNumber = sn; cb.IssuerName = issuer; cb.NotBefore = notBefore; cb.NotAfter = notAfter; cb.SubjectName = subject; cb.SubjectPublicKey = subjectKey; // extensions if (bce != null) { cb.Extensions.Add(bce); } if (eku != null) { cb.Extensions.Add(eku); } // signature cb.Hash = hashName; byte[] rawcert = cb.Sign(issuerKey); if (p12file == null) { WriteCertificate(fileName, rawcert); } else { PKCS12 p12 = new PKCS12(); p12.Password = p12pwd; ArrayList list = new ArrayList(); // we use a fixed array to avoid endianess issues // (in case some tools requires the ID to be 1). list.Add(new byte [4] { 1, 0, 0, 0 }); Hashtable attributes = new Hashtable(1); attributes.Add(PKCS9.localKeyId, list); p12.AddCertificate(new X509Certificate(rawcert), attributes); if (issuerCertificate != null) { p12.AddCertificate(issuerCertificate); } p12.AddPkcs8ShroudedKeyBag(subjectKey, attributes); p12.SaveToFile(p12file); } Console.WriteLine("Success"); return(0); } catch (Exception e) { Console.WriteLine("ERROR: " + e.ToString()); Help(); } return(1); }
public AksStack() { var config = new Pulumi.Config(); var kubernetesVersion = config.Get("kubernetesVersion") ?? "1.16.9"; var resourceGroup = new ResourceGroup("aks-rg"); var password = new RandomPassword("password", new RandomPasswordArgs { Length = 20, Special = true, }).Result; var sshPublicKey = new PrivateKey("ssh-key", new PrivateKeyArgs { Algorithm = "RSA", RsaBits = 4096, }).PublicKeyOpenssh; // Create the AD service principal for the K8s cluster. var adApp = new Application("aks"); var adSp = new ServicePrincipal("aksSp", new ServicePrincipalArgs { ApplicationId = adApp.ApplicationId }); var adSpPassword = new ServicePrincipalPassword("aksSpPassword", new ServicePrincipalPasswordArgs { ServicePrincipalId = adSp.Id, Value = password, EndDate = "2099-01-01T00:00:00Z", }); // Grant networking permissions to the SP (needed e.g. to provision Load Balancers) var assignment = new Assignment("role-assignment", new AssignmentArgs { PrincipalId = adSp.Id, Scope = resourceGroup.Id, RoleDefinitionName = "Network Contributor" }); // Create a Virtual Network for the cluster var vnet = new VirtualNetwork("vnet", new VirtualNetworkArgs { ResourceGroupName = resourceGroup.Name, AddressSpaces = { "10.2.0.0/16" }, }); // Create a Subnet for the cluster var subnet = new Subnet("subnet", new SubnetArgs { ResourceGroupName = resourceGroup.Name, VirtualNetworkName = vnet.Name, AddressPrefix = "10.2.1.0/24", }); // Now allocate an AKS cluster. var cluster = new KubernetesCluster("aksCluster", new KubernetesClusterArgs { ResourceGroupName = resourceGroup.Name, DefaultNodePool = new KubernetesClusterDefaultNodePoolArgs { Name = "aksagentpool", NodeCount = 3, VmSize = "Standard_B2s", OsDiskSizeGb = 30, VnetSubnetId = subnet.Id, }, DnsPrefix = "sampleaks", LinuxProfile = new KubernetesClusterLinuxProfileArgs { AdminUsername = "******", SshKey = new KubernetesClusterLinuxProfileSshKeyArgs { KeyData = sshPublicKey, }, }, ServicePrincipal = new KubernetesClusterServicePrincipalArgs { ClientId = adApp.ApplicationId, ClientSecret = adSpPassword.Value, }, KubernetesVersion = kubernetesVersion, RoleBasedAccessControl = new KubernetesClusterRoleBasedAccessControlArgs { Enabled = true }, NetworkProfile = new KubernetesClusterNetworkProfileArgs { NetworkPlugin = "azure", DnsServiceIp = "10.2.2.254", ServiceCidr = "10.2.2.0/24", DockerBridgeCidr = "172.17.0.1/16", }, }); this.KubeConfig = cluster.KubeConfigRaw; }
private void PrintPaperBackup() { //TODO: THIS NEEDS TO BE RE-TESTED try { string numeratorCurrency = "BTC"; // Get the text for the paper backup. string receiptText = Environment.NewLine; receiptText += Environment.NewLine; receiptText += Environment.NewLine; receiptText += Environment.NewLine; receiptText += "DATE:" + DateTime.Now.ToString() + Environment.NewLine; receiptText += "TERMINAL:" + TerminalId + Environment.NewLine; receiptText += "TAG ID:" + TagId + Environment.NewLine; receiptText += "COIN NAME:" + numeratorCurrency + Environment.NewLine; receiptText += "===============================" + Environment.NewLine; receiptText += "STORE IN A SAFE PLACE - DO NOT LOSE THESE NUMBERS" + Environment.NewLine; receiptText += "PUBLIC ACCOUNT NUMBER: " + Environment.NewLine; receiptText += PublicKey + Environment.NewLine; receiptText += ""; int indx = 0; int sep = 0; int linebreak = 0; string output = ""; for (indx = 0; indx <= PrivateKey.Length - 1; indx++) { if (sep == 4) { output += " "; sep = 0; linebreak += 1; } if (linebreak == 4) { output += Environment.NewLine; linebreak = 0; } output += PrivateKey.Substring(indx, 1); sep++; } receiptText += "===============================" + Environment.NewLine; receiptText += "PRIVATE ACCOUNT NUMBER: " + Environment.NewLine; receiptText += output + Environment.NewLine; receiptText += "===============================" + Environment.NewLine; receiptText += "http://diamondcircle.net"; receiptText += Environment.NewLine; receiptText += Environment.NewLine; receiptText += Environment.NewLine; receiptText += Environment.NewLine; receiptText += Environment.NewLine; // Initialise the printer if required. if (!Factory.GetPrinter().Initialised) { try { Factory.GetPrinter().Initialise(); } catch (Exception ex) { lblStatusMessage.Text = "Cannot Print Paper Backup."; throw new System.InvalidOperationException("PrintPaperBackup: Cannot Print Paper Backup"); } } // Print the paper backup. ErrorCode writeErrorCode = Factory.GetPrinter().PrintText(receiptText); if (writeErrorCode != ErrorCode.None) { lblStatusMessage.Text = "Cannot Print Paper Backup."; throw new System.InvalidOperationException("PrintPaperBackup: Cannot Print Paper Backup"); } } catch (Exception ex) { GeneralExceptions("PrintPaperBackup", System.Diagnostics.TraceEventType.Critical, ex); ReturnToMainMenu(); } }
private Transaction GetTransaction(UInt256 nonce, long gasLimit, UInt256 gasPrice, Address to, byte[] data, PrivateKey privateKey) => Build.A.Transaction .WithNonce(nonce) .WithGasLimit(gasLimit) .WithGasPrice(gasPrice) .WithData(data) .To(to) .DeliveredBy(privateKey.PublicKey) .SignedAndResolved(_ethereumEcdsa, privateKey, 1) .TestObject;
private static PrivateKeys GetPrivateKeys(privkeys keys) { var privateKeys = new PrivateKeys(); foreach (account account in keys.account) { var privateKey = new PrivateKey(account.private_key.dsa.GetDSAParameters(true)); privateKey.AccountName = account.name; privateKey.Protocol = account.protocol; privateKeys.Add(privateKey); } return privateKeys; }
public ElasticGridNetworkTests(ILoggable logger, IElasticNode node, IPeerList peers, PrivateKey nodeKey) { Logger = logger; Node = node; Peers = peers; NodeKey = nodeKey; }
public override PrivateKey GetPrivate(string name) { string keyPath = Path.Combine (this.path, name + privateSuffix); PrivateKey key = new PrivateKey (File.ReadAllText (keyPath, Encoding.UTF8)); key.Name = name; return key; }
public PrivateKey GeneratePrivateKey() { PrivateKey key = new PrivateKey(); key.X = x; key.P = p; return key; }
public static Chunk ToChunk(Message m, PrivateKey signatureKey) { using (MemoryStream ms = new MemoryStream()) { ms.Write (Encoding.ASCII.GetBytes ("Whisper"), 0, 7); //Message Header MessageHeader header = new MessageHeader (); if (m is TreeMessage) header.MessageId = 1; if (m is RouteMessage) header.MessageId = 2; if (m is ListMessage) header.MessageId = 3; byte[] messageData = SerializeMessage (m); if (signatureKey != null) header.Signature = signatureKey.Sign (messageData); ProtocolParser.WriteBytes (ms, MessageHeader.SerializeToBytes (header)); ProtocolParser.WriteBytes (ms, messageData); //Generate Chunk Data byte[] data = ms.ToArray (); return new Chunk (data); } }
public abstract void InitSign(PrivateKey key);
public Buy2Test(ITestOutputHelper outputHelper) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.TestOutput(outputHelper) .CreateLogger(); _initialState = new State(); var sheets = TableSheetsImporter.ImportSheets(); foreach (var(key, value) in sheets) { _initialState = _initialState .SetState(Addresses.TableSheet.Derive(key), value.Serialize()); } _tableSheets = new TableSheets(sheets); var currency = new Currency("NCG", 2, minters: null); _goldCurrencyState = new GoldCurrencyState(currency); _sellerAgentAddress = new PrivateKey().ToAddress(); var sellerAgentState = new AgentState(_sellerAgentAddress); _sellerAvatarAddress = new PrivateKey().ToAddress(); var rankingMapAddress = new PrivateKey().ToAddress(); var sellerAvatarState = new AvatarState( _sellerAvatarAddress, _sellerAgentAddress, 0, _tableSheets.GetAvatarSheets(), new GameConfigState(), rankingMapAddress) { worldInformation = new WorldInformation( 0, _tableSheets.WorldSheet, GameConfig.RequireClearedStageLevel.ActionsInShop), }; sellerAgentState.avatarAddresses[0] = _sellerAvatarAddress; _buyerAgentAddress = new PrivateKey().ToAddress(); var buyerAgentState = new AgentState(_buyerAgentAddress); _buyerAvatarAddress = new PrivateKey().ToAddress(); _buyerAvatarState = new AvatarState( _buyerAvatarAddress, _buyerAgentAddress, 0, _tableSheets.GetAvatarSheets(), new GameConfigState(), rankingMapAddress) { worldInformation = new WorldInformation( 0, _tableSheets.WorldSheet, GameConfig.RequireClearedStageLevel.ActionsInShop), }; buyerAgentState.avatarAddresses[0] = _buyerAvatarAddress; var equipment = ItemFactory.CreateItemUsable( _tableSheets.EquipmentItemSheet.First, Guid.NewGuid(), 0); var shopState = new ShopState(); shopState.Register(new ShopItem( _sellerAgentAddress, _sellerAvatarAddress, Guid.NewGuid(), new FungibleAssetValue(_goldCurrencyState.Currency, 100, 0), equipment)); var result = new CombinationConsumable.ResultModel() { id = default,
/// <summary> /// Generates a new public/private key pair as objects /// </summary> public void GenerateNewKeyset(ref PublicKey publicKey, ref PrivateKey privateKey) { string PublicKeyXML = null; string PrivateKeyXML = null; GenerateNewKeyset(ref PublicKeyXML, ref PrivateKeyXML); publicKey = new PublicKey(PublicKeyXML); privateKey = new PrivateKey(PrivateKeyXML); }
public override void InitSign (PrivateKey key) { sa.ImportParameters (((DSAPrivateKey)key).Parameters); }
/// <summary> /// Decrypts data using the provided private key /// </summary> public Data Decrypt(Data encryptedData, PrivateKey PrivateKey) { _rsa.ImportParameters(PrivateKey.ToParameters()); return DecryptPrivate(encryptedData); }
public static async Task Main(string[] args) { Options options = Options.Parse(args, Console.Error); var loggerConfig = new LoggerConfiguration(); loggerConfig = options.Debug ? loggerConfig.MinimumLevel.Debug() : loggerConfig.MinimumLevel.Information(); loggerConfig = loggerConfig .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Console(); Log.Logger = loggerConfig.CreateLogger(); try { IRichStore store = LoadStore(options); var pendingTxs = store.IterateStagedTransactionIds() .ToImmutableHashSet(); store.UnstageTransactionIds(pendingTxs); Log.Debug("Pending txs unstaged. [{PendingCount}]", pendingTxs.Count); IBlockPolicy <AppAgnosticAction> policy = new DumbBlockPolicy( new BlockPolicy <AppAgnosticAction>( null, blockIntervalMilliseconds: options.BlockIntervalMilliseconds, minimumDifficulty: options.MinimumDifficulty, difficultyBoundDivisor: options.DifficultyBoundDivisor) ); var blockChain = new BlockChain <AppAgnosticAction>(policy, store, store, options.GenesisBlock); Startup.PreloadedSingleton = false; Startup.BlockChainSingleton = blockChain; Startup.StoreSingleton = store; IWebHost webHost = WebHost.CreateDefaultBuilder() .UseStartup <ExplorerStartup <AppAgnosticAction, Startup> >() .UseSerilog() .UseUrls($"http://{options.Host}:{options.Port}/") .Build(); Swarm <AppAgnosticAction> swarm = null; if (options.Seeds.Any()) { string aggregatedSeedStrings = options.SeedStrings.Aggregate(string.Empty, (s, s1) => s + s1); Console.Error.WriteLine( $"Seeds are {aggregatedSeedStrings}"); // TODO: Take privateKey as a CLI option // TODO: Take appProtocolVersion as a CLI option // TODO: Take host as a CLI option // TODO: Take listenPort as a CLI option if (options.IceServer is null) { Console.Error.WriteLine( "error: -s/--seed option requires -I/--ice-server as well." ); Environment.Exit(1); return; } Console.Error.WriteLine("Creating Swarm."); var privateKey = new PrivateKey(); // FIXME: The appProtocolVersion should be fixed properly. var swarmOptions = new SwarmOptions { MaxTimeout = TimeSpan.FromSeconds(10), }; swarm = new Swarm <AppAgnosticAction>( blockChain, privateKey, options.AppProtocolVersionToken is string t ? AppProtocolVersion.FromToken(t) : default(AppProtocolVersion), differentAppProtocolVersionEncountered: (p, pv, lv) => true, workers: options.Workers, iceServers: new[] { options.IceServer }, options: swarmOptions ); } using (var cts = new CancellationTokenSource()) using (swarm) { Console.CancelKeyPress += (sender, eventArgs) => { eventArgs.Cancel = true; cts.Cancel(); }; try { await Task.WhenAll( webHost.RunAsync(cts.Token), StartSwarmAsync(swarm, options.Seeds, cts.Token) ); } catch (OperationCanceledException) { await swarm?.StopAsync(waitFor : TimeSpan.FromSeconds(1)) .ContinueWith(_ => NetMQConfig.Cleanup(false)); } } } catch (InvalidOptionValueException e) { string expectedValues = string.Join(", ", e.ExpectedValues); Console.Error.WriteLine($"Unexpected value given through '{e.OptionName}'\n" + $" given value: {e.OptionValue}\n" + $" expected values: {expectedValues}"); } }
public void Install(PrivateKey pk, Crt crt, IEnumerable<PKI.Crt> chain, IPkiTool cp) { AssertNotDisposed(); string pkPem; using (var ms = new MemoryStream()) { cp.ExportPrivateKey(pk, EncodingFormat.PEM, ms); pkPem = Encoding.UTF8.GetString(ms.ToArray()); } string crtPem; using (var ms = new MemoryStream()) { cp.ExportCertificate(crt, EncodingFormat.PEM, ms); crtPem = Encoding.UTF8.GetString(ms.ToArray()); } string chainPem = null; if (chain != null) { using (var ms = new MemoryStream()) { foreach (var c in chain) { cp.ExportCertificate(c, EncodingFormat.PEM, ms); } chainPem = Encoding.UTF8.GetString(ms.ToArray()); } } using (var client = new AmazonIdentityManagementServiceClient( CommonParams.ResolveCredentials(), CommonParams.RegionEndpoint)) { var iamRequ = new UploadServerCertificateRequest { PrivateKey = pkPem, CertificateBody = crtPem, CertificateChain = chainPem, ServerCertificateName = this.ServerCertificateName, Path = this.Path }; var iamResp = client.UploadServerCertificate(iamRequ); // TODO: any checks we should do? } }
private EncryptingStream(Stream baseStream, PrivateKey key, AccessMode accessMode) : base(baseStream, key, accessMode, EncryptionMode.Encrypt) { }
private KeyStore(PrivateKey privateKey, ExternalAddress address) { PrivateKey = privateKey; Address = address; }
static public string DecryptionToString(byte[] data, PrivateKey key, bool DoOAEPPadding) { byte[] decrypted = DecryptionToByteArray(data, key, DoOAEPPadding); return Encoding.UTF8.GetString(decrypted, 0, decrypted.Length); }
public static EncryptingStreamReader Read(Stream baseStream, PrivateKey key) => new EncryptingStreamReader(new EncryptingStream(baseStream, key, AccessMode.Read));
static public byte[] DecryptionToByteArray(byte[] data, PrivateKey key, bool DoOAEPPadding) { try { byte[] decryptedData = null; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { rsa.ImportParameters(key); decryptedData = rsa.Decrypt(data, DoOAEPPadding); } return decryptedData; } catch (CryptographicException e) { Debug.Log(e.ToString()); } return null; }
public static EncryptingStreamReader Read(string stream, PrivateKey key) => Read(new MemoryStream(stream.ToBytes()), key);
/// <summary> /// Decrypts data using the default private key /// </summary> public Data Decrypt(Data encryptedData) { PrivateKey PrivateKey = new PrivateKey(); PrivateKey.LoadFromConfig(); return Decrypt(encryptedData, PrivateKey); }
public static EncryptingStreamWriter Write(string stream, PrivateKey key) => Write(new MemoryStream(stream.ToBytes()), key);
public void Uninstall(PrivateKey pk, Crt crt, IEnumerable<PKI.Crt> chain, IPkiTool cp) { AssertNotDisposed(); using (var client = new AmazonIdentityManagementServiceClient( CommonParams.ResolveCredentials(), CommonParams.RegionEndpoint)) { var iamRequ = new DeleteServerCertificateRequest { ServerCertificateName = this.ServerCertificateName, }; var iamResp = client.DeleteServerCertificate(iamRequ); // TODO: any checks we should do? } }
public static EncryptingStreamWriter Write(Stream baseStream, PrivateKey key) => new EncryptingStreamWriter(new EncryptingStream(baseStream, key, AccessMode.Write));
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private String generateSignature(java.security.PrivateKey privateKey, String data) throws com.adobe.adobepass.accessenabler.api.AccessEnablerException private string generateSignature(PrivateKey privateKey, string data) { try { Signature rsaSigner = Signature.getInstance("SHA256WithRSA"); rsaSigner.initSign(privateKey); rsaSigner.update(data.GetBytes()); sbyte[] signature = rsaSigner.sign(); return new string(Base64.encode(signature, Base64.DEFAULT)); } catch (Exception e) { Log.e(TAG, e.ToString()); throw new AccessEnablerException(); } }
public ExtKey GetParentExtKey(ExtPubKey parent) { if (parent == null) { throw new ArgumentNullException("parent"); } if (Depth == 0) { throw new InvalidOperationException("This ExtKey is the root key of the HD tree"); } if (IsHardened) { throw new InvalidOperationException("This private key is hardened, so you can't get its parent"); } var expectedFingerPrint = parent.CalculateChildFingerprint(); if (parent.Depth != this.Depth - 1 || !expectedFingerPrint.SequenceEqual(vchFingerprint)) { throw new ArgumentException("The parent ExtPubKey is not the immediate parent of this ExtKey", "parent"); } byte[] l = null; byte[] ll = new byte[32]; byte[] lr = new byte[32]; var pubKey = parent.PubKey.ToBytes(); l = Hashes.BIP32Hash(parent.vchChainCode, nChild, pubKey[0], pubKey.Skip(1).ToArray()); Array.Copy(l, ll, 32); Array.Copy(l, 32, lr, 0, 32); var ccChild = lr; BigInteger parse256LL = new BigInteger(1, ll); BigInteger N = ECKey.CURVE.N; if (!ccChild.SequenceEqual(vchChainCode)) { throw new InvalidOperationException("The derived chain code of the parent is not equal to this child chain code"); } var keyBytes = PrivateKey.ToBytes(); var key = new BigInteger(1, keyBytes); BigInteger kPar = key.Add(parse256LL.Negate()).Mod(N); var keyParentBytes = kPar.ToByteArrayUnsigned(); if (keyParentBytes.Length < 32) { keyParentBytes = new byte[32 - keyParentBytes.Length].Concat(keyParentBytes).ToArray(); } var parentExtKey = new ExtKey { vchChainCode = parent.vchChainCode, nDepth = parent.Depth, vchFingerprint = parent.Fingerprint, nChild = parent.nChild, key = new Key(keyParentBytes) }; return(parentExtKey); }