001package com.gigya.android.sdk.encryption; 002 003import com.gigya.android.sdk.persistence.IPersistenceService; 004import com.gigya.android.sdk.utils.CipherUtils; 005 006import java.security.Key; 007 008import javax.crypto.Cipher; 009import javax.crypto.KeyGenerator; 010import javax.crypto.SecretKey; 011import javax.crypto.spec.SecretKeySpec; 012 013public class SessionKeyLegacy implements ISecureKey { 014 015 private final IPersistenceService _psService; 016 017 public SessionKeyLegacy(IPersistenceService psService) { 018 _psService = psService; 019 } 020 021 @Override 022 public String getAlias() { 023 return null; // Not needed as legacy does not support keystore. 024 } 025 026 @Override 027 public String getTransformation() { 028 return null; // Not needed as legacy does not support keystore. 029 } 030 031 @Override 032 public Cipher getEncryptionCipher(Key key) throws EncryptionException { 033 return null; 034 } 035 036 @Override 037 public Cipher getDecryptionCipher(Key key) throws EncryptionException { 038 return null; 039 } 040 041 @Override 042 public SecretKey getKey() throws EncryptionException { 043 try { 044 final String SECRET_PREFERENCE_KEY = "GS_PREFA"; 045 final String ALGORITHM_KEY = "AES"; 046 047 final String encryptedSecret = _psService.getString(SECRET_PREFERENCE_KEY, null); 048 if (encryptedSecret != null) { 049 // Secret key is saved in the shared preferences as a byte array. 050 final byte[] decryptedAES = CipherUtils.stringToBytes(encryptedSecret); 051 return new SecretKeySpec(decryptedAES, 0, decryptedAES.length, ALGORITHM_KEY); 052 } 053 // Generate a new secret key. 054 final KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM_KEY); 055 generator.init(128); // The AES key size in number of bits 056 final SecretKey secretKey = generator.generateKey(); 057 final String newEncryptedSecret = CipherUtils.bytesToString(secretKey.getEncoded()); 058 _psService.add(SECRET_PREFERENCE_KEY, newEncryptedSecret); 059 return secretKey; 060 } catch (Exception ex) { 061 throw new EncryptionException("Session encryption exception", ex.getCause()); 062 } 063 } 064}