Last active
          September 15, 2018 05:22 
        
      - 
      
- 
        Save Tea-Ayataka/9962cb9e8e4a9fd8a3949dcb01135163 to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | const val ENCRYPT_ALGORITHM = "AES" | |
| fun String.encrypt(key: String): String { | |
| val keySpec = SecretKeySpec(key.toByteArray(Charsets.UTF_8), ENCRYPT_ALGORITHM) | |
| val iv = SecureRandom().generateSeed(keySpec.encoded.size) | |
| val encrypted = Cipher.getInstance("$ENCRYPT_ALGORITHM/CBC/PKCS5PADDING").run { | |
| init(Cipher.ENCRYPT_MODE, keySpec, IvParameterSpec(iv)) | |
| doFinal([email protected](Charsets.UTF_8)) | |
| } | |
| return "${hex(iv)}/${hex(encrypted)}" | |
| } | |
| fun String.decrypt(key: String): String { | |
| val keySpec = SecretKeySpec(key.toByteArray(), ENCRYPT_ALGORITHM) | |
| val iv = hex(substringBefore("/")) | |
| val encrypted = hex(substringAfter("/")) | |
| return Cipher.getInstance("$ENCRYPT_ALGORITHM/CBC/PKCS5PADDING").run { | |
| init(Cipher.DECRYPT_MODE, keySpec, IvParameterSpec(iv)) | |
| doFinal(encrypted) | |
| }.toString(Charsets.UTF_8) | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment