openssl_public_decrypt return nothing - encryption

I tried to decrypt with openssl_public_decrypt and failed.Openssl_public_decrypt does return nothing.I don't know where the problem is.Below is my code.
I have tried not to use base64_encode, also not work.I need to read the rsa key value from the database.
<?php
$data = 'data to be encrypt';
echo $data;
$privateKey = '-----BEGIN PRIVATE KEY-----
MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQDJDA1AKIHIoj+a
roYVXoBogXfmIbArgiuvjJ2p87XN1pPs4YUC1dyZcdG+ULBtPaApLOsw0tNnNAjT
N3MWTIi9QD+NfD/BT6t44iWuqx9ryWy35H7yF1b92jEAMzCQ4uXaStZN3nzSoCvk
RB3iB4W4VSI/bBgaM2Q9B3mE11VJDzdcuQ6nMivIASRF5f/w05324i7ElCH521E6
2iKK63USOnNG29XH4fSL5+jC3bju/bafakb7oB148TZhf4ueCxVvK7j/enHFPKZi
Cm4qA42JgZNvXDkOixBtzDUmR+ULBr7Vt0b5Isa0Zt6845LXyRmOSwQ5W5f3H77+
JYMNSIWRO0Ola8HEkJuwCohmjcN2txVNJQjjNMZZCJ7+uj13N9rIUDsloO1KMm59
Q3yeh4qkvC0Te2C0WNGrAp952Sq5Hva7HB5K0l1wQ7l2U4oAds4V3eT60iDLcrWe
AvWEFQWjncU7ITwgZ+kFysP22TSFjl3WJZiPmcOrX/OJdKQpwxavganu3Bmpf4Tg
e5L4LWswnkTzKd9J9tN/YGyoJEe9/dkwovjJsPKBKFoqfCHsI8HqULVzkhO5whTF
921ly9qSbmBw2al8tbms46za2MHTPDqE7GtQ10CTO4G08kCs/V8Yb22us3GqxL7q
G6j6wWtrQsqYPwnZicgh8hsFeMNCiQIDAQABAoICACRsM4ZZEFIp2r4KOi5q5XaJ
ZhBiMAlh1spB/lpI1boJ0tjKbo958TI3ZZlGAwB3dqmfAqjguP3sdmDVndr/WJJ4
rkrSpLY/2b/XsJ35UIL1heW21qzDP7ZTribsHzNQd/XZMwP+d7ys2ebL1GIbnMUt
XzwAOEme390Smph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6W/FpTpz41Ywc
/pMjAStbV7/lTR9QYRtZHPsqyQgzjUDzLGFQffpDLGXNHBfIVoNKLuCOyfekcIo+
oBdPnE4O8GrJkQLQhBiT5KxBGFD0H7aBlMH8dwMaaLhhBoelONH5wyhElKVg4tL2
INRxom+wANYnRDgMh9QWURpJGVbpEA==
-----END PRIVATE KEY-----';
openssl_private_encrypt($data, $encrypted, $privateKey);
echo '-------------';
echo $encrypted;
echo '-------------';
$encrypted = base64_encode($encrypted);
echo $encrypted;
echo '-------------';
$publicKey = '-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAsZka5Mul/211/0h84Ig8
i8lJVy21tvFN8uTRKgldY3TMfcdiQjLXNXXWVBdcobXa9wzNx3YXvyqr3Tnmr0iN
loVovJ9JER5EUQPEPthMNn9de9fEgNsfABT0Eq2291t8sFMx1/mAHd6z8KE+mzYC
yVeZqLEmwsiKCMjx1Pj2NfGR9+bNfC5P0SG2ARdpFZFJL6XK7L6t+nW9HXcDwPP1
ocA38iSjovjyel/LP00zETL3z0wlIPzxMCodxUU/bPdlDGQbc1MzaYHvOP+RXVFZ
j5fEp9OFpbm6BJXi/RT3/PYWS7+RCUHsb+LSa1JLylsEzyNaKqYX+wY0/2hEcWB3
WcYP6QRF/EKSLQbB7EvMucUM79deTkmFrly4ePkrk5tPoiQzRXFkoSGM4nKxAh0T
6Sjg8/WchBpVJQRvU+9vb9yk2Tey045/Wo3G1Fvehs/OXcd5P7OPLLpmLMNve7oZ
DVaw8lHBIxjMtAz+pZKvxDDtJR9jZuaiBqyGjj7rHnvagrxhZmdQiIDuuCOdaqTk
ARGrtgsLmIPbsO6HukkyG6W+8RjtVb+M2yC7HjFcwWcwBLe5mj0gikFe6wk0GtTJ
i1KdWoxjgibvWR9PRLKKlqT+CC0xgitln8PbH0xWNj7NlmMPdBuaN7Dpu8MU9ejS
6N3vOIsj40M0pgv6fdufnK8CAwEAAQ==
-----END PUBLIC KEY-----';
$decryptData = base64_decode($encrypted);
echo $decryptData;
echo '-------------';
openssl_public_decrypt($decryptData, $decrypted, $publicKey);
echo $decrypted;
I want to know what went wrong.I need your help.

Related

zshell use variable variables to get value in hask tables

Make the following function output the same as echo ${clash[http]}
#!/usr/bin/zsh
typeset -A clash=( ["http"]=7890 ["socks"]=7891 )
function getValue() {
echo ${(P)1}
}
getValue clash http
function getValue() {
typeset -A hashTab=(${(kvP)1})
echo $hashTab[$2]
}

How to migrate Mcrypt to openssl function to encrypt with PHP7.3

Unfortunately 7.3 doesn't support mcrypt and I have to refactor some code.
I cannot migrate this encription function:
mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, pkcs5_pad(trim($strToEncode), mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB)), MCRYPT_MODE_ECB, $iv);
I tried this code:
function pkcs5_pad ($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}
$cipher = "aes-128-gcm";
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));
$block_size = strlen(openssl_encrypt('', $cipher, '', OPENSSL_RAW_DATA, $iv));
$ciphertext = openssl_encrypt(pkcs5_pad(trim($strToEncode),$block_size), $cipher, $key, $options=0, $iv);
But it doesn't work and I got: Uncaught DivisionByZeroError in pkcs5_pad function
This is the working code:
$cipher = "aes-128-ecb";
$ciphertext = openssl_encrypt(trim($strToEncode), $cipher, $key, OPENSSL_RAW_DATA);

Convert single line RSA private ssh key to multi line

I have these private keys that have been converted to single line equivalent.
These keys are quite a lot.
So I decided to invest some time to write a script to convert.
This has not yielded to much.
-----BEGIN RSA PRIVATE KEY----pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4= -----END RSA PRIVATE KEY-----
I am using echo ~/.ssh/id_rsa | tr " " "\n"
This returns:
-----BEGIN
RSA
PRIVATE
KEY-----
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=pEdInVAbH4d0PH4=
-----END
RSA
PRIVATE
KEY-----
I have been trying to figure out the best possible way to get this back to the right format.
Assuming a standard RSA private key that just had the newlines removed, a couple of sed replacements will get you back to the original format:
sed -e "s/-----BEGIN RSA PRIVATE KEY-----/&\n/"\
-e "s/-----END RSA PRIVATE KEY-----/\n&/"\
-e "s/\S\{64\}/&\n/g"\
~/.ssh/id_rsa
The standard key format requires the BEGIN and END statements to be on a separate line, and the base64-encoded key to be formatted at 64 columns. The above command will get you there.
#robby Thanks from your answer I adapted the following which worked for me.
sed -e "s/-----BEGIN RSA PRIVATE KEY-----/&\n/" -e "s/\S\{64\}/&\n/g" | sed "s/^\s//g" ~/.ssh/id_rsa
I adapted the solution to ed25519 algorithm to talk to Gitlab via SSH. Thanks #Robby!
RUN sed -i -e "s/-----BEGIN OPENSSH PRIVATE KEY-----/&\n/"\
-e "s/-----END OPENSSH PRIVATE KEY-----/\n&/"\
-e "s/\S\{70\}/&\n/g"\
/root/.ssh/id_ed25519
Input
-----BEGIN OPENSSH PRIVATE KEY----- XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX== -----END OPENSSH PRIVATE
KEY-----
Output
-----BEGIN OPENSSH PRIVATE KEY-----
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX==
-----END OPENSSH PRIVATE KEY-----

Decrypt 3DES DUKPT per the ANSI X9.24 part 1 standard

I have a Magtek uDynamo and am trying to decrypt track 1. I have read the below and understand a little bit but don't know how to actually decrypt the data. The vendor said to use the ANSI test key to decrypt but I can't find anything on that. I have the KSN, session, and serial numbers. I have also tried some Java code I found, but it doesn't seem to work. It returns null or possibly I'm putting in the wrong BDK. I'm just using the serial number for that which I read somewhere. I'm doing this on Android. Preferably I would like code that runs on the server not on the device so it goes encrypted across the line along with HTTPS.
How ciphertext was generated in card reader using DUKPT encryption?
3DES-DUKPT (CBC) decryption confirmation
https://github.com/yinheli/dukpt/blob/master/src/main/java/com/yinheli/tool/DukptDecrypt.java
Update
I'm looking to decrypt 3DES DUKPT per the ANSI X9.24 part 1 standard
I'm using this https://github.com/camcima/dukpt-php/tree/e8fceb4df8757e7e097c435221b4e93e097d3c9f
I had to update the files and make sure I got the most recent phpseclib and it runs but the data comes out like C��� ������4A�fr���( Wb������f�7z�n:�w�9��,��f7�,m=�z�CRW�
I must be missing something. I've tried different modes and I'm trying to look for encoding. Please let me know if you have a solution or ideas. Also their test data does work so I'm not sure what the difference is between mine and theirs
Code I'm running index.php in the root:
include 'vendor/autoload.php';
use DUKPT\DerivedKey;
use DUKPT\KeySerialNumber;
use DUKPT\Utility;
$encryptedHexData = 'de8bfe769dca885cf3cc312135fe2cccfacf176235f4bdee773d1865334315ed2aefcab613f1884b5d63051703d5a0e2bd5d1988eeabe641bd5d1988eeabe641';
$ksn = '00000232100117e00027';
$bdk = '0123456789ABCDEFFEDCBA9876543210';
$key = new KeySerialNumber($ksn);
$encryptionKey = DerivedKey::calculateDataEncryptionRequestKey($key, $bdk);
$actual = Utility::hex2bin(Utility::removePadding(Utility::tripleDesDecrypt($encryptedHexData, $encryptionKey, true)));
echo $encryptionKey.'<br />';
echo $actual.'<br /><br />';
With a proper BDK and KSN all you need to do now is try the different modes.
Right now you are using DerivedKey::calculateDataEncryptionRequestKey($key, $bdk);
You need to try the other modes to figure out which one your device is using. Here is the code I used to find the correct result for my device.
include 'vendor/autoload.php';
use DUKPT\DerivedKey;
use DUKPT\KeySerialNumber;
use DUKPT\Utility;
$encryptedHexData = 'C25C1D1197D31CAA87285D59A892047426D9182EC11353C051ADD6D0F072A6CB3436560B3071FC1FD11D9F7E74886742D9BEE0CFD1EA1064C213BB55278B2F12';
$ksn = 'FFFF9876543210E00008';
$bdk = '0123456789ABCDEFFEDCBA9876543210';
$key = new KeySerialNumber($ksn);
$encryptionKey = DerivedKey::calculatePinEncryptionKey($key, $bdk);
$decryptedOutput = Utility::hex2bin(Utility::tripleDesDecrypt($encryptedHexData, $encryptionKey, true));
echo '<br /><br />Pin Encryption Key: '.$encryptionKey;
echo '<br />Decrypted Output: '.$decryptedOutput;
$encryptionKey = DerivedKey::calculateMacRequestKey($key, $bdk);
$decryptedOutput = Utility::hex2bin(Utility::tripleDesDecrypt($encryptedHexData, $encryptionKey, true));
echo '<br /><br />Mac Request Key: '.$encryptionKey;
echo '<br />Decrypted Output: '.$decryptedOutput;
$encryptionKey = DerivedKey::calculateMacResponseKey($key, $bdk);
$decryptedOutput = Utility::hex2bin(Utility::tripleDesDecrypt($encryptedHexData, $encryptionKey, true));
echo '<br /><br />Mac Response Key: '.$encryptionKey;
echo '<br />Decrypted Output: '.$decryptedOutput;
$encryptionKey = DerivedKey::calculateDataEncryptionRequestKey($key, $bdk);
$decryptedOutput = Utility::hex2bin(Utility::tripleDesDecrypt($encryptedHexData, $encryptionKey, true));
echo '<br /><br />Data Encryption Request Key: '.$encryptionKey;
echo '<br />Decrypted Output: '.$decryptedOutput;
$encryptionKey = DerivedKey::calculateDataEncryptionResponseKey($key, $bdk);
$decryptedOutput = Utility::hex2bin(Utility::tripleDesDecrypt($encryptedHexData, $encryptionKey, true));
echo '<br /><br />Data Encryption Response Key: '.$encryptionKey;
echo '<br />Decrypted Output: '.$decryptedOutput;
So for this BDK and KSN the below is the resulting output.
Pin Encryption Key: 27F66D5244FF621EAA6F6120EDEB427F
Decrypted Output: %B5452300551227189^HOGAN/PAUL ^08043210000000725000000?
Mac Request Key: 27F66D5244FF9DE1AA6F6120EDEBBD80
Decrypted Output: W����U�P�TfB/`����þ&��f��3y;�U�Zy��UK�[��s�;�>�[�b
Mac Response Key: 27F66D52BBFF62E1AA6F612012EB4280
Decrypted Output: b�K2a�S0��9�Mb-����*L�J���� ��s�\���H�����=���e�]�,���Hwq�
Data Encryption Request Key: C39B2778B058AC376FB18DC906F75CBA
Decrypted Output: RA]�ԅⱰQ���'v}b��h��St�����?� lu/�ٵ�P��!���6�� �
Data Encryption Response Key: 846E267CB822197406DA2B161191C6E4
Decrypted Output: ��,�B^FZ�� ςs�c���*E�4��0��ǂ}����6`-P�b�ʞ̳aصĬ�&���+��

sending arduino data to my database using EtherCard.h library

I am having a problem in sending Arduino data into my database. I am currently using WAMPSERVER. I have an arduino mini w/ ATMEGA 328 and I am using ENC28J60. The problem is I have tried different libraries and examples to send data into the server but I failed. I just notice that some libraries are not compatible with my enc28J60. I have tried UIPEthernet.h, Ethernet.h, etherShield.h and EtherCard.h. The etherShield.h and EtherCard.h seemed to work just fine. But I prefer to use EtherCard.h because I heard etherShield is the older lib. I know a little php.
I think the things that might guide me is to see a working example of using the EtherCard.h library demonstrating the sending of sensor data from arduino into my database. The network setup I am currently working on is that, the ENC28J60 is connected in my home network with an ip address of 192.168.10.10. The server to which I placed the database is my laptop with an IP address of 192.168.10.2. I am placing the php files in this directory C:\wamp\www. I hope I have explained it well. I'm sorry for my English.
I am currently working of a port of my homewatch server from Arduino Uno w Ethernet lib to AVR-NETIO with Ethercard lib (or UIPEthernet).
On the server side there is a Apache/PHP/MySQL server.
To update data on a webserver connected database, you can use POST or GET requests to a php web page. These data can then be added easily to a database and the same or another web page can also display the data of the database.
<?php
require 'dbhelp.php';
//header('Content-type: text/plain');
echo "<html>";
echo "<head>";
echo "<meta name='viewport' content='width=device-width, user-scalable=false, initial-scale=1;'>";
echo "</head>";
echo "<body>" . "<h2>Temperatur und Luftfeuchte</h2>";
// GET requests are sent as a query string on the URL:
// GET index.html?name1=value&name2=value HTTP/1.1
// Host: about.com
// http://192.168.0.40/homewatch/index.php?channel=1&temp=165&humidity=80&datetime=010120131234
if($DEBUG){
print("<pre>");
print_r($_GET);
print("</pre>");
}
openDB();
if( isset($_GET['channel']) && isset($_GET['temp']) && isset($_GET['humidity']) )
{
if($DEBUG)
echo "<p>addData()";
$c=$_GET['channel'];
$t=$_GET['temp'];
$h=$_GET['humidity'];
addData($c, $t, $h);
if($DEBUG)
echo "<p>all done";
//listData();
echo "<p>OK updated data for channel:" . $c . "</p>";
}
else
{
if($DEBUG)
echo "listData()";
//listData();
//echo "<p>missing arg";
}
echo "<p><a href='linechart_hour.php'>Stunden-Übersicht</a></p>";
echo "<p><a href='barchart_days.php'>Tages-Übersicht</a></p>";
echo "<p><a href='http://www.unwetterzentrale.de/uwz/getwarning_de.php?plz=41363&uwz=UWZ-DE&lang=de'>Unwetterwarnungen Jüchen</a></p>";
echo showAllCharts();
//#################################################################################
// see http://code.google.com/p/googlechartphplib/wiki/GettingStarted
//#################################################################################
// don't forget to update the path here
require './lib/GoogleChart.php';
$chart = new GoogleChart('lc', 500, 200);
// manually forcing the scale to [0,100]
$chart->setScale(0,100);
// add one line
$data = new GoogleChartData(array(49,74,78,71,40,39,35,20,50,61,45));
$chart->addData($data);
// customize y axis
$y_axis = new GoogleChartAxis('y');
$y_axis->setDrawTickMarks(false)->setLabels(array(0,50,100));
$chart->addAxis($y_axis);
// customize x axis
$x_axis = new GoogleChartAxis('x');
$x_axis->setTickMarks(5);
$chart->addAxis($x_axis);
echo $chart->toHtml();
//#################################################################################
// END
//#################################################################################
echo "<p>v0.9" . "</body>" . "</html>";
?>
the dbhelp.php file creates the DB automatically if not already exists:
<?php
//global dbhelp.php file
$server="localhost";
$user="root";
$passwd="password";
$names=array(
1 => "Aussen",
2 => "Schlaf",
3 => "Andreas");
$DEBUG=false;
function openDB(){
global $DEBUG;
global $user;
global $passwd;
$link = mysql_connect("localhost", $user, $passwd);
if(!$link){
echo "SqlConnect failed";
echo mysql_error();
}
else
if($DEBUG)
echo "SqlConnect OK";
$query="CREATE database IF NOT EXISTS avrdb;";
$result = mysql_query($query, $link);
if(!$result){
echo "CreateDB failed";
echo mysql_error();
}
else
if($DEBUG)
echo "CreateDB OK";
$result = mysql_select_db("avrdb", $link);
if(!$result){
echo "SelectDB failed";
echo mysql_error();
}
else
if($DEBUG)
echo "SelectDB OK";
$query="CREATE TABLE IF NOT EXISTS `avrtemp` (" .
"`id` int(11) NOT NULL AUTO_INCREMENT, " .
"`channel` int(11), " .
"`temp` int(11), " .
"`humidity` int(11), " .
"`date_time` TIMESTAMP, " .
"PRIMARY KEY (`id`) );";
$result = mysql_query($query, $link);
if(!$result){
echo "CreateTable failed";
echo mysql_error();
}
else
if($DEBUG)
echo "CreateTable OK";
return true;
}
...
function addData($c,$t,$h){
global $DEBUG;
$lastStoredDateTime=getLastStoredDateTime();
if($DEBUG){
echo "<p>" . $c . "</p>\n";
echo "<p>LastDateTime=".$lastStoredDateTime."</p>\n";
}
// add data but do not save seconds (use 00)
$query="INSERT INTO avrtemp (`channel`,`temp`,`humidity`,`date_time`)".
" VALUES ( $c,$t,$h,".
// " DATE_FORMAT(NOW()),".
" DATE_FORMAT('".$lastStoredDateTime."', ".
" '%Y-%c-%d %H:%i') )";
if($DEBUG)
echo "<p>" . $query;
$result = mysql_query($query);
if(!$result){
echo "addData failed";
echo mysql_error();
}
else
if($DEBUG)
echo "addData OK";
}
The Arduino posts (using GET) updated data every 5 minutes. The data arrives at the Arduino via 433MHz wireless sensors every minute or so.
Using the Ethernet Lib the data update is done via
char cBuf[maxBuf+1];
const char getHttpString[] =
"GET /homewatch/index.php?channel=%i&temp=%i&humidity=%i&time=%i\0";
...
// and send data: /index.php?channel=1&temp=165&humidity=80&datetime=010120131234
if (client.connect(server, 80)) {
Serial.println("connected. Send GET...");
snprintf(cBuf, maxBuf,
getHttpString,
sensorData[idxChannel].channel,
sensorData[idxChannel].temp,
sensorData[idxChannel].humidity,
sensorData[idxChannel].time_long
);
Serial.println(F("####"));
Serial.println(cBuf);
Serial.println(F("####"));
client.println(cBuf);
...
https://github.com/hjgode/homewatch/blob/master/arduino/SketchBook/WebClientTemperature/WebClientTemperature.ino:
The string "GET /homewatch/index.php?channel=%i&temp=%i&humidity=%i&time=%i\0" is simply filled with actual sensor data and the server saves that to its database.
The Ethercard lib comes with similar examples: see the examples noipClient, pachube and webclient. Unfortunately I was not yet able to adopt these for my AVR-NETIO.
The code to post (GET) some data to the server I am currently working is
void sendData(int idxChannel){
Serial.print(F("in sendData for idx=")); Serial.println(idxChannel);
byte sd;
int channel=sensorData[idxChannel].channel;
int temp=sensorData[idxChannel].temp;
int humidity=sensorData[idxChannel].humidity;
char* stime="201301011122";
stime=printDateTime((char*)&stime, 13, sensorData[idxChannel].time_long);
if(sensorData[idxChannel].bUpdated==0){
//nothing new
if (MYDEBUG==0){
Serial.println(F("leaving for not updated channel data"));
goto exit_sendData;
}
else
{
sensorData[idxChannel].channel=idxChannel;
sensorData[idxChannel].temp=222;
sensorData[idxChannel].humidity=55;
sensorData[idxChannel].time_long=now();
}
}
// generate two fake values as payload - by using a separate stash,
// we can determine the size of the generated message ahead of time
sd = stash.create();
stash.print("0,");
stash.println((word) millis() / 123);
stash.print("1,");
stash.println((word) micros() / 456);
stash.save();
// generate the header with payload - note that the stash size is used,
// and that a "stash descriptor" is passed in as argument using "$H"
Stash::prepare(PSTR("GET http://$F/homewatch/index.php?channel=$D&temp=$D&humidity=$D&time=$S" "\r\n"
"Host: $F" "\r\n"
"Content-Length: $D" "\r\n"
"\r\n"
"$H"),
website,
channel,
temp,
humidity,
stime,
website, stash.size(), sd);
// send the packet - this also releases all stash buffers once done
ether.tcpSend();
exit_sendData:
lastConnectionTime = now();//millis();
Serial.println(F("...end of sendData()"));
}
As you see, there is a formatted string
PSTR("GET http://$F/homewatch/index.php?channel=$D&temp=$D&humidity=$D&time=$S"
which is filled with variables. $F fills from Flash Memory, $D a number var, $S from a RAM memory string. Using this without my SensorCode (which uses Interrupts) is working.

Resources