How to load encrypted bitcoin wallet.dat file in javascript? - bitcoin

I am trying to load the wallet.dat file in my react native app.
So far the function that I found online is not working.
Is there any effective way to load a bitcoin encrypted wallet.dat file in my application?
Wallet.dat has been created with the bitcoin core app.
function to parse wallet.dat file
var parseWalletdat = function parseWalletdat(data) {
var re = /\x30\x81\xD3\x02\x01\x01\x04\x20(.{32})/gm;
var dataHexStr = data.toString('latin1');
privateKeys = dataHexStr.match(re);
if (!privateKeys) {
return 'wallet is encrypted?';
}
}

If it's an encrypted Bitcoin wallet you wouldn't see the B?Der keys with just that search, even on an unencrypted wallet you wouldn't.
I suggest searching for a public key. and encoding the values into a bitcoin address for checking the balance.

Related

Google Cloud Storage report download no access

I am running node to download the sales report from google cloud storage.
I got the credentials.json file. Now the problem is every time I run my application I get "xxxxxxx#gmail.com" does not have storage.objects.get access to the Google Cloud Storage object".
Yes, this email is nowhere registered on the google cloud storage or given rights to, but it should work with the credentials alone, no?
The credentials are directly from the google cloud storage and have this information :
client_secret,project_id,redirect_uri,client_id...
My sample Code:
// Imports the Google Cloud client library.
const {Storage} = require('#google-cloud/storage');
const projectId = 'xxxxxxxxxxxxxxxxxx'
const key = 'credentials.json'
const bucketName = 'pubsite.......'
const destFileName = './test'
const fileName = 'salesreport_2020.zip'
// Creates a client
const storage = new Storage({projectId, key});
async function downloadFile() {
const options = {
destination: destFileName,
};
// Downloads the file
await storage.bucket(bucketName).file(fileName).download(options);
console.log(
`gs://${bucketName}/${fileName} downloaded to ${destFileName}.`
);
}
downloadFile().catch(console.error);
You are using the wrong type of credentials file.
Your code is written to use a service account JSON key file. You mention that the credentials file contains client_secret. That means you are trying to use OAuth 2.0 Client IDs.
Look in the file credentials.json. It should contain "type": "service_account". If you see {"installed": or {"web": at the start of the file, then you have the wrong credentials.
Creating and managing service account keys
Also, you are specifying the parameters wrong in the line:
const storage = new Storage({projectId, key});
Replace with:
const storage = new Storage({projectId: projectId, keyFilename: key});
Because you are seeing the random gmail address, that likely means the storage client is using Application default credentials instead of the ones you intend. There are two paths forward:
Embrace application default credentials. Remove the options you are passing in to the Storage constructor, and instead set the GOOGLE_APPLICATION_CREDENTIALS environmental variable to you json service account file.
Fix the Storage constructor to pass in credentials properly. The issue may be something as simple as you needing to pass the full path to the credentials file (ie /a/b/c/credentials.json). Possibly the storage options are not being processed right, try being explicit like
const storage = new Storage({projectId: 'your-project-id', keyFilename: '/path/to/keyfile.json'});

How to use YouTube Data API

I tried using YouTube Data API.
I really took a good look at everything I found on the internet. The code itself isn't the problem, but I did not find out, where to use this code. Do I simply create a python file (in Visual Studio Code for example) and run it there? Because it didn't work when I tried this...
I also saw many people using the API with the commander only, others used something in chrome (localhost:8888...). So I don`t really know what's the way to go or what I should do.
Thanks for any help :)
Best regards!
I'm not a python developer but as a guess you could start here:
https://developers.google.com/youtube/v3/quickstart/python
using pip to install the dependencies you need.
You should be able to create a simple python file that authenticates with the API and then calls a method on the on the google api client and then output it. There are some examples here:
https://github.com/youtube/api-samples/blob/master/python/
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
namespace Google.Apis.YouTube.Samples
{
/// <summary>
/// YouTube Data API v3 sample: upload a video.
/// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
/// See https://code.google.com/p/google-api-dotnet-client/wiki/GettingStarted
/// </summary>
internal class UploadVideo
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("YouTube Data API: Upload Video");
Console.WriteLine("==============================");
try
{
new UploadVideo().Run().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("Error: " + e.Message);
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private async Task Run()
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows an application to upload files to the
// authenticated user's YouTube channel, but doesn't allow other types of access.
new[] { YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = "Default Video Title";
video.Snippet.Description = "Default Video Description";
video.Snippet.Tags = new string[] { "tag1", "tag2" };
video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
var filePath = #"REPLACE_ME.mp4"; // Replace with path to actual movie file.
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
await videosInsertRequest.UploadAsync();
}
}
void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
{
switch (progress.Status)
{
case UploadStatus.Uploading:
Console.WriteLine("{0} bytes sent.", progress.BytesSent);
break;
case UploadStatus.Failed:
Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
break;
}
}
void videosInsertRequest_ResponseReceived(Video video)
{
Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
}
}
}
Make sure you have python installed on your PC
Create a project: Google’s APIs and Services dashboard
Enable the Youtube v3 API: API Library
Create credentials: Credentials wizard
Now you need to get an access token and a refresh token using the credentials you created
Find an authentication example in one of the following libraries:
https://github.com/googleapis/google-api-python-client
https://github.com/omarryhan/aiogoogle (for the async version)
Copy and paste the client ID and client secret you got from step 4 and paste them in the authentication example you found in step 6 (Should search for an OAuth2 example), this step should provide with an access token and a refresh token
Copy and paste a Youtube example from either:
https://github.com/googleapis/google-api-python-client
https://github.com/omarryhan/aiogoogle (for the async version)
Replace the access token and refresh token fields with the ones you got.
Now you should be able to run the file from any terminal by typing:
python3 yourfile.py
[EDIT]
The API key is not the same as the access token. There are 2 main ways to authenticate with Google APIs:
Access and refresh token
API_KEY.
API key won't work with personal info. You need to get an access and refresh token for that (method 1).
Once you get an access token, it acts in a similar fashion to the API_KEY you got. Getting an access token is a bit more complicated than only working with an API_KEY.
A refresh token is a token you get with the access token upon authentication. Access tokens expire after 3600 seconds. When they expire, your authentication library asks Google's servers for a new access token with the refresh token. The refresh token has a very long lifetime (often indefinite), so make sure you store it securely.
To get an access token and a refresh token (user credentials), you must first create client credentials. Which should consists of 1. a client ID and 2. a client secret. These are just normal strings.
You should also, set a redirect URL in your Google app console in order to properly perform the OAuth2 flow. The OAuth2 flow is the authentication protocol that many APIs rely on to allow them to act on a user's account with the consent of the user. (e.g. when an app asks you to post on your behalf or control your account on your behalf, it typically will use this protocol.)
Aiogoogle's docs does a decent job in explaining the authentication flow(s) available by Google.
https://aiogoogle.readthedocs.io/en/latest/
But this is an async Python library. If you're not familiar with the async syntax, you can read the docs just to get a general idea of how the authentication system works and then apply it to Google's sync Python library.
About point no.6. The links I posted with Aiogoogle being one of them, are just client libraries that help you access Google's API quicker and with less boilerplate. Both libraries have documentation, where they have links to examples on how to use them. So, open the documentation, read it, search for the examples posted, try to understand how the code in the example(s) work. Then maybe download it and run it on your own machine.
I recommend that your read the docs. Hope that helps.

Using Asymmetric Key on .Net Core

I am trying to run code from this sample
https://learn.microsoft.com/en-us/dotnet/standard/security/how-to-store-asymmetric-keys-in-a-key-container
Under .NetCore 2.0 (Web application).
However when I try to execute any line using
CspParameters
I get the following error
'CspParameters' requires Windows Cryptographic API (CAPI), which is not available on this platform.
Suggestions please on how I work around this.
Thanks.
.NET does not store cryptographic keys, that's ultimately a feature that is (or isn't) provided by the cryptographic platform it builds on top of.
To use CspParameters with .NET Core you have to run on Windows; because that's a very thin wrapper over the (old) Windows Cryptographic API. You can't use it in UAP, because UAP only allows the newer Cryptography: Next Generation (CNG) API.
macOS can store keys in a Keychain, but .NET Core doesn't provide API to read them out.
Linux (OpenSSL) does not have any key storage mechanism other than "save this to a file and load it again", but .NET Core does not support loading asymmetric keys from files.
The only way to accomplish your goal in a cross-platform mechanism is to have your asymmetric key associated with an X.509 certificate. If you build the X509Certificate2 object for which HasPrivateKey returns true you can save it to a PFX/PKCS#12 file and then load from that file; or you can add it to an X509Store instance (the "My" store for CurrentUser is the one that works best across the platforms) and then read it back from the X509Store instance.
Despite the page you referenced claiming to be written in 2017, what it really means is the content was moved from its previous location on msdn.microsoft.com on that date. The original page was written in 2008 (at least, that's the first hit on web.archive.org), so it long predated .NET Core.
You can now do it cross-platform and it works as long as you are on .netcore 3.0 or higher and you add the latest System.Security.Cryptography.Cng nuget package (NB! this will ONLY work if your project is NOT multi-targeted - it can ONLY target netcoreapp3.0) :
using (ECDsa key = ECDsa.Create())
{
key.ImportPkcs8PrivateKey(Convert.FromBase64String(privateKey), out _);
return Jose.JWT.Encode
(
payload: payload,
key: key,
algorithm: JwsAlgorithm.ES256,
extraHeaders: extraHeader
);
}
So just wanted to offer another option we found once we encountered this error. That CSP Parameters error is related to the RSACryptoServiceProvider . This has some issues with cross platform .NET Core. We found a Github issue that mentioned to use RSA.Create() method instead. I was using a Bouncy Castle library that still uses the RSACryptoServiceProvider. At the time of writing this answer, it looked like this.
public static RSA ToRSA(RsaPrivateCrtKeyParameters privKey)
{
RSAParameters rp = ToRSAParameters(privKey);
RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider();
rsaCsp.ImportParameters(rp);
return rsaCsp;
}
So we just replaced it with a private method in the class that looked like this.
private RSA ToRSA(RsaPrivateCrtKeyParameters parameters)
{
RSAParameters rp = DotNetUtilities.ToRSAParameters(parameters);
return RSA.Create(rp);
}
This ran in linux, no errors. Bouncy probably just needs to update their libs.
Use this method to import public key from the Key string make sure to install BouncyCastle.NetCore nuget package
public static RSACryptoServiceProvider ImportPublicKey(string pem)
{
PemReader pr = new PemReader(new StringReader(pem));
AsymmetricKeyParameter publicKey = (AsymmetricKeyParameter)pr.ReadObject();
RSAParameters rsaParams = DotNetUtilities.ToRSAParameters((RsaKeyParameters)publicKey);
RSACryptoServiceProvider csp = new RSACryptoServiceProvider();// cspParams);
csp.ImportParameters(rsaParams);
return csp;
}
And then you can encrypt your data as shown below
public static string Encryption(string data,string publickey)
{
var testData = Encoding.GetEncoding("iso-8859-1").GetBytes(strText);
using (var rsa = ImportPublicKey(publickey))
{
try
{
var encryptedData = rsa.Encrypt(testData, false);
var base64Encrypted = Convert.ToBase64String(encryptedData);
return base64Encrypted;
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
}

How does a desktop app sign a message using Microsoft Passport (Windows Hello)?

Using Microsoft Password (Windows Hello), a user is given a public/private keypair when they set up a PIN for their local account. This keypair is stored on the computer's TPM.
You can create a certificate for your account by asking the Start Menu to "Set up PIN Sign-in".
The following article describes the APIs used in a UWP ("Metro") app: https://msdn.microsoft.com/en-us/windows/uwp/security/microsoft-passport
There are APIs for fetching the user's public key, and signing a message:
var openKeyResult = await KeyCredentialManager.OpenAsync(AccountId);
if (openKeyResult.Status == KeyCredentialStatus.Success)
{
var userKey = openKeyResult.Credential;
var publicKey = userKey.RetrievePublicKey();
var signResult = await userKey.RequestSignAsync(message);
if (signResult.Status == KeyCredentialStatus.Success)
{
return signResult.Result;
}
else if (signResult.Status == KeyCredentialStatus.UserPrefersPassword)
{
}
}
How do I fetch the public key and sign a message using a desktop app (Win32)?
I have checked using certmgr.msc: the Microsoft Passport certificate sadly does not appear in the user's "Personal" certificate store, so I can't see a way to access it using the CryptoAPI/CNG, which my app already supports.
Ideally I would like to make a standalone signature. It would be interesting/useful to know if it's possible to use the Passport certificate with SChannel as a client certificate.

webkitDeprecatedRTCPeerConnection, DeprecatedRTCPeerConnection, RTCPeerConnection are not supported

I am trying to implement WebRTC. I am trying to create P2P connection using
var peerC = new webkitDeprecatedRTCPeerConnection("STUN stun.l.google.com:19302", onSignal);
Here, onSignal is:
// when PeerConn is created, send setup data to peer via WebSocket
function onSignal(message) {
socket.send(message);
}
// when remote adds a stream, hand it on to the local video element
function onRemoteStreamAdded(event) {
remotevid.src = window.webkitURL.createObjectURL(event.stream);
document.getElementById('anim').style.visibility='visible';
}
// when remote removes a stream, remove it from the local video element
function onRemoteStreamRemoved(event) {
remotevid.src = "";
}
But this do not work for me. Even if I use any of webkitDeprecatedRTCPeerConnection, DeprecatedRTCPeerConnection, RTCPeerConnection, nothing proceeds.
Some help would be really thankfull.
Use webkitRTCPeerConnection or even better, use https://github.com/webrtc/adapter which shims RTCPeerConnection.
See also https://webrtc.github.io/samples/ for a large amount of maintained samples how to use the WebRTC API in the browser.