I‘m a rookie in PointyCastle,how can I generate ecc base64 key pairs with PointyCastle in dart
AsymmetricKeyPair<PublicKey, PrivateKey> generateKeyPair({curve = 'secp256r1'}) {
var param = curve == 'secp256r1' ? ECCurve_secp256r1() : ECCurve_secp256k1();
var keyParams = ECKeyGeneratorParameters(param);
var random = FortunaRandom();
random.seed(KeyParameter(_seed()));
var generator = ECKeyGenerator();
generator.init(ParametersWithRandom(keyParams, random));
return generator.generateKeyPair();
}
Uint8List _seed() {
var random = Random.secure();
var seed = List<int>.generate(32, (_) => random.nextInt(256));
return Uint8List.fromList(seed);
}
above I can generate a AsymmetricKeyPair object,how to get public base64 and private base64 like my already done js bundle
{"priKey":"CVK3r/UxdGCwQBjtn5vN/orUMxKf9E/1TlJzLkMz9t4=","pubKey":"BJH/mWJqgchGxXGA5/E79SsWRwVo3rpduBmD8FOs7UlKiK8PIvwrkCDvUcwhKdysW35OByPjoVcwFqg1NyumLKM="}
besides, at first I want to use my js bundle file in flutter android, but that would be very tough as I know
how to use js bundle in flutter android
I also need to make sign and verify function with ecdsa in sha256
Signer signer = new Signer('SHA-256/ECDSA');
// 签名,参数:私钥,明文
ECSignature sign(String privateKeyStr, String txt) {
SecureRandom random = _setRadom();
// how to convert a plain txt to kTestBytes
final Uint8List kTestBytes = new Uint8List.fromList([1, 2, 3]);
// if I pass in base64 privateKey str, is the radix 64?
ECPrivateKey privateKey = new ECPrivateKey(BigInt.parse(privateKeyStr, radix: 10), ecDomain);
PrivateKeyParameter signParams = new PrivateKeyParameter(privateKey);
signer.init(true, new ParametersWithRandom(signParams, random));
ECSignature signature = signer.generateSignature(kTestBytes) as ECSignature;
return signature;
}
// 验签
// 参数: 明文,签名,公钥
bool verify(txt, signature, publicKey) {
// how to make the txt to kTestBytes
var kTestBytes = txt
signer.init(false, new PublicKeyParameter(publicKey));
bool verify = signer.verifySignature(kTestBytes, signature);
// print(verify);
return verify;
}
// I don't know what this function actually do,as I know in other language ecdsa don;t need a random number.
SecureRandom _setRadom() {
List<int> key = [67, 3, 241, 75, 143, 78, 115, 99, 21, 242, 180, 43, 26, 7, 194, 20];
List<int> iv = [87, 117, 137, 182, 2, 199, 132, 230, 120, 12, 109, 177, 34, 197, 186, 206];
KeyParameter keyParam = new KeyParameter(new Uint8List.fromList(key));
ParametersWithIV<KeyParameter> paramsIV = new ParametersWithIV(keyParam, new Uint8List.fromList(iv));
SecureRandom random = new SecureRandom('AES/CTR/AUTO-SEED-PRNG')..seed(paramsIV);
return random;
}
Any place can I find sample codes, these functions were changed by some copies on the internet。and I got many confuses list in the comment
The EC keys are to be exported/imported as a Base64 encoded raw private key and as a Base64 encoded raw uncompressed public key.
First of all it can be stated that signing and verifying with the posted code works when a fresh key pair is generated:
AsymmetricKeyPair<PublicKey, PrivateKey> kp = generateKeyPair();
ECSignature signature = sign(kp.privateKey as ECPrivateKey, "The quick brown fox jumps over the lazy dog");
bool verified = verify("The quick brown fox jumps over the lazy dog", signature, kp.publicKey as ECPublicKey);
print(verified); // true
I.e. in the following I will focus on the import/export of the keys. The raw keys are encapsulated in ECPrivateKey and ECPublicKey and can be exported and imported as follows:
String p256 = 'secp256r1';
AsymmetricKeyPair<PublicKey, PrivateKey> kp = generateKeyPair(curve: p256);
// Export
BigInt d = (kp.privateKey as ECPrivateKey).d!;
BigInt x = (kp.publicKey as ECPublicKey).Q!.x!.toBigInteger()!;
BigInt y = (kp.publicKey as ECPublicKey).Q!.y!.toBigInteger()!;
// Import
ECDomainParameters domain = ECDomainParameters(p256);
ECPrivateKey ecPrivateKey = ECPrivateKey(d, domain);
ECPublicKey ecPublicKey = ECPublicKey(domain.curve.createPoint(x, y), domain);
Here d is the raw private key and x and y are the x and y coordinates of the raw public key.
On the JavaScript side, the Base64 encoded raw private key is used and the Base64 encoded raw uncompressed key, where the uncompressed key is the concatenation 0x04 + <x> + <y>. So, for export and import, the following applies:
Regarding the export, the Base64 encoded raw private and public key can be derived from d, x, and y as follows:
String rawPrivateB64 = exportPrivate(d);
String rawUncompressedPublicB64 = exportPublic(x, y, 32);
with
import 'dart:convert';
import 'package:nanodart/nanodart.dart';
String exportPrivate(BigInt d){
return base64Encode(NanoHelpers.bigIntToBytes(d));
}
String exportPublic(BigInt x, BigInt y, int size){
return base64Encode(NanoHelpers.concat([Uint8List.fromList([4]), pad(NanoHelpers.bigIntToBytes(x), size), pad(NanoHelpers.bigIntToBytes(y), size)]));
}
Uint8List pad(Uint8List list, int size){
Uint8List padded = list;
int currSize = list.length;
if (currSize < size){
Uint8List pad = Uint8List(size - currSize);
padded = NanoHelpers.concat([pad, list]);
}
return padded;
}
The size passed in exportPublic() as 3rd parameter is the size of the order of the generator point (32 bytes for secp256r1). If x or y are smaller, they are each padded from the front with 0x00 values until the required length is reached.
For the conversion from BigInt to Uint8List and the concatenation I used the NanoHelpers class from the NanoDart package for simplicity. Of course, other implementations can be used here as well.
Regarding the import, d, x, and y can be derived from the Base64 encoded raw private and public key as follows:
BigInt d = importPrivate(rawPrivateB64);
List xy = importPublic(rawUncompressedPublicB64);
BigInt x = xy.elementAt(0);
BigInt y = xy.elementAt(1);
with
BigInt importPrivate(String d){
return NanoHelpers.byteToBigInt(base64Decode(d));
}
List importPublic(String xy){
Uint8List xyBytes = base64Decode(xy);
xyBytes = xyBytes.sublist(1, xyBytes.length);
int size = xyBytes.length ~/ 2;
Uint8List x = xyBytes.sublist(0, size);
Uint8List y = xyBytes.sublist(size);
return [NanoHelpers.byteToBigInt(x), NanoHelpers.byteToBigInt(y)];
}
Test
The posted key pair
{"priKey":"CVK3r/UxdGCwQBjtn5vN/orUMxKf9E/1TlJzLkMz9t4=","pubKey":"BJH/mWJqgchGxXGA5/E79SsWRwVo3rpduBmD8FOs7UlKiK8PIvwrkCDvUcwhKdysW35OByPjoVcwFqg1NyumLKM="}
can be imported and used for signing and verification as follows:
String rawPrivateB64 = "CVK3r/UxdGCwQBjtn5vN/orUMxKf9E/1TlJzLkMz9t4=";
String rawUncompressedPublicB64 = "BJH/mWJqgchGxXGA5/E79SsWRwVo3rpduBmD8FOs7UlKiK8PIvwrkCDvUcwhKdysW35OByPjoVcwFqg1NyumLKM=";
BigInt d = importPrivate(rawPrivateB64);
List xy = importPublic(rawUncompressedPublicB64);
BigInt x = xy.elementAt(0);
BigInt y = xy.elementAt(1);
ECDomainParameters domain = ECDomainParameters('secp256r1');
ECPrivateKey private = ECPrivateKey(d, domain);
ECPublicKey public = ECPublicKey(domain.curve.createPoint(x, y), domain);
ECSignature signature = sign(private, "The quick brown fox jumps over the lazy dog");
bool verified = verify("The quick brown fox jumps over the lazy dog", signature, public);
print(verified); // true
Edit:
Regarding your comment: sign() and verify() are the methods you posted, but according to the changes, the keys are now passed directly (instead of strings) and the actual message is applied (instead of [1,2,3]) using utf8.encode() for UTF-8 encoding:
import 'dart:convert';
ECSignature sign(ECPrivateKey privateKey, String txt) {
SecureRandom random = _setRandom();
Uint8List txtBytes = Uint8List.fromList(utf8.encode(txt));
PrivateKeyParameter signParams = PrivateKeyParameter(privateKey);
signer.init(true, ParametersWithRandom(signParams, random));
ECSignature signature = signer.generateSignature(txtBytes) as ECSignature;
return signature;
}
bool verify(String txt, ECSignature signature, ECPublicKey publicKey) {
signer.init(false, PublicKeyParameter(publicKey));
bool verify = signer.verifySignature(Uint8List.fromList(utf8.encode(txt)), signature);
return verify;
}
As _setRandom() I applied the implementation from generateKeyPair() instead of your implementation (i.e. a FortunaRandom() based CSPRNG).
my whole code based on accepted answer
crypto.dart
import "dart:typed_data";
import "dart:math";
import 'dart:convert';
import "package:pointycastle/export.dart";
import './utils.dart';
Signer signer = new Signer('SHA-256/ECDSA');
class Crypto {
final ECDomainParameters ecDomain = new ECDomainParameters('secp256r1');
/// 公私钥对生成
/// 关于公私钥encoding:https://stackoverflow.com/questions/72641616/how-to-convert-asymmetrickeypair-to-base64-encoding-string-in-dart
///
Map generateKeyPair({curve = 'secp256r1'}) {
var param = curve == 'secp256r1' ? ECCurve_secp256r1() : ECCurve_secp256k1();
var keyParams = ECKeyGeneratorParameters(param);
var random = FortunaRandom();
random.seed(KeyParameter(this._seed(32)));
var generator = ECKeyGenerator();
generator.init(ParametersWithRandom(keyParams, random));
AsymmetricKeyPair<PublicKey, PrivateKey> kp = generator.generateKeyPair();
BigInt d = (kp.privateKey as ECPrivateKey).d!;
BigInt x = (kp.publicKey as ECPublicKey).Q!.x!.toBigInteger()!;
BigInt y = (kp.publicKey as ECPublicKey).Q!.y!.toBigInteger()!;
String rawPrivateB64 = exportPrivate(d);
String rawUncompressedPublicB64 = exportPublic(x, y, 32);
return {'base64Pub': rawUncompressedPublicB64, 'base64Priv': rawPrivateB64};
}
Uint8List _seed(size) {
var random = Random.secure();
var seed = List<int>.generate(size, (_) => random.nextInt(256));
return Uint8List.fromList(seed);
}
// TODO
// Restore the ECPrivateKey from 'd'.
restoreKeyFromPrivate(privateKeyStr) {
ECPrivateKey privateKey = new ECPrivateKey(BigInt.parse(privateKeyStr, radix: 10), ecDomain);
ECPoint Q = privateKey.parameters!.G * privateKey.d as ECPoint;
ECPublicKey publicKey = new ECPublicKey(Q, privateKey.parameters);
return publicKey;
}
ECSignature sign(ECPrivateKey privateKey, String txt) {
SecureRandom random = _setRandom();
Uint8List txtBytes = Uint8List.fromList(utf8.encode(txt));
PrivateKeyParameter signParams = PrivateKeyParameter(privateKey);
signer.init(true, ParametersWithRandom(signParams, random));
ECSignature signature = signer.generateSignature(txtBytes) as ECSignature;
return signature;
}
bool verify(String txt, ECSignature signature, ECPublicKey publicKey) {
signer.init(false, PublicKeyParameter(publicKey));
bool verify = signer.verifySignature(Uint8List.fromList(utf8.encode(txt)), signature);
return verify;
}
SecureRandom _setRandom() {
// List<int> key = [67, 3, 241, 75, 143, 78, 115, 99, 21, 242, 180, 43, 26, 7, 194, 20];
// List<int> iv = [87, 117, 137, 182, 2, 199, 132, 230, 120, 12, 109, 177, 34, 197, 186, 206];
List<int> key = _seed(16);
List<int> iv = _seed(16);
KeyParameter keyParam = new KeyParameter(new Uint8List.fromList(key));
ParametersWithIV<KeyParameter> paramsIV = new ParametersWithIV(keyParam, new Uint8List.fromList(iv));
SecureRandom random = new SecureRandom('AES/CTR/AUTO-SEED-PRNG')..seed(paramsIV);
return random;
}
}
crypto_test.dart
import '../lib/crypto/crypto.dart';
import "dart:typed_data";
import "dart:math";
import '../lib/crypto/utils.dart';
import "package:pointycastle/export.dart";
var crypto = new Crypto();
void main() {
// _generateTest();
// _signTest();
Map keyPair = crypto.generateKeyPair();
String rawPrivateB64 = keyPair['base64Priv'];
String rawUncompressedPublicB64 = keyPair['base64Pub'];
BigInt d = importPrivate(rawPrivateB64);
List xy = importPublic(rawUncompressedPublicB64);
BigInt x = xy.elementAt(0);
BigInt y = xy.elementAt(1);
ECDomainParameters domain = ECDomainParameters('secp256r1');
ECPrivateKey private = ECPrivateKey(d, domain);
ECPublicKey public = ECPublicKey(domain.curve.createPoint(x, y), domain);
ECSignature signature = crypto.sign(private, "The quick brown fox jumps over the lazy dog");
bool verified = crypto.verify("The quick brown fox jumps over the lazy dog", signature, public);
print('验签结果');
print(verified); // true
}
_generateTest() {
Map keyPair = crypto.generateKeyPair();
print("结果");
print(keyPair['base64Pub']);
print(keyPair['base64Priv']);
}
_signTest() {
// AsymmetricKeyPair<PublicKey, PrivateKey> kp = crypto.generateKeyPair();
// ECSignature signature = sign(kp.privateKey as ECPrivateKey, "The quick brown fox jumps over the lazy dog");
// bool verified = crypto.verify("The quick brown fox jumps over the lazy dog", signature, kp.publicKey as ECPublicKey);
// print(verified); // true
}
Related
I have a 24-word mnemonic, and I want to convert it to public and private keys.
This is how I did it:
const hex = HexCoder.instance;
final seed = bip39.mnemonicToSeedHex(_mnmonic);
final algorithm = Ed25519();
// The hex.decode(seed) have 64 bytes lengths.
final keyPair = await algorithm.newKeyPairFromSeed(hex.decode(seed));
final newPublicKey = await keyPair.extractPublicKey();
But I get this error:
ArgumentError (Invalid argument(s): Seed must have 32 bytes)
What am I missing?
Update
Use sha256:
import 'package:crypto/crypto.dart' show sha256;
final seed = bip39.mnemonicToSeed(mnemonic);
final digest = sha256.convert(seed); // 32 bytes
Old answer
Here are some examples how people generate keys from mnemonics:
final seed = bip39.mnemonicToSeed(mnemonic);
final root = bip32.BIP32.fromSeed(seed);
getAddress(root.derivePath("m/0'/0/0"));
Here is another example:
Uint8List seed = await compute(bip39.mnemonicToSeed, mnemonic);
bip32.BIP32 masterNode = bip32.BIP32.fromSeed(seed);
String hdPath = "m/44'/12586'/$accountIndex'/0/0";
bip32.BIP32 child0 = masterNode.derivePath(hdPath);
Uint8List rawPrivateKey = child0.privateKey!;
rawPrivateKey[0] &= 0x3f;
final privateKeyHex = HEX.encode(rawPrivateKey);
I have this code
String encrypt(String x) {
String out;
var _x = x.codeUnits;
List dict;
/* <dict_assignment> */
dict[0] = 'a';
dict[1] = 'b';
dict[2] = 'c';
dict[3] = 'd';
dict[4] = 'e';
dict[5] = 'f';
dict[6] = 'g';
dict[7] = 'h';
dict[8] = 'i';
dict[9] = 'j';
/* </dict_assignment> */
_x.toList().forEach((i) {
var _i = i.toString();
_i.split("").forEach((k) {
var _k = int.parse(k);
print(_k);
print(dict[_k]);
out += dict[_k];
});
});
return out;
}
(Yes I'm writing HTML tags as comments in Dart...sue me)
(Idk why my indentations are messed up)
For some reason when I use this same function with a random string like this
var x = encrypt("hmm interesting");
I keep getting this
Unhandled exception:
NoSuchMethodError: The method '[]=' was called on null.
Receiver: null
Tried calling: []=(0, "a")
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
Please help me I'm actually confused why this is happening
You have not initialized your dict variable, so it contains null.
If you change List dict; to List dict = []; then that would start working.
You also haven't initialized out.
The remainder of the code is leaning towards being overly complicated, and can be optimized as well. Here is a suggestion:
String encrypt(String x) {
var out = StringBuffer();
const dict = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
for (var i in x.codeUnits) { // x.codeUnits is a list. Use for-in to iterate it.
for (var k in i.toString().codeUnits) {
var _k = k ^ 0x30; // Best way to convert code unit for 0-9 into integer 0-9.
// print(_k);
// print(dict[_k]);
out.write(dict[_k]); // Use a StringBuffer instead of repeated concatenation.
}
}
return out.toString();
}
It does not appear to be a decryptable encryption. The string "77" and the string "ᖳ" (aka "\u15b3") both encrypt to "ffff".
Or, if you want to "code-golf" rather than be readable or close to the original, it can also be a one-liner:
String encrypt(String x) => [
for (var i in x.codeUnits)
for (var k in "$i".codeUnits) "abcdefghij"[k ^ 0x30]
].join("");
I have csv file containing some data like:
374,Test Comment multiplelines \n Here's the 2nd line,Other_Data
Where 374 is the object ID from doors, then some commentary and then some other data.
I have a piece of code that reads the data from the CSV file, stores it in the appropriate variables and then writes it to the doors Object.
Module Openend_module = edit("path_to_mod", true,true,true)
Object o ;
Column c;
string attrib;
string oneLine ;
string OBJECT_ID = "";
string Comment = "";
String Other_data = "";
int offset;
string split_text(string s)
{
if (findPlainText(s, sub, offset, len, false))
{
return s[0 : offset -1]
}
else
{
return ""
}
}
Stream input = read("Path_to_Input.txt");
input >> oneLine
OBJECT_ID = split_text(oneLine)
oneLine = oneLine[offset+1:]
Comment = split_text(oneLine)
Other_data = oneLine[offset+1:]
When using print Comment the output in the DXL console is : Test Comment multiplelines \n Here's the 2nd line
for o in Opened_Module do
{
if (o."Absolute Number"""==OBJECT_ID ){
attrib = "Result_Comment " 2
o.attrib = Comment
}
}
But after writing to the doors object, the \n is not taken into consideration and the result is as follows:
I've tried putting the string inside a Buffer and using stringOf() but the escape character just disappeared.
I've also tried adding \r\n and \\n to the input csv text but still no luck
This isn't the most efficient way of handling this, but I have a relatively straightforward fix.
I would suggest adding the following:
Module Openend_module = edit("path_to_mod", true,true,true)
Object o ;
Column c;
string attrib;
string oneLine ;
string OBJECT_ID = "";
string Comment = "";
String Other_data = "";
int offset;
string split_text(string s)
{
if (findPlainText(s, sub, offset, len, false))
{
return s[0 : offset -1]
}
else
{
return ""
}
}
Stream input = read("Path_to_Input.txt");
input >> oneLine
OBJECT_ID = split_text(oneLine)
oneLine = oneLine[offset+1:]
Comment = split_text(oneLine)
Other_data = oneLine[offset+1:]
//Modification to comment string
int x
int y
while ( findPlainText ( Comment , "\\n" , x , y , false ) ) {
Comment = ( Comment [ 0 : x - 1 ] ) "\n" ( Comment [ x + 2 : ] )
}
This will run the comment string through a parser, replacing string "\n" with the char '\n'. Be aware- this will ignore any trailing spaces at the end of a line.
Let me know if that helps.
I am trying to build an Nancy OData support app using LinqToQuerystring. I got below sample code. it is working for any query url like:
http:/test/?$filter=Recommended eq true
Get["/test"] = _ =>
{
var dict = (IDictionary)Request.Query.ToDictionary();
new List<Movie>
{
new Movie
{
Title = "Matrix (The)",
ReleaseDate = new DateTime(1999, 3, 31),
DurationInMinutes = 136,
MetaScore = 73,
Director = "Wachowski Brothers",
Recommended = true
},
new Movie
{
Title = "There and Back Again, An Unexpected Journey",
ReleaseDate = new DateTime(2012, 12, 14),
DurationInMinutes = 169,
MetaScore = 58,
Director = "Peter Jackson",
Recommended = false
}
}.AsQueryable()
.LinqToQuerystring(dict);
return dict;
}
You can solve this by calling ToDictionary first.
i.e
var dict = (IDictionary<string, object>) Request.Query.ToDictionary();
...
.LinqToQuerystring(dict);
This is probably because of the way LinqToQuerystring handles Dictionary under the hood, outputting them in an intermediate window causes:
(IDictionary<string, object>) Request.Query
{Nancy.DynamicDictionary}
[Nancy.DynamicDictionary]: {Nancy.DynamicDictionary}
Keys: Count = 2
Values: Count = 2
(IDictionary<string, object>) Request.Query.ToDictionary()
Count = 2
[0]: {[one, one]}
[1]: {[two, 2]}
Edit:
Based on your comment I assume you want to ALWAYS return JSON.
If that's the case the way you would do that is to return:
return Response.AsJson(dict);
This will serialize the dictionary as JSON for you.
I've been playing with python's crypto library, and I built a simple threading server to encrypt and decrypt. The problem I'm having is that about 1 out of 3 decryptions comes back incorrectly. Here's the code:
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
global KEY
request_text = ''
while request_text.rfind("\n") == -1:
sock_data='';
recv_size=8192
sock_data=self.request.recv(recv_size)
if sock_data == '':
print "hangup"
break
request_text = request_text + sock_data
args = json.loads(request_text)
print request_text
print "\n"
if args['command'] == 'encrypt':
iv = Random.new().read(AES.block_size)
cipher = AES.new(KEY, AES.MODE_CFB, iv)
crypted_message = iv + b'|' + cipher.encrypt(unquote_plus(args['message']))
response = {'encrypted_message': binascii.hexlify(crypted_message)}
if args['command'] == 'decrypt':
unhexed = binascii.unhexlify(args['message'])
components = unhexed.split('|')
iv = components[0]
cipher = AES.new(KEY, AES.MODE_CFB, iv)
decrypted_message = cipher.decrypt(components[1])
response = {'decrypted_message': decrypted_message}
self.request.sendall(json.dumps(response) + "\n")
Often, I get this error from python:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/SocketServer.py", line 582, in process_request_thread
self.finish_request(request, client_address)
File "/usr/local/lib/python2.7/SocketServer.py", line 323, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/local/lib/python2.7/SocketServer.py", line 639, in __init__
self.handle()
File "cryptoserver.py", line 40, in handle
cipher = AES.new(KEY, AES.MODE_CFB, iv)
File "build/bdist.macosx-10.4-x86_64/egg/Crypto/Cipher/AES.py", line 95, in new
return AESCipher(key, *args, **kwargs)
File "build/bdist.macosx-10.4-x86_64/egg/Crypto/Cipher/AES.py", line 59, in __init__
blockalgo.BlockAlgo.__init__(self, _AES, key, *args, **kwargs)
File "build/bdist.macosx-10.4-x86_64/egg/Crypto/Cipher/blockalgo.py", line 141, in __init__
self._cipher = factory.new(key, *args, **kwargs)
ValueError: IV must be 16 bytes long
----------------------------------------
but just as often, I get no error, but the decryption doesn't work correctly. I'm using this php to test it:
<?php
include_once("config.php");
function encrypt($text) {
$package = array("command" => "encrypt",
"message" => base64_encode($text));
$package_json = json_encode($package);
$serverSays = transmit($package_json);
$serverSaysArray = json_decode($serverSays);
return $serverSaysArray->encrypted_message;
}
function decrypt($text) {
$package = array("command" => "decrypt",
"message" => $text);
$package_json = json_encode($package);
$serverSays = transmit($package_json);
$serverSaysArray = json_decode($serverSays);
return base64_decode($serverSaysArray->decrypted_message);
}
function transmit($package) {
global $CRYPTO_PORT;
global $CRYPTO_HOST;
$serverLink = fsockopen($CRYPTO_HOST, $CRYPTO_PORT);
if ($serverLink === FALSE) {
error_log("Could not connect to encryption server");
return FALSE;
}
fwrite($serverLink, $package . "\n");
$response = '';
while (!feof($serverLink)) {
$response .= fgets($serverLink, 128);
}
fclose($serverLink);
return $response;
}
while (TRUE) {
$enc = encrypt('totsadaddywoopxxx');
print "$enc\n";
$dec = decrypt($enc);
print "$dec\n";
$enc = encrypt('totsadaddywoopxxx');
print "$enc\n";
$dec = decrypt($enc);
print "$dec\n";
$enc = encrypt('totsadaddywoopxxx');
print "$enc\n";
$dec = decrypt($enc);
print "$dec\n";
#print decrypt('1c6dee677126551fa4b3f0732986dc3b7c985c64c07075e3651213d7a69435bcd87083e729e8de860c');
#print "\n";
#print decrypt('550cbec7498371dc01bcd6b88fc623b47cb2efd1881da6e07ee992229308305992bbc7ccc374f00c91d56d10a68d6110e2');
print "===========================\n";
sleep(1);
}
In your decryption routine you use:
unhexed.split('|')
to find the boundary between IV and the ciphertext. However, the IV is generated randomly by the sender. Sometimes, one of its 16 bytes will be 124, that is the boundary character '|'.
When that happens (in roughly 6% of the cases), the decryption routine will initialize the cipher either with
an IV with length between 1 and 15 bytes, which leads to the exception, or
an IV with length 0, which leads to the incorrect decryption, because in PyCrypto versions<2.6 an all-zero 16 byte IV will be used by default
In the decryption routine you should have instead:
components = [ unhexed[:AES.block_size], unhexed[AES.block_size+1:] ]
Or you could get rid of the '|' separator altogether.