Advertisement
Guest User

Untitled

a guest
Dec 20th, 2014
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.28 KB | None | 0 0
  1. package fr.tiphedor.tools;
  2.  
  3. import android.content.Context;
  4.  
  5. import org.bouncycastle.x509.X509V1CertificateGenerator;
  6.  
  7. import java.io.FileInputStream;
  8. import java.io.FileNotFoundException;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.math.BigInteger;
  12. import java.security.InvalidKeyException;
  13. import java.security.KeyPair;
  14. import java.security.KeyPairGenerator;
  15. import java.security.KeyStore;
  16. import java.security.KeyStoreException;
  17. import java.security.NoSuchAlgorithmException;
  18. import java.security.NoSuchProviderException;
  19. import java.security.PrivateKey;
  20. import java.security.PublicKey;
  21. import java.security.SignatureException;
  22. import java.security.UnrecoverableKeyException;
  23. import java.security.cert.Certificate;
  24. import java.security.cert.CertificateEncodingException;
  25. import java.security.cert.CertificateException;
  26. import java.security.cert.X509Certificate;
  27. import java.util.Date;
  28.  
  29. import javax.crypto.BadPaddingException;
  30. import javax.crypto.Cipher;
  31. import javax.crypto.IllegalBlockSizeException;
  32. import javax.crypto.NoSuchPaddingException;
  33. import javax.security.auth.x500.X500Principal;
  34.  
  35. /**
  36. * Crypto manager
  37. */
  38. public class CryptoManager {
  39. /*
  40. * Context is required to access file input/output
  41. */
  42. Context ctx;
  43.  
  44. /*
  45. * Location of the keystore on disk
  46. */
  47. private final String KEYSTORE_FILE = "bc.keystore";
  48.  
  49. /*
  50. * Key's alias
  51. */
  52. private final String PRIVATE_KEY_ALIAS = "PRIVATEKEY";
  53.  
  54.  
  55. public CryptoManager(Context ctx) {
  56. this.ctx = ctx;
  57. }
  58.  
  59.  
  60. public KeyPair generateKeyPair() throws NoSuchAlgorithmException {
  61. KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
  62. keygen.initialize(2048);
  63. return keygen.generateKeyPair();
  64. }
  65.  
  66. public KeyStore getKeyStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
  67. KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  68. FileInputStream fis = null;
  69. try {
  70. fis = ctx.openFileInput(KEYSTORE_FILE);
  71. ks.load(fis, null);
  72. } catch (FileNotFoundException e) {
  73. ks.load(null, null);
  74. }
  75.  
  76. if(fis != null) { fis.close(); }
  77.  
  78. return ks;
  79. }
  80.  
  81. public void saveKeyStore(KeyStore ks) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
  82. FileOutputStream fos = ctx.openFileOutput(KEYSTORE_FILE, Context.MODE_PRIVATE);
  83. ks.store(fos, null);
  84. fos.close();
  85. }
  86.  
  87. public void storeKeyPair(KeyPair kp) throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException, InvalidKeyException, NoSuchProviderException, SignatureException {
  88. KeyStore ks = getKeyStore();
  89.  
  90. Certificate[] cert = new Certificate[1];
  91. cert[0] = getCertificate(kp);
  92. ks.setKeyEntry(PRIVATE_KEY_ALIAS, kp.getPrivate(), null, cert);
  93. saveKeyStore(ks);
  94. }
  95.  
  96. public PrivateKey fetchPrivateKey() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, UnrecoverableKeyException {
  97. return (PrivateKey) getKeyStore().getKey(PRIVATE_KEY_ALIAS, null);
  98. }
  99.  
  100. public PublicKey fetchPublicKey() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
  101. return (PublicKey) getKeyStore().getCertificate(PRIVATE_KEY_ALIAS).getPublicKey();
  102. }
  103.  
  104. public String fetchStringPrivateKey() throws UnrecoverableKeyException, CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
  105. return bytesToHex(fetchPrivateKey().getEncoded());
  106. }
  107.  
  108. public String fetchStringPublicKey() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
  109. return bytesToHex(fetchPublicKey().getEncoded());
  110. }
  111.  
  112. public byte[] encryptString(String plain, PublicKey publicKey) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
  113. return encryptByte(plain.getBytes(), publicKey);
  114. }
  115.  
  116. public byte[] encryptByte(byte[] plain, PublicKey publicKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
  117. Cipher cipher = Cipher.getInstance("RSA");
  118. cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  119.  
  120. return cipher.doFinal(plain);
  121. }
  122.  
  123. public byte[] decryptByte(byte[] crypted, PrivateKey privateKey) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
  124. Cipher cipher = Cipher.getInstance("RSA");
  125. cipher.init(Cipher.DECRYPT_MODE, privateKey);
  126.  
  127. return cipher.doFinal(crypted);
  128. }
  129.  
  130. public String decryptByteToString(byte[] crypted, PrivateKey privareKey) throws NoSuchAlgorithmException, BadPaddingException, NoSuchPaddingException, IllegalBlockSizeException, InvalidKeyException {
  131. return new String(decryptByte(crypted, privareKey));
  132. }
  133.  
  134.  
  135.  
  136.  
  137.  
  138.  
  139.  
  140.  
  141. final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
  142. public static String bytesToHex(byte[] bytes) {
  143. char[] hexChars = new char[bytes.length * 2];
  144. for ( int j = 0; j < bytes.length; j++ ) {
  145. int v = bytes[j] & 0xFF;
  146. hexChars[j * 2] = hexArray[v >>> 4];
  147. hexChars[j * 2 + 1] = hexArray[v & 0x0F];
  148. }
  149. return new String(hexChars);
  150. }
  151.  
  152. X509Certificate getCertificate(KeyPair kp) throws NoSuchAlgorithmException, CertificateEncodingException, NoSuchProviderException, InvalidKeyException, SignatureException {
  153. Date startDate = new Date(System.currentTimeMillis());
  154. Date expiryDate = new Date(System.currentTimeMillis() + 631138519494l);
  155. BigInteger serialNumber = BigInteger.valueOf(1);
  156. KeyPair keyPair = kp;
  157. X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
  158. X500Principal dnName = new X500Principal("CN=Test CA Certificate");
  159. certGen.setSerialNumber(serialNumber);
  160. certGen.setIssuerDN(dnName);
  161. certGen.setNotBefore(startDate);
  162. certGen.setNotAfter(expiryDate);
  163. certGen.setSubjectDN(dnName);
  164. certGen.setPublicKey(keyPair.getPublic());
  165. certGen.setSignatureAlgorithm("SHA256withRSA");
  166.  
  167. return certGen.generate(kp.getPrivate(), "BC");
  168. }
  169.  
  170.  
  171. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement