Search Results

Search found 217 results on 9 pages for 'plaintext'.

Page 3/9 | < Previous Page | 1 2 3 4 5 6 7 8 9  | Next Page >

  • How to use Bouncy Castle lightweight API with AES and PBE

    - by Adrian
    I have a block of ciphertext that was created using the JCE algorithim "PBEWithSHA256And256BitAES-CBC-BC". The provider is BouncyCastle. What I'd like to do it decrypt this ciphertext using the BouncyCastle lightweight API. I don't want to use JCE because that requires installing the Unlimited Strength Jurisdiction Policy Files. Documentation seems to be thin on the ground when it comes to using BC with PBE and AES. Here's what I have so far. The decryption code runs without exception but returns rubbish. The encryption code, String password = "qwerty"; String plainText = "hello world"; byte[] salt = generateSalt(); byte[] cipherText = encrypt(plainText, password.toCharArray(), salt); private static byte[] generateSalt() throws NoSuchAlgorithmException { byte salt[] = new byte[8]; SecureRandom saltGen = SecureRandom.getInstance("SHA1PRNG"); saltGen.nextBytes(salt); return salt; } private static byte[] encrypt(String plainText, char[] password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { Security.addProvider(new BouncyCastleProvider()); PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20); PBEKeySpec pbeKeySpec = new PBEKeySpec(password); SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC"); SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); Cipher encryptionCipher = Cipher.getInstance("PBEWithSHA256And256BitAES-CBC-BC"); encryptionCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec); return encryptionCipher.doFinal(plainText.getBytes()); } The decryption code, byte[] decryptedText = decrypt(cipherText, password.getBytes(), salt); private static byte[] decrypt(byte[] cipherText, byte[] password, byte[] salt) throws DataLengthException, IllegalStateException, InvalidCipherTextException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { BlockCipher engine = new AESEngine(); CBCBlockCipher cipher = new CBCBlockCipher(engine); PKCS5S1ParametersGenerator keyGenerator = new PKCS5S1ParametersGenerator(new SHA256Digest()); keyGenerator.init(password, salt, 20); CipherParameters keyParams = keyGenerator.generateDerivedParameters(256); cipher.init(false, keyParams); byte[] decryptedBytes = new byte[cipherText.length]; int numBytesCopied = cipher.processBlock(cipherText, 0, decryptedBytes, 0); return decryptedBytes; }

    Read the article

  • How can I turn a string of text into a BigInteger representation for use in an El Gamal cryptosystem

    - by angstrom91
    I'm playing with the El Gamal cryptosystem, and my goal is to be able to encipher and decipher long sequences of text. I have come up with a method that works for short sequences, but does not work for long sequences, and I cannot figure out why. El Gamal requires the plaintext to be an integer. I have turned my string into a byte[] using the .getBytes() method for Strings, and then created a BigInteger out of the byte[]. After encryption/decryption, I turn the BigInteger into a byte[] using the .toByteArray() method for BigIntegers, and then create a new String object from the byte[]. This works perfectly when i call ElGamalEncipher with strings up to 129 characters. With 130 or more characters, the output produced is garbled. Can someone suggest how to solve this issue? Is this an issue with my method of turning the string into a BigInteger? If so, is there a better way to turn my string of text into a BigInteger and back? Below is my encipher/decipher code. public static BigInteger[] ElGamalEncipher(String plaintext, BigInteger p, BigInteger g, BigInteger r) { // returns a BigInteger[] cipherText // cipherText[0] is c // cipherText[1] is d BigInteger[] cipherText = new BigInteger[2]; BigInteger pText = new BigInteger(plaintext.getBytes()); // 1: select a random integer k such that 1 <= k <= p-2 BigInteger k = new BigInteger(p.bitLength() - 2, sr); // 2: Compute c = g^k(mod p) BigInteger c = g.modPow(k, p); // 3: Compute d= P*r^k = P(g^a)^k(mod p) BigInteger d = pText.multiply(r.modPow(k, p)).mod(p); // C =(c,d) is the ciphertext cipherText[0] = c; cipherText[1] = d; return cipherText; } public static String ElGamalDecipher(BigInteger c, BigInteger d, BigInteger a, BigInteger p) { //returns the plaintext enciphered as (c,d) // 1: use the private key a to compute the least non-negative residue // of an inverse of (c^a)' (mod p) BigInteger z = c.modPow(a, p).modInverse(p); BigInteger P = z.multiply(d).mod(p); byte[] plainTextArray = P.toByteArray(); String output = null; try { output = new String(plainTextArray, "UTF8"); } catch (Exception e) { } return output; }

    Read the article

  • AESlibrary only two lines

    - by user303968
    Does anyone know a c++ library that uses advanced encryption standard encryption that can achieve encryption and decryption (using counter mode) in just two lines of codes. No need of padding or buffering the plaintexts the library will take care of all this. I have had a look at crypto++, openssl and libtomcrypt but in these it seems I need to write codes to buffer and pad the plaintexts which I don't want. In brief, I need something along these lines: ciphertext = encrypt(ctr_mode(),plaintext,key) plaintext = decrypt(ctr_mode(),ciphertext,key) Thanks!

    Read the article

  • webscraper grabbing images, but not entering info into database

    - by Jason
    Hello, again. I'm having more issues with my script entering info into my database. The script below grabs a page, strips down the necessary info, then downloads the related image file. After that, it is supposed to enter the information gleaned from the URL into the database. For some reason, the script seems to iterate through the URLs, as I get downloaded images for each URL, but each URL's product is not entered into the database. The script will insert the first product's categories and product info, and then it just stops, and continues to download images. Any suggestions? <?php define('IN_PHPBB', true); $phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './'; $phpEx = substr(strrchr(__FILE__, '.'), 1); include($phpbb_root_path . 'common.' . $phpEx); include($phpbb_root_path . 'includes/simple_html_dom.' . $phpEx); // Start session management $user->session_begin(); $auth->acl($user->data); $user->setup(); set_time_limit(259200); function save($in, $out) { $ch = curl_init ($in); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); $rawdata=curl_exec($ch); curl_close ($ch); if(file_exists($out)) { unlink($out); } $fp = fopen($out,'x'); fwrite($fp, $rawdata); fclose($fp); } function scrape($i) { $url = 'http:/xxxxxxxx/index.php?main_page=product_info&products_id='.$i.'&zenid=e4b7dde8de02e1df005d4549e2e3e529'; echo "$url -- "; $exists = file_get_contents($url); if ($exists != false) { $html = file_get_html($url); foreach($html->find('body') as $html) { $test = $html->find('#productName', 0); if ($test) { $item['title'] = trim($html->find('#productName', 0)->plaintext); $item['price'] = trim($html->find('#productPrices', 0)->plaintext); $item['cat'] = $html->find('#navBreadCrumb', 0)->plaintext; list($home, $item['cat'], $item['subcat'], $title) = explode("::", $item['cat']); $item['cat'] = str_replace("&nbsp;", "", $item['cat']); $item['subcat'] = str_replace("\n", "", str_replace("&nbsp;", "", $item['subcat'])); $item['desc'] = trim($html->find('#productDescription', 0)->plaintext); $item['model'] = $html->find('ul#productDetailsList', 0)->find('li', 0)->plaintext; $item['model'] = explode(":", $item['model']); $item['model'] = trim($item['model'][1]); $item['manufacturer'] = $html->find('ul#productDetailsList', 0)->find('li', 1)->plaintext; $item['manufacturer'] = explode(":", $item['manufacturer']); $item['manufacturer'] = trim($item['manufacturer'][1]); foreach($html->find('img') as $img) { if($img->alt == $item['title']) { $item['img_sm'] = $img->src; } } $ret[] = $item; } } $html->clear(); unset($html); unset($item); return $ret; } else { echo "Could not find page<br />"; } unset($exists); } $i = 1; $end = 9999999; while($i < $end) { $ret = scrape($i); if(isset($ret)) { foreach($ret as $v) { $item['title'] = $v['title']; $item['price'] = $v['price']; $item['desc'] = $v['desc']; $item['model'] = $v['model']; $item['manufacturer'] = $v['manufacturer']; $item['image'] = $v['image']; $item['cat'] = $v['cat']; $item['subcat'] = $v['subcat']; $item['img_sm'] = $v['img_sm']; } unset($ret); unset($v); $sm_img_src = "http://xxxxxx/".$item['img_sm']; $ext = strrchr($item['img_sm'], '.'); $filename = $item['model'] . $ext; $lg_img_src = "http://xxxxx/images/STC/".$filename; $new_sm = "./rip_images/small/{$filename}"; $new_lg = "./rip_images/large/{$filename}"; $item['image'] = $filename; save($lg_img_src,$new_lg); save($sm_img_src,$new_sm); //see if parent cat exists $sql = 'SELECT cat_id FROM ' . SHOP_CAT_TABLE . ' WHERE cat_name = "'.$db->sql_escape($item['cat']).'"'; $result = $db->sql_query($sql); $parent = $db->sql_fetchrow($result); $db->sql_freeresult($result); // if not exists if($parent['cat_id'] == '') { //add the parent cat to the db $sql_ary = array( 'cat_name' => $item['cat'], 'cat_parent' => 0 ); $sql = 'INSERT INTO '.SHOP_CAT_TABLE.' '.$db->sql_build_array('INSERT', $sql_ary); $db->sql_query($sql); $cat_id = $db->sql_nextid(); //see if subcat exists $sql = 'SELECT cat_id FROM ' . SHOP_CAT_TABLE . ' WHERE cat_name = "'.$db->sql_escape($item['subcat']).'"'; $result = $db->sql_query($sql); $row = $db->sql_fetchrow($result); $db->sql_freeresult($result); // if not exists if($row['cat_id'] == '') { //add subcat to db $sql_ary = array( 'cat_name' => $db->sql_escape($item['subcat']), 'cat_parent' => $cat_id ); $sql = 'INSERT INTO '.SHOP_CAT_TABLE.' '.$db->sql_build_array('INSERT', $sql_ary); $db->sql_query($sql); $item_cat = $db->sql_nextid(); } else //if exists { $item_cat = $row['cat_id']; } } else //if parent cat exists { //see if subcat exists $sql = 'SELECT cat_id FROM ' . SHOP_CAT_TABLE . ' WHERE cat_name = "'.$db->sql_escape($item['subcat']).'"'; $result = $db->sql_query($sql); $row = $db->sql_fetchrow($result); $db->sql_freeresult($result); // if not exists if($row['cat_id'] == '') { //add the subcat to the db $sql_ary = array( 'cat_name' => $db->sql_escape($item['subcat']), 'cat_parent' => $parent['cat_id'] ); $sql = 'INSERT INTO '.SHOP_CAT_TABLE.' '.$db->sql_build_array('INSERT', $sql_ary); $db->sql_query($sql); $item_cat = $db->sql_nextid(); } else //if exists { $item_cat = $row['cat_id']; } } $sql_ary = array( 'item_title' => $db->sql_escape($item['title']), 'item_price' => $db->sql_escape($item['price']), 'item_desc' => $db->sql_escape($item['desc']), 'item_model' => $db->sql_escape($item['model']), 'item_manufacturer' => $db->sql_escape($item['manufacturer']), 'item_image' => $db->sql_escape($item['image']), 'item_cat' => $db->sql_escape($item_cat) ); $sql = 'INSERT INTO ' . SHOP_ITEM_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary); $db->sql_query($sql); garbage_collection(); echo 'Done<br />'; } $i++; unset($item); } ?>

    Read the article

  • error in encryption program

    - by Raja
    #include<iostream> #include<math.h> #include<string> using namespace std; int gcd(int n,int m) { if(m<=n && n%m ==0) return m; if(n<m) return gcd(m,n); else return gcd(m,n%m); } int REncryptText(char m) { int p = 11, q = 3; int e = 3; int n = p * q; int phi = (p - 1) * (q - 1); int check1 = gcd(e, p - 1); int check2 = gcd(e, q - 1); int check3 = gcd(e, phi); // // Compute d such that ed = 1 (mod phi) //i.e. compute d = e-1 mod phi = 3-1 mod 20 //i.e. find a value for d such that phi divides (ed-1) //i.e. find d such that 20 divides 3d-1. //Simple testing (d = 1, 2, ...) gives d = 7 // double d = Math.Pow(e, -1) % phi; int d = 7; // public key = (n,e) // (33,3) //private key = (n,d) //(33 ,7) double g = pow(m,e); int ciphertext = g %n; // Now say we want to encrypt the message m = 7, c = me mod n = 73 mod 33 = 343 mod 33 = 13. Hence the ciphertext c = 13. //double decrypt = Math.Pow(ciphertext, d) % n; return ciphertext; } int main() { char plaintext[80],str[80]; cout<<" enter the text you want to encrpt"; cin.get(plaintext,79); int l =strlen(plaintext); for ( int i =0 ; i<l ; i++) { char s = plaintext[i]; str[i]=REncryptText(s); } for ( int i =0 ; i<l ; i++) { cout<<"the encryption of string"<<endl; cout<<str[i]; } return 0; }

    Read the article

  • Identify html tags for image, video in text and convert them into images, videos while laying dynami

    - by neha
    Hi all, In my app I need to lay some text which I'm getting from a parsed data. Currently I'm currently laying it in a label. The problem is there are going to be some html tags indicating an image [along with its url] and videos etc in that plaintext. What is a good way to handle this identifying images and videos tags and laying corresponding images and videos along with rest of the plaintext dynamically? Thanx in advance.

    Read the article

  • fatal error occured while trying to sysprep the machine windows 8.1

    - by Mick
    I try do sysprep in Windows 8.1 I have create unattend.xml <settings pass="oobeSystem"> <component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <InputLocale>en-US</InputLocale> <SystemLocale>en-US</SystemLocale> <UILanguage>en-US</UILanguage> <UILanguageFallback>en-US</UILanguageFallback> <UserLocale>en-US</UserLocale> </component> <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <OEMInformation> <Manufacturer>XYZ</Manufacturer> <SupportURL>http://www.XYZ.com</SupportURL> </OEMInformation> <OOBE> <HideEULAPage>true</HideEULAPage> <NetworkLocation>Work</NetworkLocation> <ProtectYourPC>1</ProtectYourPC> </OOBE> <UserAccounts> <AdministratorPassword> <Value>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</Value> <PlainText>false</PlainText> </AdministratorPassword> <LocalAccounts> <LocalAccount wcm:action="add"> <Password> <Value>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</Value> <PlainText>false</PlainText> </Password> <Description>Admin</Description> <DisplayName>Admin</DisplayName> <Group>Administrators</Group> <Name>Admin</Name> </LocalAccount> </LocalAccounts> </UserAccounts> <WindowsFeatures> <ShowWindowsMediaPlayer>false</ShowWindowsMediaPlayer> <ShowMediaCenter>false</ShowMediaCenter> </WindowsFeatures> <RegisteredOrganization>XXXXXXXXXXXXXXXXXXXXX</RegisteredOrganization> <RegisteredOwner>XXXXXXXXXXXXXXXXXXXXXXX</RegisteredOwner> <TimeZone>Central European Standard Time</TimeZone> <ShowWindowsLive>false</ShowWindowsLive> </component> </settings> <settings pass="specialize"> <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <RegisteredOrganization>XXXXXXXXXXXXXXXXXXXXXXXXX</RegisteredOrganization> <RegisteredOwner>XXXXXXXXXXXXXXXXXXXXXXXXXX</RegisteredOwner> <ProductKey>XXXXXXXXXXXXXXXXXXXXXXXXXXXXX</ProductKey> </component> </settings> And then I run sysprep.exe /oobe /generalize /shutdown I see this error: fatal error occurred while trying to sysprep the machine

    Read the article

  • what is wrong in java AES decrypt function?

    - by rohit
    hi, i modified the code available on http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html and made encrypt and decrypt methods in program. but i am getting BadpaddingException.. also the function is returning null.. why it is happing?? whats going wrong? please help me.. these are variables i am using: kgen = KeyGenerator.getInstance("AES"); kgen.init(128); raw = new byte[]{(byte)0x00,(byte)0x11,(byte)0x22,(byte)0x33,(byte)0x44,(byte)0x55,(byte)0x66,(byte)0x77,(byte)0x88,(byte)0x99,(byte)0xaa,(byte)0xbb,(byte)0xcc,(byte)0xdd,(byte)0xee,(byte)0xff}; skeySpec = new SecretKeySpec(raw, "AES"); cipher = Cipher.getInstance("AES"); plainText=null; cipherText=null; following is decrypt function.. public String decrypt(String cipherText) { try { cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] original = cipher.doFinal(cipherText.getBytes()); plainText = new String(original); } catch(BadPaddingException e) { } return plainText; }

    Read the article

  • Why wont this compile its killing me. (java)

    - by Ryan The Leach
    import java.util.*; public class Caesar { public static void main(String [] args) { final boolean DEBUG = false; System.out.println("Welcome to the Caesar Cypher"); System.out.println("----------------------------"); Scanner keyboard = new Scanner (System.in); System.out.print("Enter a String : "); String plainText = keyboard.nextLine(); System.out.print("Enter an offset: "); int offset = keyboard.nextInt(); String cipherText = ""; for(int i=0;i<plainText.length();i++) { int chVal = plainText.charAt(i); if (DEBUG) {int debugchVal = chVal;} chVal +=offset; if (DEBUG) {System.out.print(chVal + "\t");} while (chVal <32 || chVal > 127) { if (chVal < 32) chVal += 96; if (chVal > 127) chVal -= 96; if(DEBUG) {System.out.print(chVal+" ");} } if (DEBUG) {System.out.println();} char c = (char) chVal; cipherText = cipherText + c; if (DEBUG) {System.out.println(i + "\t" + debugchVal + "\t" + chVal + "\t" + c + "\t" + cipherText);} } System.out.println(cipherText); } }

    Read the article

  • Is sending a hashed password over the wire a security hole?

    - by Ubiquitous Che
    I've come across a system that is in use by a company that we are considering partnering with on a medium-sized (for us, not them) project. They have a web service that we will need to integrate with. My current understanding of proper username/password management is that the username may be stored as plaintext in the database. Every user should have a unique pseudo-random salt, which may also be stored in plaintext. The text of their password must be concatenated with the salt and then this combined string may be hashed and stored in the database in an nvarchar field. So long as passwords are submitted to the website (or web service) over plaintext, everything should be just lovely. Feel free to rip into my understanding as summarized above if I'm wrong. Anyway, back to the subject at hand. The WebService run by this potential partner doesn't accept username and password, which I had anticipated. Instead, it accepts two string fields named 'Username' and 'PasswordHash'. The 'PasswordHash' value that I have been given does indeed look like a hash, and not just a value for a mis-named password field. This is raising a red flag for me. I'm not sure why, but I feel uncomfortable sending a hashed password over the wire for some reason. Off the top of my head I can't think of a reason why this would be a bad thing... Technically, the hash is available on the database anyway. But it's making me nervous, and I'm not sure if there's a reason for this or if I'm just being paranoid.

    Read the article

  • Windows 7 Pro sysprep not working

    - by Callum D
    Hello, I'm trying to sysprep a Windows 7 Professional machine, prior to grabbing an image for mass deployment on identical hardware, and am having a hard time getting sysprep to work (at all). I've created an XML answer file with WSIM, and have a basic setupcomplete.cmd file, but none of the configurations in the answer file seem to be applied. I've read technet articles and googled, and I still have no idea why this is happening. Is someone able to have a look at the answer file I've attached and let me know where I'm going wrong? thanks, Callum AutoUnattend.XML <?xml version="1.0" encoding="utf-8"?> <unattend xmlns="urn:schemas-microsoft-com:unattend"> <settings pass="specialize"> <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <AutoLogon> <Password> <Value>**********************************</Value> <PlainText>false</PlainText> </Password> <Username>administrator</Username> <LogonCount>1</LogonCount> <Enabled>true</Enabled> </AutoLogon> <WindowsFeatures> <ShowMediaCenter>false</ShowMediaCenter> <ShowWindowsMediaPlayer>false</ShowWindowsMediaPlayer> </WindowsFeatures> <CopyProfile>true</CopyProfile> <DoNotCleanTaskBar>true</DoNotCleanTaskBar> <RegisteredOrganization>SomeCompany (UK) Ltd.</RegisteredOrganization> <RegisteredOwner>SomeCompany User</RegisteredOwner> <ShowWindowsLive>false</ShowWindowsLive> <TimeZone>GMT Standard Time</TimeZone> </component> <component name="Security-Malware-Windows-Defender" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <DisableAntiSpyware>true</DisableAntiSpyware> </component> </settings> <settings pass="oobeSystem"> <component name="Microsoft-Windows-International-Core" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <SystemLocale>en-UK</SystemLocale> <UserLocale>en-UK</UserLocale> <UILanguage>en-US</UILanguage> <InputLocale>0809:00000809</InputLocale> </component> <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <OOBE> <HideEULAPage>true</HideEULAPage> <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE> <NetworkLocation>Work</NetworkLocation> <ProtectYourPC>1</ProtectYourPC> </OOBE> <UserAccounts> <AdministratorPassword> <Value>*************************************************=</Value> <PlainText>false</PlainText> </AdministratorPassword> </UserAccounts> </component> <component name="Microsoft-Windows-Deployment" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Reseal> <Mode>OOBE</Mode> </Reseal> </component> </settings> <settings pass="generalize"> <component name="Microsoft-Windows-Security-SPP" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <SkipRearm>0</SkipRearm> </component> </settings> <settings pass="windowsPE"> <component name="Microsoft-Windows-Setup" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <UseConfigurationSet>true</UseConfigurationSet> </component> </settings> <cpi:offlineImage cpi:source="wim:c:/wim/install.wim#Windows 7 PROFESSIONAL" xmlns:cpi="urn:schemas-microsoft-com:cpi" /> </unattend>

    Read the article

  • Getting EOFException while trying to read from SSLSocket

    - by Isac
    Hi, I am developing a SSL client that will do a simple request to a SSL server and wait for the response. The SSL handshake and the writing goes OK but I can't READ data from the socket. I turned on the debug of java.net.ssl and got the following: [..] main, READ: TLSv1 Change Cipher Spec, length = 1 [Raw read]: length = 5 0000: 16 03 01 00 20 .... [Raw read]: length = 32 [..] main, READ: TLSv1 Handshake, length = 32 Padded plaintext after DECRYPTION: len = 32 [..] * Finished verify_data: { 29, 1, 139, 226, 25, 1, 96, 254, 176, 51, 206, 35 } %% Didn't cache non-resumable client session: [Session-1, SSL_RSA_WITH_RC4_128_MD5] [read] MD5 and SHA1 hashes: len = 16 0000: 14 00 00 0C 1D 01 8B E2 19 01 60 FE B0 33 CE 23 ..........`..3.# Padded plaintext before ENCRYPTION: len = 70 [..] a.j.y. main, WRITE: TLSv1 Application Data, length = 70 [Raw write]: length = 75 [..] Padded plaintext before ENCRYPTION: len = 70 [..] main, WRITE: TLSv1 Application Data, length = 70 [Raw write]: length = 75 [..] main, received EOFException: ignored main, called closeInternal(false) main, SEND TLSv1 ALERT: warning, description = close_notify Padded plaintext before ENCRYPTION: len = 18 [..] main, WRITE: TLSv1 Alert, length = 18 [Raw write]: length = 23 [..] main, called close() main, called closeInternal(true) main, called close() main, called closeInternal(true) The [..] are the certificate chain. Here is a code snippet: try { System.setProperty("javax.net.debug","all"); /* * Set up a key manager for client authentication * if asked by the server. Use the implementation's * default TrustStore and secureRandom routines. */ SSLSocketFactory factory = null; try { SSLContext ctx; KeyManagerFactory kmf; KeyStore ks; char[] passphrase = "importkey".toCharArray(); ctx = SSLContext.getInstance("TLS"); kmf = KeyManagerFactory.getInstance("SunX509"); ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream("keystore.jks"), passphrase); kmf.init(ks, passphrase); ctx.init(kmf.getKeyManagers(), null, null); factory = ctx.getSocketFactory(); } catch (Exception e) { throw new IOException(e.getMessage()); } SSLSocket socket = (SSLSocket)factory.createSocket("server ip", 9999); /* * send http request * * See SSLSocketClient.java for more information about why * there is a forced handshake here when using PrintWriters. */ SSLSession session = socket.getSession(); [build query] byte[] buff = query.toWire(); out.write(buff); out.flush(); InputStream input = socket.getInputStream(); int readBytes = -1; int randomLength = 1024; byte[] buffer = new byte[randomLength]; while((readBytes = input.read(buffer, 0, randomLength)) != -1) { LOG.debug("Read: " + new String(buffer)); } input.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } I can write multiple times and I don't get any error but the EOFException happens on the first read. Am I doing something wrong with the socket or with the SSL authentication? Thank you.

    Read the article

  • C#, AES encryption check!

    - by Data-Base
    I have this code for AES encryption, can some one verify that this code is good and not wrong? it works fine, but I'm more concern about the implementation of the algorithm // Plaintext value to be encrypted. //Passphrase from which a pseudo-random password will be derived. //The derived password will be used to generate the encryption key. //Password can be any string. In this example we assume that this passphrase is an ASCII string. //Salt value used along with passphrase to generate password. //Salt can be any string. In this example we assume that salt is an ASCII string. //HashAlgorithm used to generate password. Allowed values are: "MD5" and "SHA1". //SHA1 hashes are a bit slower, but more secure than MD5 hashes. //PasswordIterations used to generate password. One or two iterations should be enough. //InitialVector (or IV). This value is required to encrypt the first block of plaintext data. //For RijndaelManaged class IV must be exactly 16 ASCII characters long. //KeySize. Allowed values are: 128, 192, and 256. //Longer keys are more secure than shorter keys. //Encrypted value formatted as a base64-encoded string. public static string Encrypt(string PlainText, string Password, string Salt, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize) { byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector); byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt); byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText); PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations); byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8); RijndaelManaged SymmetricKey = new RijndaelManaged(); SymmetricKey.Mode = CipherMode.CBC; ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes); MemoryStream MemStream = new MemoryStream(); CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write); CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length); CryptoStream.FlushFinalBlock(); byte[] CipherTextBytes = MemStream.ToArray(); MemStream.Close(); CryptoStream.Close(); return Convert.ToBase64String(CipherTextBytes); } public static string Decrypt(string CipherText, string Password, string Salt, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize) { byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector); byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt); byte[] CipherTextBytes = Convert.FromBase64String(CipherText); PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations); byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8); RijndaelManaged SymmetricKey = new RijndaelManaged(); SymmetricKey.Mode = CipherMode.CBC; ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes); MemoryStream MemStream = new MemoryStream(CipherTextBytes); CryptoStream cryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read); byte[] PlainTextBytes = new byte[CipherTextBytes.Length]; int ByteCount = cryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length); MemStream.Close(); cryptoStream.Close(); return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount); } Thank you

    Read the article

  • Padding error - when using AES Encryption in Java and Decryption in C

    - by user234445
    Hi All, I have a problem while decrypting the xl file in rijndael 'c' code (The file got encrypted in Java through JCE) and this problem is happening only for the excel files types which having formula's. Remaining all file type encryption/decryption is happening properly. (If i decrypt the same file in java the output is coming fine.) While i am dumped a file i can see the difference between java decryption and 'C' file decryption. od -c -b filename(file decrypted in C) 0034620 005 006 \0 \0 \0 \0 022 \0 022 \0 320 004 \0 \0 276 4 005 006 000 000 000 000 022 000 022 000 320 004 000 000 276 064 0034640 \0 \0 \0 \0 \f \f \f \f \f \f \f \f \f \f \f \f 000 000 000 000 014 014 014 014 014 014 014 014 014 014 014 014 0034660 od -c -b filename(file decrypted in Java) 0034620 005 006 \0 \0 \0 \0 022 \0 022 \0 320 004 \0 \0 276 4 005 006 000 000 000 000 022 000 022 000 320 004 000 000 276 064 0034640 \0 \0 \0 \0 000 000 000 000 0034644 (the above is the difference between the dumped files) The following java code i used to encrypt the file. public class AES { /** * Turns array of bytes into string * * @param buf Array of bytes to convert to hex string * @return Generated hex string */ public static void main(String[] args) throws Exception { File file = new File("testxls.xls"); byte[] lContents = new byte[(int) file.length()]; try { FileInputStream fileInputStream = new FileInputStream(file); fileInputStream.read(lContents); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(256); // 192 and 256 bits may not be available // Generate the secret key specs. SecretKey skey = kgen.generateKey(); //byte[] raw = skey.getEncoded(); byte[] raw = "aabbccddeeffgghhaabbccddeeffgghh".getBytes(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(lContents); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] original = cipher.doFinal(lContents); FileOutputStream f1 = new FileOutputStream("testxls_java.xls"); f1.write(original); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } I used the following file for decryption in 'C'. #include <stdio.h> #include "rijndael.h" #define KEYBITS 256 #include <stdio.h> #include "rijndael.h" #define KEYBITS 256 int main(int argc, char **argv) { unsigned long rk[RKLENGTH(KEYBITS)]; unsigned char key[KEYLENGTH(KEYBITS)]; int i; int nrounds; char dummy[100] = "aabbccddeeffgghhaabbccddeeffgghh"; char *password; FILE *input,*output; password = dummy; for (i = 0; i < sizeof(key); i++) key[i] = *password != 0 ? *password++ : 0; input = fopen("doc_for_logu.xlsb", "rb"); if (input == NULL) { fputs("File read error", stderr); return 1; } output = fopen("ori_c_res.xlsb","w"); nrounds = rijndaelSetupDecrypt(rk, key, 256); while (1) { unsigned char plaintext[16]; unsigned char ciphertext[16]; int j; if (fread(ciphertext, sizeof(ciphertext), 1, input) != 1) break; rijndaelDecrypt(rk, nrounds, ciphertext, plaintext); fwrite(plaintext, sizeof(plaintext), 1, output); } fclose(input); fclose(output); }

    Read the article

  • Restful Services, oData, and Rest Sharp

    - by jkrebsbach
    After a great presentation by Jason Sheehan at MDC about RestSharp, I decided to implement it. RestSharp is a .Net framework for consuming restful data sources via either Json or XML. My first step was to put together a Restful data source for RestSharp to consume.  Staying entirely withing .Net, I decided to use Microsoft's oData implementation, built on System.Data.Services.DataServices.  Natively, these support Json, or atom+pub xml.  (XML with a few bells and whistles added on) There are three main steps for creating an oData data source: 1)  override CreateDSPMetaData This is where the metadata data is returned.  The meta data defines the structure of the data to return.  The structure contains the relationships between data objects, along with what properties the objects expose.  The meta data can and should be somehow cached so that the structure is not rebuild with every data request. 2) override CreateDataSource The context contains the data the data source will publish.  This method is the conduit which will populate the metadata objects to be returned to the requestor. 3) implement static InitializeService At this point we can set up security, along with setting up properties of the web service (versioning, etc)   Here is a web service which publishes stock prices for various Products (stocks) in various Categories. namespace RestService {     public class RestServiceImpl : DSPDataService<DSPContext>     {         private static DSPContext _context;         private static DSPMetadata _metadata;         /// <summary>         /// Populate traversable data source         /// </summary>         /// <returns></returns>         protected override DSPContext CreateDataSource()         {             if (_context == null)             {                 _context = new DSPContext();                 Category utilities = new Category(0);                 utilities.Name = "Electric";                 Category financials = new Category(1);                 financials.Name = "Financial";                                 IList products = _context.GetResourceSetEntities("Products");                 Product electric = new Product(0, utilities);                 electric.Name = "ABC Electric";                 electric.Description = "Electric Utility";                 electric.Price = 3.5;                 products.Add(electric);                 Product water = new Product(1, utilities);                 water.Name = "XYZ Water";                 water.Description = "Water Utility";                 water.Price = 2.4;                 products.Add(water);                 Product banks = new Product(2, financials);                 banks.Name = "FatCat Bank";                 banks.Description = "A bank that's almost too big";                 banks.Price = 19.9; // This will never get to the client                 products.Add(banks);                 IList categories = _context.GetResourceSetEntities("Categories");                 categories.Add(utilities);                 categories.Add(financials);                 utilities.Products.Add(electric);                 utilities.Products.Add(electric);                 financials.Products.Add(banks);             }             return _context;         }         /// <summary>         /// Setup rules describing published data structure - relationships between data,         /// key field, other searchable fields, etc.         /// </summary>         /// <returns></returns>         protected override DSPMetadata CreateDSPMetadata()         {             if (_metadata == null)             {                 _metadata = new DSPMetadata("DemoService", "DataServiceProviderDemo");                 // Define entity type product                 ResourceType product = _metadata.AddEntityType(typeof(Product), "Product");                 _metadata.AddKeyProperty(product, "ProductID");                 // Only add properties we wish to share with end users                 _metadata.AddPrimitiveProperty(product, "Name");                 _metadata.AddPrimitiveProperty(product, "Description");                 EntityPropertyMappingAttribute att = new EntityPropertyMappingAttribute("Name",                     SyndicationItemProperty.Title, SyndicationTextContentKind.Plaintext, true);                 product.AddEntityPropertyMappingAttribute(att);                 att = new EntityPropertyMappingAttribute("Description",                     SyndicationItemProperty.Summary, SyndicationTextContentKind.Plaintext, true);                 product.AddEntityPropertyMappingAttribute(att);                 // Define products as a set of product entities                 ResourceSet products = _metadata.AddResourceSet("Products", product);                 // Define entity type category                 ResourceType category = _metadata.AddEntityType(typeof(Category), "Category");                 _metadata.AddKeyProperty(category, "CategoryID");                 _metadata.AddPrimitiveProperty(category, "Name");                 _metadata.AddPrimitiveProperty(category, "Description");                 // Define categories as a set of category entities                 ResourceSet categories = _metadata.AddResourceSet("Categories", category);                 att = new EntityPropertyMappingAttribute("Name",                     SyndicationItemProperty.Title, SyndicationTextContentKind.Plaintext, true);                 category.AddEntityPropertyMappingAttribute(att);                 att = new EntityPropertyMappingAttribute("Description",                     SyndicationItemProperty.Summary, SyndicationTextContentKind.Plaintext, true);                 category.AddEntityPropertyMappingAttribute(att);                 // A product has a category, a category has products                 _metadata.AddResourceReferenceProperty(product, "Category", categories);                 _metadata.AddResourceSetReferenceProperty(category, "Products", products);             }             return _metadata;         }         /// <summary>         /// Based on the requesting user, can set up permissions to Read, Write, etc.         /// </summary>         /// <param name="config"></param>         public static void InitializeService(DataServiceConfiguration config)         {             config.SetEntitySetAccessRule("*", EntitySetRights.All);             config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;             config.DataServiceBehavior.AcceptProjectionRequests = true;         }     } }     The objects prefixed with DSP come from the samples on the oData site: http://www.odata.org/developers The products and categories objects are POCO business objects with no special modifiers. Three main options are available for defining the MetaData of data sources in .Net: 1) Generate Entity Data model (Potentially directly from SQL Server database).  This requires the least amount of manual interaction, and uses the edmx WYSIWYG editor to generate a data model.  This can be directly tied to the SQL Server database and generated from the database if you want a data access layer tightly coupled with your database. 2) Object model decorations.  If you already have a POCO data layer, you can decorate your objects with properties to statically inform the compiler how the objects are related.  The disadvantage is there are now tags strewn about your business layer that need to be updated as the business rules change.  3) Programmatically construct metadata object.  This is the object illustrated above in CreateDSPMetaData.  This puts all relationship information into one central programmatic location.  Here business rules are constructed when the DSPMetaData response object is returned.   Once you have your service up and running, RestSharp is designed for XML / Json, along with the native Microsoft library.  There are currently some differences between how Jason made RestSharp expect XML with how atom+pub works, so I found better results currently with the Json implementation - modifying the RestSharp XML parser to make an atom+pub parser is fairly trivial though, so use what implementation works best for you. I put together a sample console app which calls the RestSvcImpl.svc service defined above (and assumes it to be running on port 2000).  I used both RestSharp as a client, and also the default Microsoft oData client tools. namespace RestConsole {     class Program     {         private static DataServiceContext _ctx;         private enum DemoType         {             Xml,             Json         }         static void Main(string[] args)         {             // Microsoft implementation             _ctx = new DataServiceContext(new System.Uri("http://localhost:2000/RestServiceImpl.svc"));             var msProducts = RunQuery<Product>("Products").ToList();             var msCategory = RunQuery<Category>("/Products(0)/Category").AsEnumerable().Single();             var msFilteredProducts = RunQuery<Product>("/Products?$filter=length(Name) ge 4").ToList();             // RestSharp implementation                          DemoType demoType = DemoType.Json;             var client = new RestClient("http://localhost:2000/RestServiceImpl.svc");             client.ClearHandlers(); // Remove all available handlers             // Set up handler depending on what situation dictates             if (demoType == DemoType.Json)                 client.AddHandler("application/json", new RestSharp.Deserializers.JsonDeserializer());             else if (demoType == DemoType.Xml)             {                 client.AddHandler("application/atom+xml", new RestSharp.Deserializers.XmlDeserializer());             }                          var request = new RestRequest();             if (demoType == DemoType.Json)                 request.RootElement = "d"; // service root element for json             else if (demoType == DemoType.Xml)             {                 request.XmlNamespace = "http://www.w3.org/2005/Atom";             }                              // Return all products             request.Resource = "/Products?$orderby=Name";             RestResponse<List<Product>> productsResp = client.Execute<List<Product>>(request);             List<Product> products = productsResp.Data;             // Find category for product with ProductID = 1             request.Resource = string.Format("/Products(1)/Category");             RestResponse<Category> categoryResp = client.Execute<Category>(request);             Category category = categoryResp.Data;             // Specialized queries             request.Resource = string.Format("/Products?$filter=ProductID eq {0}", 1);             RestResponse<Product> productResp = client.Execute<Product>(request);             Product product = productResp.Data;                          request.Resource = string.Format("/Products?$filter=Name eq '{0}'", "XYZ Water");             productResp = client.Execute<Product>(request);             product = productResp.Data;         }         private static IEnumerable<TElement> RunQuery<TElement>(string queryUri)         {             try             {                 return _ctx.Execute<TElement>(new Uri(queryUri, UriKind.Relative));             }             catch (Exception ex)             {                 throw ex;             }         }              } }   Feel free to step through the code a few times and to attach a debugger to the service as well to see how and where the context and metadata objects are constructed and returned.  Pay special attention to the response object being returned by the oData service - There are several properties of the RestRequest that can be used to help troubleshoot when the structure of the response is not exactly what would be expected.

    Read the article

  • Spring Security DB Authentication w/Hibernate and hashed passwords?

    - by Seth
    I'm trying to set up spring security 3 to authenticate users against my hibernate 3 database. I'm storing only sha1 hashes of the passwords in the database (not plaintext). I've looked at this and this, which tell me to implement my own UserDetailsService. Unfortunately, the UserDetails that loadUserByUsername spits out seem to need the plaintext password, which I don't have. How is this usually handled? Can Spring Security actually do what I need here? Am I missing something?

    Read the article

  • What is an efficient way to write password cracking algorithm (python)

    - by Luminance
    This problem might be relatively simple, but I'm given two text files. One text file contains all encrypted passwords encrypted via crypt.crypt in python. The other list contains over 400k+ normal dictionary words. The assignment is that given 3 different functions which transform strings from their normal case to all different permutations of capitalizations, transforms a letter to a number (if it looks alike, e.g. G - 6, B - 8), and reverses a string. The thing is that given the 10 - 20 encrypted passwords in the password file, what is the most efficient way to get the fastest running solution in python to run those functions on dictionary word in the words file? It is given that all those words, when transformed in whatever way, will encrypt to a password in the password file. Here is the function which checks if a given string, when encrypted, is the same as the encrypted password passed in: def check_pass(plaintext,encrypted): crypted_pass = crypt.crypt(plaintext,encrypted) if crypted_pass == encrypted: return True else: return False Thanks in advance.

    Read the article

  • NSData to NSString by changing the value null is returned. I need you help

    - by kevin
    *cipher.h, cipher.m all code : http://watchitlater.com/blog/2010/02/java-and-iphone-aes-interoperability Cipher.m -(NSData *)encrypt:(NSData *)plainText{ return [self transform:KCCEncrypt data:plainText; } step1. Cipher *cipher = [[Cipher alloc]initWithKey:@"1234567890"]; NSData *input = [@"kevin" dataUsingEncoding:NSUTF8StringEncoding]; NSData *data = [cipher encrypt:input]; data variables NSLog print : <4d1c4d7f 1592718c fd588cec 84053e35 step2. NSString *changeVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; data variables NSLog print : null NSData to NSString by changing the value null is returned. By converting NSString NSURLConnection want to transfer. I need you help

    Read the article

  • Simple RSA encryption (Java)

    - by jake blue
    This is simply for fun. This will not be used for any actual encryption. I'm only first year comp sci student and love cryptography. This took a long time to get working. At approximately N = 18, it begins breaking down. It won't encrypt messages properly after that point. I'm not sure why. Any insights? I'd also appreciate any links you could provide me to tutorials or interesting reading about Cryptography. import java.math.BigInteger; import java.security.SecureRandom; /** * Cryptography. * * Generates public and private keys used in encryption and * decryption * */ public class RSA { private final static BigInteger one = new BigInteger("1"); private final static SecureRandom random = new SecureRandom(); // prime numbers private BigInteger p; private BigInteger q; // modulus private BigInteger n; // totient private BigInteger t; // public key private BigInteger e; // private key private BigInteger d; private String cipherText; /** * Constructor for objects of class RSA */ public RSA(int N) { p = BigInteger.probablePrime(N/2, random); q = BigInteger.probablePrime(N/2, random); // initialising modulus n = p.multiply(q); // initialising t by euclid's totient function (p-1)(q-1) t = (p.subtract(one)).multiply(q.subtract(one)); // initialising public key ~ 65537 is common public key e = new BigInteger("65537"); } public int generatePrivateKey() { d = e.modInverse(t); return d.intValue(); } public String encrypt(String plainText) { String encrypted = ""; int j = 0; for(int i = 0; i < plainText.length(); i++){ char m = plainText.charAt(i); BigInteger bi1 = BigInteger.valueOf(m); BigInteger bi2 = bi1.modPow(e, n); j = bi2.intValue(); m = (char) j; encrypted += m; } cipherText = encrypted; return encrypted; } public String decrypt() { String decrypted = ""; int j = 0; for(int i = 0; i < cipherText.length(); i++){ char c = cipherText.charAt(i); BigInteger bi1 = BigInteger.valueOf(c); BigInteger bi2 = bi1.modPow(d, n); j = bi2.intValue(); c = (char) j; decrypted += c; } return decrypted; } }

    Read the article

  • Encoding license file for privacy

    - by Swingline Rage
    Hi, We're using XML Digital Signatures for signing and verifying our license keys. The signing works fine and has been running smoothly. The XML license file contains a few (plaintext) details about the license, along with a binary signature. We'd like to encode (I don't say encrypt) those plaintext details (license duration, user name, etc, etc.) so they're not immediately visible to prying eyes. Is there a standard (eg, base 64 or something else) that people use in this situation? It doesn't need to be secure or particularly clever, just enough to conceal the information in Notepad. Thanks : )

    Read the article

  • How to ReHash a password stored into my Database ? (PHP)

    - by Vincent Roye
    Hi! I have some passwords encrypted in my database and I would like to find a way to display them. Here is how they are saved into my mysql database: function generateHash($plainText, $salt = null){ if ($salt === null) { $salt = substr(md5(uniqid(rand(), true)), 0, 25); } else { $salt = substr($salt, 0, 25); } return $salt . sha1($salt . $plainText); } $secure_pass = generateHash($this->clean_password); Then $secure_pass is saved into my database. Anyone would have an idea ?? Thank you very much ;)

    Read the article

  • Does this exist: a standardized way of documenting a file-system structure

    - by eegg
    At work, I'm in charge of maintaining the organization of a whole lot of varied data on a standard file-system. Part of this is coming up with sensible classification (by similarity, need, read/write access, etc), but the bigger part is actually documenting it: what documents/files/media should go where, what should not be in this directory, "for something slightly different, see ../../other-dir", etc. At the moment, I've documented this using a plaintext file filing.txt in every directory I want to document. If someone is unsure what's meant to be in any directory, they read that file. This works alright, but it seems odd that I have this primitive custom solution to a problem that any maintainer of a non-trivial directory structure must experience. Every company I've known of, for example, has some kind of shared file-system where agreed terminology for categorization is important. In my experience, people just have to learn what's what by trial-and-error and experimentation. So allow me to propose a better solution, and hopefully you can tell me if it exists. Any directory on any filesystem can have a hidden plaintext file named .filing. Its contents are descriptive human language. It uses some markup like Markdown, with little more than bold, italic, and (relative) hyperlinks to other directories. Now a suitably-enabled file browser will check for a file named .filing whenever it displays a directory. If it exists, its contents are parsed and displayed in an unobtrusive pane near the directory-path widget. Any links therein can be clicked, and the user will be taken to the target directory of that link. I think that the effort of implementing such a standard would pay back many times over in usability gains. We would have, say, plugins for Nautilus, Konqueror, etc.. It could be used to display directory information in the standard file lists served by webservers. And so on. So, question: does such a thing exist? If not, why not? Do people think it's a worthwhile idea?

    Read the article

  • AES Cipher not picking up IV

    - by timothyjc
    I am trying to use an IV with AES so that the encrypted text is unpredictable. However, the encrypted hex string is always the same. I have actually tried a few methods of attempting to add some randomness by passing some additional parameters to the cipher init call: 1) Manual IV generation byte[] iv = generateIv(); IvParameterSpec ivspec = new IvParameterSpec(iv); 2) Asking cipher to generate IV AlgorithmParameters params = cipher.getParameters(); params.getParameterSpec(IvParameterSpec.class); 3) Using a PBEParameterSpec byte[] encryptionSalt = generateSalt(); PBEParameterSpec pbeParamSpec = new PBEParameterSpec(encryptionSalt, 1000); All of these seem to have no influence on the encrypted text.... help!!! My code: package com.citc.testencryption; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class Main extends Activity { public static final int SALT_LENGTH = 20; public static final int PBE_ITERATION_COUNT = 1000; private static final String RANDOM_ALGORITHM = "SHA1PRNG"; private static final String PBE_ALGORITHM = "PBEWithSHA256And256BitAES-CBC-BC"; private static final String CIPHER_ALGORITHM = "PBEWithSHA256And256BitAES-CBC-BC"; private static final String TAG = Main.class.getSimpleName(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { String password = "password"; String plainText = "plaintext message to be encrypted"; // byte[] salt = generateSalt(); byte[] salt = "dfghjklpoiuytgftgyhj".getBytes(); Log.i(TAG, "Salt: " + salt.length + " " + HexEncoder.toHex(salt)); PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), salt, PBE_ITERATION_COUNT); SecretKeyFactory keyFac = SecretKeyFactory.getInstance(PBE_ALGORITHM); SecretKey secretKey = keyFac.generateSecret(pbeKeySpec); byte[] key = secretKey.getEncoded(); Log.i(TAG, "Key: " + HexEncoder.toHex(key)); // PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, ITERATION_COUNT); Cipher encryptionCipher = Cipher.getInstance(CIPHER_ALGORITHM); // byte[] encryptionSalt = generateSalt(); // Log.i(TAG, "Encrypted Salt: " + encryptionSalt.length + " " + HexEncoder.toHex(encryptionSalt)); // PBEParameterSpec pbeParamSpec = new PBEParameterSpec(encryptionSalt, 1000); // byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); // Log.i(TAG, encryptionCipher.getParameters() + " "); byte[] iv = generateIv(); IvParameterSpec ivspec = new IvParameterSpec(iv); encryptionCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec); byte[] encryptedText = encryptionCipher.doFinal(plainText.getBytes()); Log.i(TAG, "Encrypted: " + HexEncoder.toHex(encryptedText)); // <== Why is this always the same :( Cipher decryptionCipher = Cipher.getInstance(CIPHER_ALGORITHM); decryptionCipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec); byte[] decryptedText = decryptionCipher.doFinal(encryptedText); Log.i(TAG, "Decrypted: " + new String(decryptedText)); } catch (Exception e) { e.printStackTrace(); } } private byte[] generateSalt() throws NoSuchAlgorithmException { SecureRandom random = SecureRandom.getInstance(RANDOM_ALGORITHM); byte[] salt = new byte[SALT_LENGTH]; random.nextBytes(salt); return salt; } private byte[] generateIv() throws NoSuchAlgorithmException { SecureRandom random = SecureRandom.getInstance(RANDOM_ALGORITHM); byte[] iv = new byte[16]; random.nextBytes(iv); return iv; } }

    Read the article

  • Generate authenticated CMSEnvelopedData Messages with bouncycastle

    - by levinalex
    I am trying to encrypt data with a password and store it inside a ASN.1 encoded CMS message (using C# and BouncyCastle 1.4) The code I have seems to have two problems: the data does not seem to be signed with a HMAC, so when I tamper with the encodedData (by enabling the commented out line), the decryption still succeeds. when I decrypt the data I have tampered with, I get beck corrupted plain text. However only a two blocks of plaintext data are corrupted. This seems to suggest that the encryption does not actually use CBC mode. (edit: disregard the second point, this is exactly how CBC is supposed to work) This is what I am testing with: public void TestMethod1() { byte[] data = new byte[1024]; // plaintext: a list of zeroes CmsEnvelopedDataGenerator generator = new CmsEnvelopedDataGenerator(); CmsPbeKey encryptionKey = new Pkcs5Scheme2PbeKey("foo", new byte[] { 1, 2, 3 }, 2048); generator.AddPasswordRecipient(encryptionKey, CmsEnvelopedDataGenerator.Aes256Cbc); CmsProcessableByteArray cmsByteArray = new CmsProcessableByteArray(data); CmsEnvelopedData envelopeData = generator.Generate(cmsByteArray, CmsEnvelopedDataGenerator.Aes256Cbc); byte[] encodedData = envelopeData.GetEncoded(); // encodedData[500] = 10; // tamper with the data RecipientID recipientID = new RecipientID(); CmsEnvelopedData decodedEnvelopeData = new CmsEnvelopedData(encodedData); RecipientInformation recipient = decodedEnvelopeData.GetRecipientInfos().GetFirstRecipient(recipientID); byte[] data2 = recipient.GetContent(encryptionKey); CollectionAssert.AreEqual(data, data2); } What am I doing wrong? What would be the correct way to write this?

    Read the article

  • Encryption in Java & Flex

    - by Jef
    I want tp encrypt and decrypt string, with defined salt. But the result must be same if the code run in java and adobe flex. The main goal is: the app in adobe flex will be generate a string that can be decrypt in server using java. I use this flex library http://crypto.hurlant.com/demo/ Try to 'Secret Key' Tab. I want to use AES Encryption, 'CBC' or 'PKCS5'. var k:String = "1234567890123456"; var kdata:ByteArray = Hex.toArray(k); var txt:String = "hello"; var data:ByteArray = Hex.toArray(Hex.fromString(txt));; var name:String = "simple-aes-cbc"; var pad:IPad =new PKCS5(); var mode:ICipher = Crypto.getCipher(name, kdata, pad); pad.setBlockSize(mode.getBlockSize()); mode.encrypt(data); encrypted.text=Hex.fromArray(data); trace(Hex.fromArray(data)); And here is the code in java String plaintext = "hello"; String key = "1234567890123456"; SecretKey keyspec = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE,keyspec); byte[] encrypted = cipher.doFinal(plaintext.getBytes()); BASE64Encoder base64 = new BASE64Encoder(); String encodedString = base64.encode(encrypted); System.out.println(encodedString); Why the result is not same? Can you guys provide the sample with the same result both of java and flex (encrypt and decrypt)? And if I want to change the paramater, for example, from cbc to ebc, which line that need to be changed? Thanks!

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9  | Next Page >