PageRenderTime 61ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/ovirt-engine-3.0.0_0001/backend/manager/modules/engineencryptutils/src/main/java/org/ovirt/engine/core/engineencryptutils/EncryptionUtils.java

#
Java | 304 lines | 176 code | 22 blank | 106 comment | 14 complexity | e4bc91fa46b51be09fc1648792997fe3 MD5 | raw file
Possible License(s): Apache-2.0
  1. package org.ovirt.engine.core.engineencryptutils;
  2. import java.io.FileInputStream;
  3. import java.io.InputStream;
  4. import java.math.BigInteger;
  5. import java.security.GeneralSecurityException;
  6. import java.security.InvalidKeyException;
  7. import java.security.Key;
  8. import java.security.KeyStore;
  9. import java.security.NoSuchAlgorithmException;
  10. import java.security.cert.Certificate;
  11. import java.util.Enumeration;
  12. import javax.crypto.BadPaddingException;
  13. import javax.crypto.Cipher;
  14. import javax.crypto.IllegalBlockSizeException;
  15. import javax.crypto.NoSuchPaddingException;
  16. import javax.crypto.spec.SecretKeySpec;
  17. import org.ovirt.engine.core.compat.Encoding;
  18. import org.ovirt.engine.core.compat.LogCompat;
  19. import org.ovirt.engine.core.compat.LogFactoryCompat;
  20. import org.ovirt.engine.core.compat.RefObject;
  21. import org.ovirt.engine.core.compat.StringHelper;
  22. public class EncryptionUtils {
  23. private static String algo = "RSA";
  24. private static String certType = "JKS";
  25. /**
  26. * Encrypts the specified source.
  27. *
  28. * @param source
  29. * The source.
  30. * @param cert
  31. * The cert.
  32. * @return base64 encoded result.
  33. */
  34. private static String encrypt(String source, Certificate cert) throws GeneralSecurityException {
  35. String result = null;
  36. byte[] cipherbytes = Encoding.UTF8.getBytes(source.trim());
  37. Cipher rsa = Cipher.getInstance(algo);
  38. rsa.init(Cipher.ENCRYPT_MODE, cert.getPublicKey());
  39. byte[] cipher = rsa.doFinal(cipherbytes);
  40. result = Encoding.Base64.getString(cipher);
  41. return result;
  42. }
  43. /**
  44. * Decrypts the specified source given a Private Key
  45. *
  46. * @param source
  47. * The source.
  48. * @param key
  49. * The private key.
  50. * @param error
  51. * The error.
  52. * @return
  53. */
  54. private static String Decrypt(String source, Key key, RefObject<String> error) {
  55. error.argvalue = "";
  56. String result = "";
  57. try {
  58. {
  59. byte[] cipherbytes = Encoding.Base64.getBytes(source);
  60. {
  61. Cipher rsa = Cipher.getInstance(algo);
  62. rsa.init(Cipher.DECRYPT_MODE, key);
  63. {
  64. byte[] plainbytes = rsa.doFinal(cipherbytes);
  65. result = Encoding.ASCII.getString(plainbytes);
  66. }
  67. }
  68. }
  69. } catch (Exception e) {
  70. log.error("Error in the Decryption", e);
  71. error.argvalue = e.getMessage();
  72. }
  73. return result;
  74. }
  75. /**
  76. * Encrypts the specified source using certification file.
  77. *
  78. * @param source
  79. * The source.
  80. * @param certificateFile
  81. * The certificate file.
  82. * @param passwd
  83. * The passwd.
  84. * @param alis
  85. * The certificate alias.
  86. * @return
  87. *
  88. * Loads a private key from a JKS file using the supplied password and encrypts the value. The string which
  89. * is returned is first base64 encoded The keyfile is loaded first off of the classpath, then from the file
  90. * system.
  91. */
  92. public final static String encrypt(String source, String certificateFile, String passwd, String alias)
  93. throws Exception {
  94. String result = "";
  95. if (!StringHelper.isNullOrEmpty(source.trim())) {
  96. try {
  97. KeyStore store = EncryptionUtils.getKeyStore(certificateFile, passwd, certType);
  98. Certificate cert = store.getCertificate(alias);
  99. result = encrypt(source, cert);
  100. } catch (Exception e) {
  101. log.error("Error doing the encryption", e);
  102. throw e;
  103. }
  104. }
  105. return result;
  106. }
  107. /**
  108. * Decrypts the specified source using certification file.
  109. *
  110. * @param source
  111. * The source.
  112. * @param keyFile
  113. * The key file.
  114. * @param passwd
  115. * The passwd.
  116. * @param alias
  117. * The certificate alias.
  118. * @return
  119. *
  120. * Loads a private key from a JKS file using the supplied password and decrypts the value. The string to be
  121. * decrypted is assumed to have been base64 encoded. The keyfile is loaded from the file system
  122. */
  123. public static String decrypt(String source, String keyFile, String passwd, String alias)
  124. throws Exception {
  125. String result = source;
  126. try {
  127. if (!StringHelper.isNullOrEmpty(source.trim())) {
  128. KeyStore store = EncryptionUtils.getKeyStore(keyFile, passwd, certType);
  129. Key key = store.getKey(alias, passwd.toCharArray());
  130. result = decrypt(source, key);
  131. }
  132. } catch (Exception e) {
  133. log.errorFormat("Failed to decrypt", e.getMessage());
  134. log.debug("Failed to decrypt", e);
  135. throw e;
  136. }
  137. return result;
  138. }
  139. private static String decrypt(String source, Key key) throws NoSuchAlgorithmException, NoSuchPaddingException,
  140. InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
  141. String result = "";
  142. byte[] cipherbytes = Encoding.Base64.getBytes(source);
  143. Cipher rsa = Cipher.getInstance(algo);
  144. rsa.init(Cipher.DECRYPT_MODE, key);
  145. byte[] plainbytes = rsa.doFinal(cipherbytes);
  146. result = Encoding.UTF8.getString(plainbytes);
  147. return result;
  148. }
  149. /**
  150. * Decrypts the specified source using Store.
  151. *
  152. * @param source
  153. * The source.
  154. * @param certificateFingerPrint
  155. * The certification finger print.
  156. * @param error
  157. * The error.
  158. * @return
  159. */
  160. public static final String Decrypt(String source, String keyFile, String passwd,
  161. RefObject<String> error) {
  162. error.argvalue = "";
  163. String result = source;
  164. if (!StringHelper.isNullOrEmpty(source.trim())) {
  165. try {
  166. KeyStore store = EncryptionUtils.getKeyStore(keyFile, passwd, certType);
  167. // Get the first one.
  168. String alias = "None";
  169. Enumeration<String> aliases = store.aliases();
  170. while (aliases.hasMoreElements()) {
  171. alias = aliases.nextElement();
  172. break;
  173. }
  174. Key key = store.getKey(alias, passwd.toCharArray());
  175. result = Decrypt(source, key, error);
  176. } catch (Exception e) {
  177. log.error("Error doing the decryption", e);
  178. error.argvalue = e.getMessage();
  179. }
  180. }
  181. return result;
  182. }
  183. /**
  184. * Determines whether the specified name is a password holder.
  185. *
  186. * @param name
  187. * The name.
  188. * @return <c>true</c> if the specified name is password; otherwise, <c>false</c>.
  189. */
  190. public static boolean IsPassword(String name) {
  191. final String PASSWORD = "NoSoup4U";
  192. return (name.toLowerCase().endsWith(PASSWORD));
  193. }
  194. public static KeyStore getKeyStore(String path, String passwd, String storeType) {
  195. try {
  196. InputStream fis = new FileInputStream(path);
  197. KeyStore store = KeyStore.getInstance(storeType);
  198. store.load(fis, passwd.toCharArray());
  199. return store;
  200. } catch (Exception e) {
  201. throw new RuntimeException(e);
  202. }
  203. }
  204. /**
  205. * Encodes a given secret by specified key material and algorithm<BR>
  206. * If not supplying any key material and algorithm using defaults:<BR>
  207. * keyMaterial - <i>"jaas is the way"</i> <BR>
  208. * algorithm - <i>"Blowfish"<i>
  209. *
  210. * @param secret
  211. * the encrypted object
  212. * @param keyMaterial
  213. * the material for the encryption
  214. * @param algorithm
  215. * defines which algorithm to use
  216. * @return the encrypted secret or null if encryption fails
  217. */
  218. public static String encode(String secret, String keyMaterial, String algorithm) {
  219. Cipher cipher;
  220. byte[] encoding = null;
  221. try {
  222. EncryptUtilParams params = new EncryptUtilParams(keyMaterial, algorithm);
  223. cipher = Cipher.getInstance(params.algorithm);
  224. cipher.init(Cipher.ENCRYPT_MODE, params.secretKey);
  225. encoding = cipher.doFinal(secret.getBytes());
  226. } catch (Exception e) {
  227. log.error("Error in encrypting the secret", e);
  228. }
  229. return encoding != null ? (new BigInteger(encoding)).toString(16) : null;
  230. }
  231. /**
  232. * Decodes a given secret by specified key material and algorithm.<BR>
  233. * If no key material and algorithm are supplied, using defaults:<BR>
  234. * keyMaterial - <i>"jaas is the way"</i> <BR>
  235. * algorithm - <i>"Blowfish"<i>
  236. *
  237. * @param secret
  238. * the object to decode
  239. * @param keyMaterial
  240. * the material for the decoding action
  241. * @param algorithm
  242. * defines which algorithm to use
  243. * @return the decoded secret or null if decode fails
  244. */
  245. public static String decode(String secret, String keyMaterial, String algorithm) {
  246. BigInteger n = new BigInteger(secret, 16);
  247. byte[] encoding = n.toByteArray();
  248. byte[] decode = null;
  249. try {
  250. EncryptUtilParams params = new EncryptUtilParams(keyMaterial, algorithm);
  251. Cipher cipher = Cipher.getInstance(params.algorithm);
  252. cipher.init(Cipher.DECRYPT_MODE, params.secretKey);
  253. decode = cipher.doFinal(encoding);
  254. } catch (Exception e) {
  255. log.error("Error in decrypting the secret", e);
  256. }
  257. return decode != null ? new String(decode) : null;
  258. }
  259. /**
  260. * Class use to holds and defines defaults values for encryption/decryption <BR>
  261. * based on. Targeted to set defaults values as used in JBoss security login module:<BR>
  262. * keyMaterial - <i>"jaas is the way"</i> <BR>
  263. * algorithm - <i>"Blowfish"<i>
  264. */
  265. private static class EncryptUtilParams {
  266. private String algorithm = null;
  267. private SecretKeySpec secretKey = null;
  268. public EncryptUtilParams(String keyMaterial, String algorithm) {
  269. if (algorithm == null || "".equals(algorithm)) {
  270. this.algorithm = "Blowfish";
  271. } else {
  272. this.algorithm = algorithm;
  273. }
  274. if (keyMaterial == null || "".equals(keyMaterial)) {
  275. secretKey = new SecretKeySpec("jaas is the way".getBytes(), this.algorithm);
  276. } else {
  277. secretKey = new SecretKeySpec(keyMaterial.getBytes(), this.algorithm);
  278. }
  279. }
  280. }
  281. private static LogCompat log = LogFactoryCompat.getLog(EncryptionUtils.class);
  282. }