/v3.2/nimbits-sdk/src/com/nimbits/security/Encryptor.java

http://nimbits-server.googlecode.com/ · Java · 67 lines · 42 code · 7 blank · 18 comment · 3 complexity · 5c16ce25b28579ae6c748369990cfffe MD5 · raw file

  1. /*
  2. * Copyright (c) 2010 Tonic Solutions LLC.
  3. *
  4. * http://www.nimbits.com
  5. *
  6. *
  7. * Licensed under the GNU GENERAL PUBLIC LICENSE, Version 3.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
  8. *
  9. * http://www.gnu.org/licenses/gpl.html
  10. *
  11. * Unless required by applicable law or agreed to in writing, software distributed under the license is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
  12. */
  13. package com.nimbits.security;
  14. import sun.misc.*;
  15. import javax.crypto.*;
  16. import java.io.*;
  17. import java.security.*;
  18. /**
  19. * Created by bsautner
  20. * User: benjamin
  21. * Date: 8/11/11
  22. * Time: 11:39 AM
  23. */
  24. public class Encryptor {
  25. public static String encode(String str) {
  26. BASE64Encoder encoder = new BASE64Encoder();
  27. str = encoder.encodeBuffer(str.getBytes());
  28. return str;
  29. }
  30. public static String decode(String str) {
  31. BASE64Decoder decoder = new BASE64Decoder();
  32. try {
  33. str = new String(decoder.decodeBuffer(str));
  34. } catch (IOException e) {
  35. e.printStackTrace();
  36. }
  37. return str;
  38. }
  39. public static void writeEncryptedFile(final String fileName, final String unencryptedString) throws IOException {
  40. final String e = encode(unencryptedString);
  41. final Writer out = new OutputStreamWriter(new FileOutputStream(fileName));
  42. out.write(e);
  43. out.close();
  44. }
  45. public static String readEncryptedFile(final String fileName) throws IOException {
  46. String retStr = null;
  47. final File file = new File(fileName);
  48. if (file.exists()) {
  49. final StringBuilder sb = new StringBuilder();
  50. final BufferedReader in = new BufferedReader(new FileReader(fileName));
  51. String str;
  52. while ((str = in.readLine()) != null) {
  53. sb.append(str);
  54. }
  55. in.close();
  56. retStr = decode(sb.toString());
  57. }
  58. return retStr;
  59. }
  60. }