I have added pointycastle and generated a keypair, encrypting the trial "Hello World" string. From this, I want to get the values of the Private and Public Key. Is there anywhere they are stored, because whenever I try to print the values of keyPair.privateKey, it returns Instance of 'RSAPrivateKey.
Here is the code I used
var keyParams = new RSAKeyGeneratorParameters(new BigInt.from(65537), 2048, 5);
var secureRandom = new FortunaRandom();
var random = new Random.secure();
List<int> seeds = [];
for (int i = 0; i < 32; i++) {
seeds.add(random.nextInt(255));
}
secureRandom.seed(new KeyParameter(new Uint8List.fromList(seeds)));
var rngParams = new ParametersWithRandom(keyParams, secureRandom);
var k = new RSAKeyGenerator();
k.init(rngParams);
var keyPair = k.generateKeyPair();
var cipher = new RSAEngine()..init( true, new PublicKeyParameter<RSAPublicKey>(keyPair.publicKey));
print("pubkey: ${keyPair.publicKey.toString()}");
var cipherText = cipher.process(new Uint8List.fromList("Hello World".codeUnits));
print("Encrypted: ${new String.fromCharCodes(cipherText)}");
cipher.init( false, new PrivateKeyParameter<RSAPrivateKey>(keyPair.privateKey));
//cipher.init( false, new PrivateKeyParameter(keyPair.privateKey) )
var decrypted = cipher.process(cipherText);
print("Decrypted: ${new String.fromCharCodes(decrypted)}");
Make sure to import package:pointycastle/asymmetric/api.dart, then use:
var k = RSAKeyGenerator()..init(rngParams);
AsymmetricKeyPair<PublicKey, PrivateKey> keyPair = k.generateKeyPair();
RSAPrivateKey privateKey = keyPair.privateKey;
RSAPublicKey publicKey = keyPair.publicKey;
print(privateKey.d); // prints private exponent
print(publicKey.n); // prints modulus
Recreate from the individual parts:
RSAPrivateKey foo = RSAPrivateKey(
privateKey.n,
privateKey.d,
privateKey.p,
privateKey.q,
);
RSAPublicKey bar = RSAPublicKey(publicKey.n, publicKey.e);
Related
I did generate a signature using the below code but, I want a signature in IEEE P1336 (length 80) format
guard let signData = SecKeyCreateSignature(
key,
SecKeyAlgorithm.ecdsaSignatureMessageX962SHA256,
signatureString.data(using: .utf8)! as CFData, &error) else {
let e = error!.takeRetainedValue() as Error
print("Signing Error \( e.localizedDescription)")
return nil
}
let signedData = signData as Data
let signedString = signedData.base64EncodedString(options: [])
I am not an expert in iOS. But I fixed this issue for a signature generated by iOS. You can create this format by your own. e.g. for SHA-256 hashed signature. JavaScript sample
function parseASN1ToIEEEP1363(signature) {
const buffer = new ArrayBuffer(signature.length);
const int8View = new Int8Array(buffer);
for (let i = 0, strLen = signature.length; i < strLen; i++) {
int8View[i] = signature.charCodeAt(i);
}
//Currently these bytes getting for SHA256. for other hashings need to make it dynamic
const r = new Int8Array(buffer.slice(4, 36));
const s = new Int8Array(buffer.slice(39));
return appendBuffer(r, s);
}
function appendBuffer(buffer1, buffer2) {
var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
tmp.set(new Uint8Array(buffer1), 0);
tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
return tmp;
};
I'm trying to recreate an existing mobile apps into flutter but struggling in the "PBEWithMD5AndDES" encryption on android which I can't seem to find similar way in dart.
This is so far what I've tried to achieve the same using Flutter_Des.dart, Password_Hash.dart and Crypto.dart library but still can't get the same output.
encryptPassword(String keyStr, String passwordStr) async {
if (keyStr.length == 0 || passwordStr.length == 0) {
return "";
}
var generator = new PBKDF2(hashAlgorithm: md5);
String saltStr = generateSaltBase64String();
var hash = generator.generateBase64Key(keyStr, saltStr, round, keyLength);
var encryptBase64 = await FlutterDes.encryptToBase64(passwordStr, hash.toString());
return encryptBase64;
}
Below is what I have currently on Android.
KeySpec keySpec = new PBEKeySpec(str.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
ecipher = Cipher.getInstance("PBEWithMD5AndDES");
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
byte[] utf8 = password.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
enc = Base64.encode(enc, Base64.DEFAULT);
return new String(enc);
I'm expecting the same output as android so my backend able to decrypt it.
PBEWithMD5AndDES uses PBKDF1 to generate the key material (not PBKDF2). This gives you 128 bits of key material that you then use as two 64 bit halves as the key and the IV for DES.
Derive the key and IV as follows - I've plugged in some arbitrary values for iteration, password and salt and confirmed against JCrypto.
int iterations = 31;
List<int> salt = [0x21, 0x21, 0xf0, 0x55, 0xc3, 0x9f, 0x5a, 0x75];
List<int> password = utf8.encode('test');
List<int> saltedKey = password + salt;
Digest d = md5.convert(saltedKey);
for (int i = 1; i < iterations; i++) {
d = md5.convert(d.bytes);
}
print(d);
List<int> key = d.bytes.sublist(0, 8);
List<int> iv = d.bytes.sublist(8, 16);
print(key);
print(iv);
I can't find a Dart implementation of DES which takes a key and IV as bytes. triple_des wants them as strings - i.e. it's dumbed down. Pointy castle doesn't do DES. FlutterDes also seems to want strings. You might be able to modify triple_des to take binary keys and IVs. Or use a different cipher.
Solved by using flutter's methodchannel and call platform specific code to do the encryption and its working now. Thanks
I'm trying to use pointy castle to generate a public and private keypair using the secp256k1 curve. I think i have successfully created an AsymmetricKeyPair composed of an ECPrivateKey and ECPublicKey but i can't obtain their corresponding hex strings (something like this:
private:
ee792658c8eb1f8c3d2010ee6bc2ea328bb584fbecbfb17cf0f9103d122a8716,
public:
041b3f87beb2559aa3ca1c1d9ebb9447e4842d21cf0c70db103acc0db27ea8c27536fc2b1405b8a16a460ca089b01de8c556825927b4890b7236e357787f3e6d54).
When i try to print the keys, all i get is "Instance of 'ECPrivateKey'" and "Instance of 'ECPublicKey'" whether i use .toString() or not.
I have been looking around everywhere for a way to do this but i can't find one, is it even possible?
Here's my code:
SecureRandom secureRandom = new SecureRandom("Fortuna");
var random = new Random.secure();
List<int> seeds = [];
for (int i = 0; i < 32; i++) {
seeds.add(random.nextInt(255));
}
secureRandom.seed(new KeyParameter(new Uint8List.fromList(seeds)));
var domainParams = new ECDomainParameters("secp256k1");
var ecParams = new ECKeyGeneratorParameters(domainParams);
var params = new ParametersWithRandom<ECKeyGeneratorParameters>(
ecParams, secureRandom);
var keyGenerator = new ECKeyGenerator();
keyGenerator.init(params);
AsymmetricKeyPair keypair = keyGenerator.generateKeyPair();
ECPrivateKey privateKey = keypair.privateKey;
ECPublicKey publicKey = keypair.publicKey;
print(privateKey);
print(privateKey.toString());
print(publicKey);
print(publicKey.toString());
The private key and public point are member variables of their respective keys:
ECPrivateKey privateKey = keypair.privateKey;
ECPublicKey publicKey = keypair.publicKey;
// in decimal
print(privateKey.d);
print(publicKey.Q.x);
print(publicKey.Q.y);
// in hex
print(privateKey.d.toRadixString(16));
print(publicKey.Q.x.toBigInteger().toRadixString(16));
print(publicKey.Q.y.toBigInteger().toRadixString(16));
I'm new to coding. I am attempting to import e-mail addresses from a Google Sheet to my gmail account. Any help on why this code is not working would be greatly appreciated! Here is the code I have entered:
function myFunction() {
var alreadyAdded = "Already added";
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 396; // Number of rows to process
// Fetch the range of cells A2:F397
var dataRange = sheet.getRange(startRow, 1, numRows, 400
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for
var
for (var i = 0; i < data.length; ++i)
};
var row = data[i];
var lastName = row[0]
var firstName = row[1]
var emailAddress = row[2]
var address = row[3]
var notes = row[4]
if (addedAlready != alreadyAdded) {
// Create contact in Google Contacts
var contact = ContactsApp.createContact(firstName, lastName, emailAddress);
// Add values to new contact
contact.addAddress(address, "");
contact.setNotes(notes);
sheet.getRange(startRow + i, 7).setValue(alreadyAdded);
};
};
}
try it var dataRange = sheet.getRange(startRow, 1, numRows, 400);
How do I base64 encode a string in cloud code? The value is for a HTTP Basic Auth.
I have tried the following two approaches and I had no success.
var string = 'AQXTTPmj-boT_yDEPQXg9ezIOIM7O:EMx6RLr8jF3S6YYo-X4bZ';
var buffer1 = new Buffer(string, 'base64');
var b3 = buffer1.toString('base64');
console.log(b3);
var string = 'AQXTTPmj-boT_yDEPQXg9ezIOIM7O:EMx6RLr8jF3S6YYo-X4bZ';
var encodeString = Base64.encode(string);
console.log(encodeString);
You send your string to the Buffer constructor and use toString method to convert it to base64 like this:
var string = 'AQXTTPmj-boT_yDEPQXg9ezIOIM7O:EMx6RLr8jF3S6YYo-X4bZ';
var buffer1 = new Buffer(string);
var b3 = buffer1.toString('base64');
console.log(b3);
Also make sure you put var Buffer = require('buffer').Buffer; on top of your main.js file.