What will be analog of this code in PHP? I am not able to port this piece of code on PHP.
internal void GenerateKeyPair()
{
ecKey = new ECKey();
GeneratedPublicKey = new ECPublicKey()
{
X = ecKey.X,
Y = ecKey.Y,
CurveOId = ecKey.CurveOId
};
}
openssl_pkey_new() can generate a private key, see the Documentation for an example with private/public key usage.
Related
I am using Google API for the first time and I want to use Natural Language API.
But I don't know how.
So I search the internet and found an example code.
But when it uses APIs, the program throws an exception.
problem source code and thrown exception:
using Google.Cloud.Language.V1;
using System;
namespace GoogleCloudSamples
{
public class QuickStart
{
public static void Main(string[] args)
{
// The text to analyze.
string text = "Hello World!";
try
{
var client = LanguageServiceClient.Create();
var response = client.AnalyzeSentiment(new Document()
{
Content = text,
Type = Document.Types.Type.PlainText
});
var sentiment = response.DocumentSentiment;
Console.WriteLine($"Score: {sentiment.Score}");
Console.WriteLine($"Magnitude: {sentiment.Magnitude}");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
The console output:
The Application Default Credentials are not available.
They are available if running on Google Compute Engine.
Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials.
See https://developers.google.com/accounts/docs/application-default-credentials for more information.
What should I do?
I had used NLP a year ago for entity analysis. I had used Google.Apis.CloudNaturalLanguage.v1. I put together my code with what you have written for sentiment analysis. You will need the API key for this:
var service = new CloudNaturalLanguageService(new CloudNaturalLanguageService.Initializer { ApiKey = ApiKey });
var req = new AnalyzeSentimentRequest {
Document = new Document()
{
Content = text,
Type = Document.Types.Type.PlainText
},
EncodingType = "UTF8"
};
var output = service.Documents.AnalyzeSentiment(req);
var exe = output.Execute();
Hope this works.
I need to decrypt some data in Flex that is encrypted in C# and written to a file.
I settled on blowfish for simplicity's sake using the as3crypto As3 library and Bruce Schneier C# library.
AS3 as3crypto link
Bruce Schneier C# blowfish link
I can get a short string to encrypt in C# and decrypt in Flex fine
however longer strings just fail to produce results and I do not know what I am missing?
C#:
string reportstring = "watson?";
BlowFish b = new BlowFish("04B915BA43FEB5B6");
string cipherText = b.Encrypt_ECB(reportstring);
String plainText = b.Decrypt_ECB(cipherText);
AS3:
var txt:String = "watson?";
var key:ByteArray = Hex.toArray("04B915BA43FEB5B6");
var blowfish:BlowFishKey = new BlowFishKey(key);
var dataBytes:ByteArray = new ByteArray();
dataBytes=Hex.toArray(Hex.fromString(txt));
blowfish.encrypt(dataBytes);
blowfish.decrypt(dataBytes);
Update, some samples
working
encrypt string = "watson?"
C# produces: 1514ea36fecfd5f5
AS3 produces: 1514ea36fecfd5f5
not working
encrypt string = "whats up watson?"
C# produces: 3ea9808a4b9f74aaa8e54fe682947673
AS3 produces: 3ea9808a4b9f74aa20776174736f6e3f
which is very similar but not matching
if I decrypt the AS3 cipher in C# I get :
whats up?`r???
if I decrypt the C# cipher in AS3 I get :
whats up¨åO悔vs
The AS3 code seems to be incorrect. Working example code:
import com.hurlant.util.Hex;
import com.hurlant.util.Base64;
import com.hurlant.crypto.Crypto;
import flash.utils.ByteArray;
import com.hurlant.crypto.symmetric.IPad;
import com.hurlant.crypto.symmetric.ICipher;
import com.hurlant.crypto.symmetric.NullPad;
import com.hurlant.crypto.symmetric.BlowFishKey;
function encrypt($text:String, $cryptKey:ByteArray):String
{
var iPad:IPad = new NullPad();
var crypt = Crypto.getCipher('blowfish-ecb',$cryptKey,iPad);
var cryptText:ByteArray = new ByteArray();
cryptText.writeUTFBytes( $text );
crypt.encrypt( cryptText );
trace( Hex.fromArray( cryptText ) );
return null;
}
var txt:String = "whats up watson?";
var key:ByteArray = Hex.toArray("04B915BA43FEB5B6");
encrypt(txt, key);
Answer to "how do I decrypt the string afterwards":
var encodedtxt:String = Hex.fromArray(cryptText);
cryptText = Hex.toArray(encodedtxt);
crypt.decrypt(cryptText);
package
{
import com.hurlant.crypto.Crypto;
import com.hurlant.crypto.prng.Random;
import com.hurlant.crypto.symmetric.ICipher;
import com.hurlant.util.Base64;
import com.hurlant.util.Hex;
import flash.utils.ByteArray;
import mx.utils.Base64Decoder;
import mx.utils.Base64Encoder;
public class EncryptionManager
{
public function EncryptionManager()
{
}
public function enCrypt(data:String, keyStr:String):String
{
var key:ByteArray;
var fileBytes:ByteArray = Hex.toArray(Hex.fromString(data));
key = Hex.toArray(Hex.fromString(keyStr));
var aes:ICipher = Crypto.getCipher("blowfish-ecb", key, Crypto.getPad("pkcs5"));
aes.encrypt(fileBytes);
var enc:Base64Encoder = new Base64Encoder();
enc.encodeBytes(fileBytes);
var result:String = enc.flush();
return result;
}
public function deCrypt(data:String, keyStr:String):String
{
var key:ByteArray;
var dec:Base64Decoder = new Base64Decoder();
dec.decode(data);
var fileBytes:ByteArray = dec.toByteArray();
key = Hex.toArray(Hex.fromString(keyStr));
var aes:ICipher = Crypto.getCipher("blowfish-ecb", key, Crypto.getPad("pkcs5"));
aes.decrypt(fileBytes);
return fileBytes.toString();
}
}
}
Try out this Class that might solve your problem.
I am trying co import a .pem key into c#, and I've found a library, which does that: BouncyCastle
I've created a code, which loads public key and is supposed to load the data into DSACryptoServiceProvider:
DSA dsa;
using (StreamReader rdr = new StreamReader(#"pubkey.pem"))
{
PemReader pr = new PemReader(rdr);
DsaPublicKeyParameters o = pr.ReadObject() as DsaPublicKeyParameters;
CspParameters prm = new CspParameters(13);
prm.Flags = System.Security.Cryptography.CspProviderFlags.UseMachineKeyStore;
//o.Parameters.
dsa = new DSACryptoServiceProvider(prm);
DSAParameters dp = new DSAParameters();
dp.G = o.Parameters.G.ToByteArray();
dp.P = o.Parameters.P.ToByteArray();
dp.Q = o.Parameters.Q.ToByteArray();
dp.Y = o.Y.ToByteArray();
if (o.Parameters.ValidationParameters != null)
{
dp.Counter = o.Parameters.ValidationParameters.Counter;
dp.Seed = o.Parameters.ValidationParameters.GetSeed();
}
//todo: missing: J, X?
dsa.ImportParameters(dp);
}
it crashes on dsa.ImportParameters(dp); with following exception: Cryptographic exception:bad data.
What should I change for this to work?
You need to use the ToByteArrayUnsigned method instead of plain ToByteArray one as otherwise there are cases where the byte array representation ends up with a leading zero byte which breaks everything :)
Can someone please help me convert the following two lines of python to C#.
hash = hmac.new(secret, data, digestmod = hashlib.sha1)
key = hash.hexdigest()[:8]
The rest looks like this if you're intersted:
#!/usr/bin/env python
import hmac
import hashlib
secret = 'mySecret'
data = 'myData'
hash = hmac.new(secret, data, digestmod = hashlib.sha1)
key = hash.hexdigest()[:8]
print key
Thanks
You could use the HMACSHA1 class to compute the hash:
class Program
{
static void Main()
{
var secret = "secret";
var data = "data";
var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(secret));
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(data));
Console.WriteLine(BitConverter.ToString(hash));
}
}
What is PHP for C# (asuming we open some local (on server) file instead of OpenFileDialog
private const int HEADER_LENGTH = 13;
stream = File.OpenRead(openFileDialog.FileName);
header = ReadBytes(stream, HEADER_LENGTH);
And will we be able to do something like this in PHP as a next step
private const byte SIGNATURE1 = 0x46;
private const byte SIGNATURE2 = 0x4C;
private const byte SIGNATURE3 = 0x56;
if ((SIGNATURE1 != header[0]) || (SIGNATURE2 != header[1]) || (SIGNATURE3 != header[2]))
throw new InvalidDataException("Not a valid FLV file!.");
Hmm, I think you look for something like that
$handle = fopen(FILE, 'r');
if ($handle)
{
$head = fread ( $handle , 13 );
if ($head[0] != chr (0x46)) ...
...
}
Of course you can create constants for this signature, but this way:
define('SIG1', chr(0x46));
then you can use them as normal: $head[0] == SIG1 etc. You can use functions when defining constants, for both constant names and values.
Use fopen and fread:
$fh = fopen($filename, "r");
if ($fh) {
$data = fread($fh, 13);
}
PHP supports the []-operator on strings, so you will be able to validate the signature in basically the same way as you did in C#.