Search Results

Search found 510 results on 21 pages for 'decrypt'.

Page 9/21 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • How can I encrypt CoreData contents on an iPhone

    - by James A. Rosen
    I have some information I'd like to store statically encrypted on an iPhone application. I'm new to iPhone development, some I'm not terribly familiar with CoreData and how it integrates with the views. I have the data as JSON, though I can easily put it into a SQLITE3 database or any other backing data format. I'll take whatever is easiest (a) to encrypt and (b) to integrate with the iPhone view layer. The user will need to enter the password to decrypt the data each time the app is launched. The purpose of the encryption is to keep the data from being accessible if the user loses the phone. For speed reasons, I would prefer to encrypt and decrypt the entire file at once rather than encrypting each individual field in each row of the database. Note: this isn't the same idea as Question 929744, in which the purpose is to keep the user from messing with or seeing the data. The data should be perfectly transparent when in use. Also note: I'm willing to use SQLCipher to store the data, but would prefer to use things that already exist on the iPhone/CoreData framework rather than go through the lengthy build/integration process involved.

    Read the article

  • Ruby - encrypted_strings

    - by Tom Andersen
    A bit of a Ruby newbie here - should be an easy question: I want to use the encrypted_strings gem to create a password encrypted string: (from http://rdoc.info/projects/pluginaweek/encrypted_strings) Question is: Everything works fine, but how come I don't need the password to decrypt the string? Say I want to store the string somewhere for a while,like the session. Is the password also stored with it? (which would seem very strange?). And no, I'm not planning on using 'secret-key' or any similar hack as a password. I am planning on dynamically generating a class variable @@password using a uuid, which I don't store other than in memory, and can change from one running of the program to the next. Symmetric: >> password = 'shhhh' => "shhhh" >> crypted_password = password.encrypt(:symmetric, :password => 'secret_key') => "qSg8vOo6QfU=\n" >> crypted_password.class => String >> crypted_password == 'shhhh' => true >> password = crypted_password.decrypt => "shhhh"

    Read the article

  • Help decrypting in ColdFusion passwords created in .NET

    - by KnightStalker
    I have a SQL db storing passwords that were encrypted through a .NET application, that I need to decrypt through a ColdFusion app. I just can't seem to get things set upproperly for the CF decryption to work. Any help would by appreciated. Thanks. The .NET decryption code is: public string Decrypt(string input) { try { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); int ZeroBasedByteCount = (input.Length / 2); //Put the input string into the byte array byte[] inputByteArray = new byte[ZeroBasedByteCount]; int i; int x; for (x = 0;x<ZeroBasedByteCount;x++) { i = (Convert.ToInt32(input.Substring(x * 2, 2), 16)); inputByteArray[x] = (byte)i; } //Create the crypto objects des.Key = ASCIIEncoding.ASCII.GetBytes(key); des.IV = ASCIIEncoding.ASCII.GetBytes(key); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); //Flush the data through the crypto stream into the memory stream cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); //Get the decrypted data back from the memory stream StringBuilder ret = new StringBuilder(); foreach(byte b in ms.ToArray()) { ret.Append((char)b); } return ret.ToString(); } catch(Exception ex) { throw(ex); return null; } }

    Read the article

  • how to edit a text message ( sms ) as it arrives in windows mobile 6 using managed code

    - by x86shadow
    I want to make an application to be installed on two pocket PCs and send Encrypted text messages and receive and decrypt them on the other device. I already made an application that gets special text messages ( starting with !farenc! ) and I know how to Encrypt/Decrypt the messages as well but I don't know how to edit a text message as it's arrive ( for decryption ). please help. thanks in advance and sorry for my bad English using System; using System.Linq; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Microsoft.WindowsMobile; using Microsoft.WindowsMobile.PocketOutlook; using Microsoft.WindowsMobile.PocketOutlook.MessageInterception; namespace SMSDECRYPT { public partial class Form1 : Form { MessageInterceptor _SMSCatcher = new MessageInterceptor(InterceptionAction.Notify, true); MessageCondition _SMSFilter = new MessageCondition(); public Form1() { InitializeComponent(); _SMSFilter.Property = MessageProperty.Body; _SMSFilter.ComparisonType = MessagePropertyComparisonType.StartsWith; _SMSFilter.CaseSensitive = true; _SMSFilter.ComparisonValue = "!farenc!"; _SMSCatcher.MessageCondition = _SMSFilter; _SMSCatcher.MessageReceived += new MessageInterceptorEventHandler(_SMSCatcher_MessageReceived); } private void Form1_Load(object sender, EventArgs e) { //... } void _SMSCatcher_MessageReceived(object sender, MessageInterceptorEventArgs e) { SmsMessage mySMS = (SmsMessage)e.Message; string sms = mySMS.Body.ToString(); sms = sms.Substring(8); //Decryption //... //Update the received message and replace it with the decrypted text //!!!HELP!!! } } }

    Read the article

  • ASP MVC: E-mail Verification (Encrypting the activation link)

    - by wh0emPah
    Okay i'm a little bit stuck on how to solve this problem. When a user registers. I want to send him a link so that he can verify hes email address. But i have troubles generating the link. I've already written the controller to accept the links with the correct keys. i only have no idea on how to generate the activation keys. So when the user registers i'll send him a link by mail like this: Your activation link is : http://site.com/user/verify?key=keyhere Now i have created this method (called by the controller/action) to handle the key in the link: public string Verify(string value) { String email = Decrypt(value); user u = gebRep.GetUsers().WithEmail(email).SingleOrDefault(); if (u != null) { u.emailValid = true; userReppository.Save(); } return "Invallid validation value!"; } Now my problem is I have no idea on how to encrypt and decrypt the email into some sort of key (url friendly) So i can mail it with the link and can use it to verify the email. I need some kind of (not to complicated but secure) way to encrypt the email into a urlfriendly key. Tyvm

    Read the article

  • XML Decryption Bug (referencing issue)

    - by OrangePekoe
    Hi, Needing some explanation of what exactly the decryption is doing, in addition to some help on solving the problem. Currently, when a portion of XML is encrypted, and then decrypted, the DOM appears to work correctly. We can see the element is encrypted and then see it return back once it is decrypted. Our problem lies when a user tries to change data in that same element after decryption has occurred. When a user changes some settings, data in the XML should change. However, if the user attempts to change an XML element that has been decrypted the changes are not reflected in the DOM. We have a reference pointer to the XML element that is used to bind the element to an object. If you encrypt the node and then decrypt it, the reference pointer now points to a valid orphaned XML element that is no longer part of the DOM. After decryption, there will be 2 copies of the XML element. One in the DOM as expected (though will not reflect new changes), and one orphaned element in memory that is still referenced by our pointer. The orphaned element is valid (reflects new changes). We can see that this orphaned element is owned by the DOM, but when we try to return its parent, it returns null. The question is: Where did this orphaned xml element come from? And how can we get it to correctly append (replace old data) to the DOM? The code resembles: public static void Decrypt(XmlDocument Doc, SymmetricAlgorithm Alg) { if (Doc == null) throw new ArgumentNullException("Doc"); if (Alg == null) throw new ArgumentNullException("Alg"); XmlElement encryptedElement = Doc.GetElementsByTagName("EncryptedData")[0] as XmlElement; if (encryptedElement == null) { throw new XmlException("The EncryptedData element was not found."); } EncryptedData edElement = new EncryptedData(); edElement.LoadXml(encryptedElement); EncryptedXml exml = new EncryptedXml(); byte[] rgbOutput = exml.DecryptData(edElement, Alg); exml.ReplaceData(encryptedElement, rgbOutput); }

    Read the article

  • no default constructor exists for class

    - by MixedCoder
    #include "Includes.h" enum BlowfishAlgorithm { ECB, CBC, CFB64, OFB64, }; class Blowfish { public: struct bf_key_st { unsigned long P[18]; unsigned long S[1024]; }; Blowfish(BlowfishAlgorithm algorithm); void Dispose(); void SetKey(unsigned char data[]); unsigned char Encrypt(unsigned char buffer[]); unsigned char Decrypt(unsigned char buffer[]); char EncryptIV(); char DecryptIV(); private: BlowfishAlgorithm _algorithm; unsigned char _encryptIv[200]; unsigned char _decryptIv[200]; int _encryptNum; int _decryptNum; }; class GameCryptography { public: Blowfish _blowfish; GameCryptography(unsigned char key[]); void Decrypt(unsigned char packet[]); void Encrypt(unsigned char packet[]); Blowfish Blowfish; void SetKey(unsigned char k[]); void SetIvs(unsigned char i1[],unsigned char i2[]); }; GameCryptography::GameCryptography(unsigned char key[]) { } Error:IntelliSense: no default constructor exists for class "Blowfish" ???!

    Read the article

  • Encouter error "Linux ip -6 addr add failed" while setting up OpenVPN client

    - by Mickel
    I am trying to set up my router to use OpenVPN and have gotten quite far (I think), but something seems to be missing and I am not sure what. Here is my configuration for the client: client dev tun proto udp remote ovpn.azirevpn.net 1194 remote-random resolv-retry infinite auth-user-pass /tmp/password.txt nobind persist-key persist-tun ca /tmp/AzireVPN.ca.crt remote-cert-tls server reneg-sec 0 verb 3 OpenVPN client log: Nov 8 15:45:13 rc_service: httpd 15776:notify_rc start_vpnclient1 Nov 8 15:45:14 openvpn[27196]: OpenVPN 2.3.2 arm-unknown-linux-gnu [SSL (OpenSSL)] [LZO] [EPOLL] [MH] [IPv6] built on Nov 1 2013 Nov 8 15:45:14 openvpn[27196]: NOTE: the current --script-security setting may allow this configuration to call user-defined scripts Nov 8 15:45:14 openvpn[27196]: Socket Buffers: R=[116736->131072] S=[116736->131072] Nov 8 15:45:14 openvpn[27202]: UDPv4 link local: [undef] Nov 8 15:45:14 openvpn[27202]: UDPv4 link remote: [AF_INET]178.132.75.14:1194 Nov 8 15:45:14 openvpn[27202]: TLS: Initial packet from [AF_INET]178.132.75.14:1194, sid=44d80db5 8b36adf9 Nov 8 15:45:14 openvpn[27202]: WARNING: this configuration may cache passwords in memory -- use the auth-nocache option to prevent this Nov 8 15:45:14 openvpn[27202]: VERIFY OK: depth=1, C=RU, ST=Moscow, L=Moscow, O=Azire Networks, OU=VPN, CN=Azire Networks, name=Azire Networks, [email protected] Nov 8 15:45:14 openvpn[27202]: Validating certificate key usage Nov 8 15:45:14 openvpn[27202]: ++ Certificate has key usage 00a0, expects 00a0 Nov 8 15:45:14 openvpn[27202]: VERIFY KU OK Nov 8 15:45:14 openvpn[27202]: Validating certificate extended key usage Nov 8 15:45:14 openvpn[27202]: ++ Certificate has EKU (str) TLS Web Server Authentication, expects TLS Web Server Authentication Nov 8 15:45:14 openvpn[27202]: VERIFY EKU OK Nov 8 15:45:14 openvpn[27202]: VERIFY OK: depth=0, C=RU, ST=Moscow, L=Moscow, O=AzireVPN, OU=VPN, CN=ovpn, name=ovpn, [email protected] Nov 8 15:45:15 openvpn[27202]: Data Channel Encrypt: Cipher 'BF-CBC' initialized with 128 bit key Nov 8 15:45:15 openvpn[27202]: Data Channel Encrypt: Using 160 bit message hash 'SHA1' for HMAC authentication Nov 8 15:45:15 openvpn[27202]: Data Channel Decrypt: Cipher 'BF-CBC' initialized with 128 bit key Nov 8 15:45:15 openvpn[27202]: Data Channel Decrypt: Using 160 bit message hash 'SHA1' for HMAC authentication Nov 8 15:45:15 openvpn[27202]: Control Channel: TLSv1, cipher TLSv1/SSLv3 DHE-RSA-AES256-SHA, 2048 bit RSA Nov 8 15:45:15 openvpn[27202]: [ovpn] Peer Connection Initiated with [AF_INET]178.132.75.14:1194 Nov 8 15:45:17 openvpn[27202]: SENT CONTROL [ovpn]: 'PUSH_REQUEST' (status=1) Nov 8 15:45:17 openvpn[27202]: PUSH: Received control message: 'PUSH_REPLY,ifconfig-ipv6 2a03:8600:1001:4010::101f/64 2a03:8600:1001:4010::1,route-ipv6 2000::/3 2A03:8600:1001:4010::1,redirect-gateway def1 bypass-dhcp,dhcp-option DNS 194.1.247.30,tun-ipv6,route-gateway 178.132.77.1,topology subnet,ping 3,ping-restart 15,ifconfig 178.132.77.33 255.255.255.192' Nov 8 15:45:17 openvpn[27202]: OPTIONS IMPORT: timers and/or timeouts modified Nov 8 15:45:17 openvpn[27202]: OPTIONS IMPORT: --ifconfig/up options modified Nov 8 15:45:17 openvpn[27202]: OPTIONS IMPORT: route options modified Nov 8 15:45:17 openvpn[27202]: OPTIONS IMPORT: route-related options modified Nov 8 15:45:17 openvpn[27202]: OPTIONS IMPORT: --ip-win32 and/or --dhcp-option options modified Nov 8 15:45:17 openvpn[27202]: TUN/TAP device tun0 opened Nov 8 15:45:17 openvpn[27202]: TUN/TAP TX queue length set to 100 Nov 8 15:45:17 openvpn[27202]: do_ifconfig, tt->ipv6=1, tt->did_ifconfig_ipv6_setup=1 Nov 8 15:45:17 openvpn[27202]: /usr/sbin/ip link set dev tun0 up mtu 1500 Nov 8 15:45:18 openvpn[27202]: /usr/sbin/ip addr add dev tun0 178.132.77.33/26 broadcast 178.132.77.63 Nov 8 15:45:18 openvpn[27202]: /usr/sbin/ip -6 addr add 2a03:8600:1001:4010::101f/64 dev tun0 Nov 8 15:45:18 openvpn[27202]: Linux ip -6 addr add failed: external program exited with error status: 254 Nov 8 15:45:18 openvpn[27202]: Exiting due to fatal error Any ideas are most welcome!

    Read the article

  • How good is Word's password protection?

    - by Yuval
    Hi, I have a password protected MS-Word 2007 file that needs to stay private. How good is Word's protection? If it's not very good, can you suggest a better method for keeping the file protected? EDIT: my goal is to send the protected file to a recipient (who knows the password). I assume this recipient knows nothing about encryption/decryption, but if I absolutely have to, I'll encrypt the file and painstakingly teach the recipient how to decrypt it.

    Read the article

  • Possible to get cleartext password?

    - by Farhan
    I have hosting service hosted on more than 20+ Plesk servers, version 11. As in the previous versions, the passwords were not encrypted, then if i had to design some tools to manage the hosting accounts, i just picked up the cleartext passwords from the Database. but as now the passwords are encrypted, is there any way i can decrypt the passwords? through API or any other way so that i can integrate my php based hosting management with plesk 11?

    Read the article

  • How do I integrate GPG with alpine?

    - by Thomas
    I have tried a couple of howtos, but they seem to either be too out of date or just plain don't work (don't work for me, at least). How do I sign and encrypt messages, as well as check integrity of received messages (and decrypt them if needed) in pine/alpine? I tried pipeing (with "|") but the terminal doesn't seem to cooperate so that I can provide my passphrase.

    Read the article

  • Encrypt uploaded pdf files with mcrypt and php

    - by microchasm
    I'm currently set up with a CentOS box that utilizes mcrypt to encrypt/decrypt data to/from the database. In my haste, I forgot that I also need a solution to encrypt files (primarily pdf, with a xls and txt file here and there). Is there a way to utilize mcrypt to encrypt uploaded pdf files? I understand the possibility of file_get_contents() with txt; is a similar solution available for other formats? Thanks!

    Read the article

  • Encrypt pdf files with mcrypt and php

    - by microchasm
    I'm currently set up with a CentOS box that utilizes mcrypt to encrypt/decrypt data to/from the database. In my haste, I forgot that I also need a solution to encrypt files (primarily pdf, with a xls and txt file here and there). Is there a way to utilize mcrypt to encrypt pdf files? I understand the possibility of file_get_contents() with txt; is a similar solution available for other formats? Thanks!

    Read the article

  • Decrypting EFS w/o altering timestamp - possible?

    - by grojo
    Hi, I'd like to decrypt some EFS-encrypted files, but I do not know how to do that without altering the timestamp. When encrypting/decrypting files, the modified-time is set to the current time. I'd like to preserve the original timestamp, as the files have not really changed. Is this possible? Solutions i dont think work copy to/from FAT (timestamp resolution differs) copy to from Samba share (same) programmatically copy original timestamp and reapply after decryption (possible, but need to handle decryption time which may vary)

    Read the article

  • Sharing public key with ssh

    - by jtnire
    Hi Everyone, Is it possible to somehow setup an ssh server that doesn't require a username,password or cert to login? If that's not possible, if I were to give all customers the same public key, would each connection be encrypted individually? (i.e. user A coudn't decrypt the payload of user B's connection) I wish to provide access to a single program, which will prompt for a username and password. Encryption is essential though, and users must not be able to snoop in on each other Thanks

    Read the article

  • gpg4win PGP Error occured

    - by ffffff
    I use gpg4win in Mailer and want to use a PGP email. but I cant solve this pgp error. "The input pass phrase meets neither of the listed key" [Environment] OS: Vista Business SP2 GnuPG 2.0.12(gpg4win) decrypt and encrypt are possible.

    Read the article

  • How to mount LUKS partition securely on server

    - by Ency
    I'm curious if it is possible to mount a partition encrypted by cryptsetup with LUKS securely and automatically on Ubuntu 10.0.4 LTS. For example, if I use the key for the encrypted partition, than that key has to be presented on a device that is not encrypted and if someone steals my disk they'll be able to find the key and decrypt the partition. Is there any safe way to mount an encrypted partition? If not, does anything exist to do what I want?

    Read the article

  • Using AES encryption in .NET - CryptographicException saying the padding is invalid and cannot be removed

    - by Jake Petroules
    I wrote some AES encryption code in C# and I am having trouble getting it to encrypt and decrypt properly. If I enter "test" as the passphrase and "This data must be kept secret from everyone!" I receive the following exception: System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed. at System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast) at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) at System.Security.Cryptography.CryptoStream.FlushFinalBlock() at System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing) at System.IO.Stream.Close() at System.IO.Stream.Dispose() ... And if I enter something less than 16 characters I get no output. I believe I need some special handling in the encryption since AES is a block cipher, but I'm not sure exactly what that is, and I wasn't able to find any examples on the web showing how. Here is my code: using System; using System.IO; using System.Security.Cryptography; using System.Text; public static class DatabaseCrypto { public static EncryptedData Encrypt(string password, string data) { return DatabaseCrypto.Transform(true, password, data, null, null) as EncryptedData; } public static string Decrypt(string password, EncryptedData data) { return DatabaseCrypto.Transform(false, password, data.DataString, data.SaltString, data.MACString) as string; } private static object Transform(bool encrypt, string password, string data, string saltString, string macString) { using (AesManaged aes = new AesManaged()) { aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; int key_len = aes.KeySize / 8; int iv_len = aes.BlockSize / 8; const int salt_size = 8; const int iterations = 8192; byte[] salt = encrypt ? new Rfc2898DeriveBytes(string.Empty, salt_size).Salt : Convert.FromBase64String(saltString); byte[] bc_key = new Rfc2898DeriveBytes("BLK" + password, salt, iterations).GetBytes(key_len); byte[] iv = new Rfc2898DeriveBytes("IV" + password, salt, iterations).GetBytes(iv_len); byte[] mac_key = new Rfc2898DeriveBytes("MAC" + password, salt, iterations).GetBytes(16); aes.Key = bc_key; aes.IV = iv; byte[] rawData = encrypt ? Encoding.UTF8.GetBytes(data) : Convert.FromBase64String(data); using (ICryptoTransform transform = encrypt ? aes.CreateEncryptor() : aes.CreateDecryptor()) using (MemoryStream memoryStream = encrypt ? new MemoryStream() : new MemoryStream(rawData)) using (CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, encrypt ? CryptoStreamMode.Write : CryptoStreamMode.Read)) { if (encrypt) { cryptoStream.Write(rawData, 0, rawData.Length); return new EncryptedData(salt, mac_key, memoryStream.ToArray()); } else { byte[] originalData = new byte[rawData.Length]; int count = cryptoStream.Read(originalData, 0, originalData.Length); return Encoding.UTF8.GetString(originalData, 0, count); } } } } } public class EncryptedData { public EncryptedData() { } public EncryptedData(byte[] salt, byte[] mac, byte[] data) { this.Salt = salt; this.MAC = mac; this.Data = data; } public EncryptedData(string salt, string mac, string data) { this.SaltString = salt; this.MACString = mac; this.DataString = data; } public byte[] Salt { get; set; } public string SaltString { get { return Convert.ToBase64String(this.Salt); } set { this.Salt = Convert.FromBase64String(value); } } public byte[] MAC { get; set; } public string MACString { get { return Convert.ToBase64String(this.MAC); } set { this.MAC = Convert.FromBase64String(value); } } public byte[] Data { get; set; } public string DataString { get { return Convert.ToBase64String(this.Data); } set { this.Data = Convert.FromBase64String(value); } } } static void ReadTest() { Console.WriteLine("Enter password: "); string password = Console.ReadLine(); using (StreamReader reader = new StreamReader("aes.cs.txt")) { EncryptedData enc = new EncryptedData(); enc.SaltString = reader.ReadLine(); enc.MACString = reader.ReadLine(); enc.DataString = reader.ReadLine(); Console.WriteLine("The decrypted data was: " + DatabaseCrypto.Decrypt(password, enc)); } } static void WriteTest() { Console.WriteLine("Enter data: "); string data = Console.ReadLine(); Console.WriteLine("Enter password: "); string password = Console.ReadLine(); EncryptedData enc = DatabaseCrypto.Encrypt(password, data); using (StreamWriter stream = new StreamWriter("aes.cs.txt")) { stream.WriteLine(enc.SaltString); stream.WriteLine(enc.MACString); stream.WriteLine(enc.DataString); Console.WriteLine("The encrypted data was: " + enc.DataString); } }

    Read the article

  • How do encrypt a long or int using the Bouncy Castle crypto routines for BlackBerry?

    - by DanG
    How do encrypt/decrypt a long or int using the Bouncy Castle crypto routines for BlackBerry? I know how to encrypt/decrypt a String. I can encrypt a long but can't get a long to decrypt properly. Some of this is poorly done, but I'm just trying stuff out at the moment. I've included my entire crypto engine here: import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.engines.AESFastEngine; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.KeyParameter; public class CryptoEngine { // Global Variables // Global Objects private static AESFastEngine engine; private static BufferedBlockCipher cipher; private static KeyParameter key; public static boolean setEncryptionKey(String keyText) { // adding in spaces to force a proper key keyText += " "; // cutting off at 128 bits (16 characters) keyText = keyText.substring(0, 16); keyText = HelperMethods.cleanUpNullString(keyText); byte[] keyBytes = keyText.getBytes(); key = new KeyParameter(keyBytes); engine = new AESFastEngine(); cipher = new PaddedBufferedBlockCipher(engine); // just for now return true; } public static String encryptString(String plainText) { try { byte[] plainArray = plainText.getBytes(); cipher.init(true, key); byte[] cipherBytes = new byte[cipher.getOutputSize(plainArray.length)]; int cipherLength = cipher.processBytes(plainArray, 0, plainArray.length, cipherBytes, 0); cipher.doFinal(cipherBytes, cipherLength); String cipherString = new String(cipherBytes); return cipherString; } catch (DataLengthException e) { Logger.logToConsole(e); } catch (IllegalArgumentException e) { Logger.logToConsole(e); } catch (IllegalStateException e) { Logger.logToConsole(e); } catch (InvalidCipherTextException e) { Logger.logToConsole(e); } catch (Exception ex) { Logger.logToConsole(ex); } // else return "";// default bad value } public static String decryptString(String encryptedText) { try { byte[] cipherBytes = encryptedText.getBytes(); cipher.init(false, key); byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)]; int decryptedLength = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0); cipher.doFinal(decryptedBytes, decryptedLength); String decryptedString = new String(decryptedBytes); // crop accordingly int index = decryptedString.indexOf("\u0000"); if (index >= 0) { decryptedString = decryptedString.substring(0, index); } return decryptedString; } catch (DataLengthException e) { Logger.logToConsole(e); } catch (IllegalArgumentException e) { Logger.logToConsole(e); } catch (IllegalStateException e) { Logger.logToConsole(e); } catch (InvalidCipherTextException e) { Logger.logToConsole(e); } catch (Exception ex) { Logger.logToConsole(ex); } // else return "";// default bad value } private static byte[] convertLongToByteArray(long longToConvert) { return new byte[] { (byte) (longToConvert >>> 56), (byte) (longToConvert >>> 48), (byte) (longToConvert >>> 40), (byte) (longToConvert >>> 32), (byte) (longToConvert >>> 24), (byte) (longToConvert >>> 16), (byte) (longToConvert >>> 8), (byte) (longToConvert) }; } private static long convertByteArrayToLong(byte[] byteArrayToConvert) { long returnable = 0; for (int counter = 0; counter < byteArrayToConvert.length; counter++) { returnable += ((byteArrayToConvert[byteArrayToConvert.length - counter - 1] & 0xFF) << counter * 8); } if (returnable < 0) { returnable++; } return returnable; } public static long encryptLong(long plainLong) { try { String plainString = String.valueOf(plainLong); String cipherString = encryptString(plainString); byte[] cipherBytes = cipherString.getBytes(); long returnable = convertByteArrayToLong(cipherBytes); return returnable; } catch (Exception e) { Logger.logToConsole(e); } // else return Integer.MIN_VALUE;// default bad value } public static long decryptLong(long encryptedLong) { byte[] cipherBytes = convertLongToByteArray(encryptedLong); cipher.init(false, key); byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)]; int decryptedLength = cipherBytes.length; try { cipher.doFinal(decryptedBytes, decryptedLength); } catch (DataLengthException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidCipherTextException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } long plainLong = convertByteArrayToLong(decryptedBytes); return plainLong; } public static boolean encryptBoolean(int plainBoolean) { return false; } public static boolean decryptBoolean(int encryptedBoolean) { return false; } public static boolean testLongToByteArrayConversion() { boolean returnable = true; // fails out of the bounds of an integer, the conversion to long from byte // array does not hold, need to figure out a better solution for (long counter = -1000000; counter < 1000000; counter++) { long test = counter; byte[] bytes = convertLongToByteArray(test); long result = convertByteArrayToLong(bytes); if (result != test) { returnable = false; Logger.logToConsole("long conversion failed"); Logger.logToConsole("test = " + test + "\n result = " + result); } // regardless } // the end Logger.logToConsole("final returnable result = " + returnable); return returnable; } }

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >