Java源码示例:org.jasypt.util.text.TextEncryptor

示例1
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
    
    in.defaultReadObject();
    
    final EncryptablePropertiesEncryptorRegistry registry =
            EncryptablePropertiesEncryptorRegistry.getInstance();
    
    final StringEncryptor registeredStringEncryptor = registry.getStringEncryptor(this);
    if (registeredStringEncryptor != null) {
        this.stringEncryptor = registeredStringEncryptor;
        return;
    }
    
    final TextEncryptor registeredTextEncryptor = registry.getTextEncryptor(this);
    if (registeredTextEncryptor != null) {
        this.textEncryptor = registeredTextEncryptor;
    }
    
}
 
示例2
protected FindConfigFileService(final FilterProvider filterProvider,
                                final TextEncryptor textEncryptor,
                                final JsonSerializer<FieldPath> fieldPathSerializer,
                                final JsonDeserializer<FieldPath> fieldPathDeserializer) {

    final ObjectMapper objectMapper = new Jackson2ObjectMapperBuilder()
        .featuresToEnable(SerializationFeature.INDENT_OUTPUT)
        .mixIns(customMixins())
        .serializersByType(ImmutableMap.of(FieldPath.class, fieldPathSerializer))
        .deserializersByType(ImmutableMap.of(FieldPath.class, fieldPathDeserializer))
        .createXmlMapper(false)
        .build();

    setConfigFileLocation(CONFIG_FILE_LOCATION);
    setDeprecatedConfigFileLocations(Collections.singletonList(CONFIG_FILE_LOCATION_HP));
    setConfigFileName(CONFIG_FILE_NAME);
    setDefaultConfigFile(getDefaultConfigFile());
    setMapper(objectMapper);
    setTextEncryptor(textEncryptor);
    setFilterProvider(filterProvider);
}
 
示例3
public static void main(String[] args) throws ParseException {
  CommandLine cl = parseArgs(args);
  if (shouldPrintUsageAndExit(cl)) {
    printUsage();
    return;
  }
  String masterPassword = getMasterPassword(cl);
  TextEncryptor encryptor = getEncryptor(cl, masterPassword);

  if (cl.hasOption(ENCRYPTED_PWD_OPTION)) {
    Matcher matcher = ENCRYPTED_PATTERN.matcher(cl.getOptionValue(ENCRYPTED_PWD_OPTION));
    if (matcher.find()) {
      String encrypted = matcher.group(1);
      System.out.println(encryptor.decrypt(encrypted));
    } else {
      throw new RuntimeException("Input encrypted password does not match pattern \"ENC(...)\"");
    }
  } else if (cl.hasOption(PLAIN_PWD_OPTION)){
    System.out.println("ENC(" + encryptor.encrypt(cl.getOptionValue(PLAIN_PWD_OPTION)) + ")");
  } else {
    printUsage();
    throw new RuntimeException(String.format("Must provide -%s or -%s option.", PLAIN_PWD_OPTION, ENCRYPTED_PWD_OPTION));
  }
}
 
示例4
private static Properties processProperties(final Properties props, final TextEncryptor encryptor) {
    if (props == null) {
        return null;
    }
    if (props instanceof EncryptableProperties) {
        throw new IllegalArgumentException(
                "Properties object already is an " + EncryptableProperties.class.getName() + 
                " object. No encryptor should be specified.");
    }
    final EncryptableProperties encryptableProperties = new EncryptableProperties(encryptor);
    encryptableProperties.putAll(props);
    return encryptableProperties;
}
 
示例5
public static String encrypt(
        final String decodedValue, final TextEncryptor encryptor) {
    return 
        ENCRYPTED_VALUE_PREFIX + 
        encryptor.encrypt(decodedValue) +
        ENCRYPTED_VALUE_SUFFIX;
}
 
示例6
private static Properties processProperties(final Properties props, final TextEncryptor encryptor) {
    if (props == null) {
        return null;
    }
    if (props instanceof EncryptableProperties) {
        throw new IllegalArgumentException(
                "Properties object already is an " + EncryptableProperties.class.getName() + 
                " object. No encryptor should be specified.");
    }
    final EncryptableProperties encryptableProperties = new EncryptableProperties(encryptor);
    encryptableProperties.putAll(props);
    return encryptableProperties;
}
 
示例7
@Autowired
public HodFindConfigFileService(
        final FilterProvider filterProvider,
        final TextEncryptor textEncryptor,
        final JsonSerializer<FieldPath> fieldPathSerializer,
        final JsonDeserializer<FieldPath> fieldPathDeserializer) {
    super(filterProvider, textEncryptor, fieldPathSerializer, fieldPathDeserializer);
}
 
示例8
@Override
public CredentialsConfig withDecryptedPasswords(final TextEncryptor encryptor) {
    return toBuilder()
        // allow removing password from config by setting to empty string
        .password(encryptor.decrypt((password != null && password.isEmpty()) ? null : password))
        .build();
}
 
示例9
@Autowired
public IdolFindConfigFileService(
        final FilterProvider filterProvider,
        final TextEncryptor textEncryptor,
        final JsonSerializer<FieldPath> fieldPathSerializer,
        final JsonDeserializer<FieldPath> fieldPathDeserializer,
        final IdolConfigUpdateHandler idolConfigUpdateHandler,
        final IdolFieldPathNormaliserImpl idolFieldPathNormaliser
) {
    super(filterProvider, textEncryptor, fieldPathSerializer, fieldPathDeserializer);

    this.idolConfigUpdateHandler = idolConfigUpdateHandler;
    this.idolFieldPathNormaliser = idolFieldPathNormaliser;
}
 
示例10
@Before
public void setUp() {
    encryptor = Mockito.mock(TextEncryptor.class);
    Mockito.when(encryptor.encrypt(Mockito.any()))
        .then(invocation -> "encrypted:" + invocation.getArgumentAt(0, String.class));
    Mockito.when(encryptor.decrypt(Mockito.any()))
        .then(invocation -> invocation.getArgumentAt(0, String.class).substring(10));
}
 
示例11
@Bean
public TextEncryptor textEncryptor() {
    final FactoryBean<String> passwordFactory = new TextEncryptorPasswordFactory();

    final BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();

    try {
        basicTextEncryptor.setPassword(passwordFactory.getObject());
    } catch(final Exception e) {
        throw new BeanInitializationException("Failed to initialize TextEncryptor for some reason", e);
    }

    return basicTextEncryptor;
}
 
示例12
/**
 * Decrypt an encrypted password. A master password file must have been provided in the constructor.
 * @param encrypted An encrypted password.
 * @return The decrypted password.
 */
public String decryptPassword(String encrypted) {
  Preconditions.checkArgument(this.encryptors.size() > 0,
      "A master password needs to be provided for decrypting passwords.");

  for (TextEncryptor encryptor : encryptors) {
    try {
      return encryptor.decrypt(encrypted);
    } catch (Exception e) {
      LOG.warn("Failed attempt to decrypt secret {}", encrypted, e);
    }
  }
  LOG.error("All {} decrypt attempt(s) failed.", encryptors.size());
  throw new RuntimeException("Failed to decrypt password ENC(" + encrypted + ")");
}
 
示例13
public EncryptablePropertiesPropertySource(final String name, final Properties props, final TextEncryptor encryptor) {
    super(name, processProperties(props, encryptor));
}
 
示例14
public static String decrypt(
        final String encodedValue, final TextEncryptor encryptor) {
    return encryptor.decrypt(getInnerEncryptedValue(encodedValue.trim()));
}
 
示例15
TextEncryptor getTextEncryptor(final EncryptableProperties prop) {
    return (TextEncryptor) this.textEncryptors.get(prop.getIdent());
}
 
示例16
void setTextEncryptor(final EncryptableProperties prop, final TextEncryptor encryptor) {
    this.textEncryptors.put(prop.getIdent(), encryptor);
}
 
示例17
public EncryptablePropertiesPropertySource(final String name, final Properties props, final TextEncryptor encryptor) {
    super(name, processProperties(props, encryptor));
}
 
示例18
@Override
public HodFindConfig withEncryptedPasswords(final TextEncryptor encryptor) {
    return this;
}
 
示例19
@Override
public HodFindConfig withDecryptedPasswords(final TextEncryptor encryptor) {
    return this;
}
 
示例20
@Override
public CredentialsConfig withEncryptedPasswords(final TextEncryptor encryptor) {
    return toBuilder().password(encryptor.encrypt(password)).build();
}
 
示例21
@Override
public ControlPointConfig withEncryptedPasswords(final TextEncryptor encryptor) {
    return toBuilder()
        .server(server == null ? null : server.withEncryptedPasswords(encryptor))
        .build();
}
 
示例22
@Override
public ControlPointConfig withDecryptedPasswords(final TextEncryptor encryptor) {
    return toBuilder()
        .server(server == null ? null : server.withDecryptedPasswords(encryptor))
        .build();
}
 
示例23
@Override
public IdolFindConfig withEncryptedPasswords(final TextEncryptor encryptor) {
    return toBuilder().controlPoint(
        controlPoint == null ? null : controlPoint.withEncryptedPasswords(encryptor)
    ).build();
}
 
示例24
@Override
public IdolFindConfig withDecryptedPasswords(final TextEncryptor encryptor) {
    return toBuilder().controlPoint(
        controlPoint == null ? null : controlPoint.withDecryptedPasswords(encryptor)
    ).build();
}
 
示例25
@Override
public ControlPointServerConfig withEncryptedPasswords(final TextEncryptor encryptor) {
    return toBuilder()
        .credentials(credentials == null ? null : credentials.withEncryptedPasswords(encryptor))
        .build();
}
 
示例26
@Override
public ControlPointServerConfig withDecryptedPasswords(final TextEncryptor encryptor) {
    return toBuilder()
        .credentials(credentials == null ? null : credentials.withDecryptedPasswords(encryptor))
        .build();
}
 
示例27
private List<TextEncryptor> getEncryptors(CachedInstanceKey cacheKey) {
  List<TextEncryptor> encryptors = new ArrayList<>();
  int numOfEncryptionKeys = cacheKey.numOfEncryptionKeys;
  String suffix = "";
  int i = 1;

  if (cacheKey.masterPasswordFile == null || numOfEncryptionKeys < 1) {
    return encryptors;
  }

  Exception exception = null;

  do {
    Path currentMasterPasswordFile = new Path(cacheKey.masterPasswordFile + suffix);
    try (Closer closer = Closer.create()) {
      if (!fs.exists(currentMasterPasswordFile) ||
          fs.getFileStatus(currentMasterPasswordFile).isDirectory()) {
        continue;
      }
      InputStream in = closer.register(fs.open(currentMasterPasswordFile));
      String masterPassword = new LineReader(new InputStreamReader(in, Charsets.UTF_8)).readLine();
      TextEncryptor encryptor = useStrongEncryptor ? new StrongTextEncryptor() : new BasicTextEncryptor();
      // setPassword() needs to be called via reflection since the TextEncryptor interface doesn't have this method.
      encryptor.getClass().getMethod("setPassword", String.class).invoke(encryptor, masterPassword);
      encryptors.add(encryptor);
      suffix = "." + String.valueOf(i);
    } catch (FileNotFoundException fnf) {
      // It is ok for password files not being present
      LOG.warn("Master password file " + currentMasterPasswordFile + " not found.");
    } catch (IOException ioe) {
      exception = ioe;
      LOG.warn("Master password could not be read from file " + currentMasterPasswordFile);
    } catch (Exception e) {
      LOG.warn("Encryptor could not be instantiated.");
    }
  } while (i++ < numOfEncryptionKeys);

  // Throw exception if could not read any existing password file
  if (encryptors.size() < 1 && exception != null) {
    throw new RuntimeException("Master Password could not be read from any master password file.", exception);
  }
  return encryptors;
}
 
示例28
/**
 * <p>
 * Creates an <tt>EncryptablePreferencesPlaceholderConfigurer</tt> instance which will use the
 * passed {@link TextEncryptor} object to decrypt encrypted values.
 * </p>
 * 
 * @param textEncryptor
 *            the {@link TextEncryptor} to be used do decrypt values. It can
 *            not be null.
 */
public EncryptablePreferencesPlaceholderConfigurer(final TextEncryptor textEncryptor) {
	super();
	CommonUtils.validateNotNull(textEncryptor, "Encryptor cannot be null");
	this.stringEncryptor = null;
	this.textEncryptor = textEncryptor;
}
 
示例29
/**
 * <p>
 * Creates an <tt>EncryptableServletContextPropertyPlaceholderConfigurer</tt> instance which will use the
 * passed {@link TextEncryptor} object to decrypt encrypted values.
 * </p>
 * 
 * @param textEncryptor
 *            the {@link TextEncryptor} to be used do decrypt values. It can
 *            not be null.
 */
public EncryptableServletContextPropertyPlaceholderConfigurer(final TextEncryptor textEncryptor) {
	super();
	CommonUtils.validateNotNull(textEncryptor, "Encryptor cannot be null");
	this.stringEncryptor = null;
	this.textEncryptor = textEncryptor;
}
 
示例30
/**
 * <p>
 * Creates an <tt>EncryptablePropertyOverrideConfigurer</tt> instance which will use the
 * passed {@link TextEncryptor} object to decrypt encrypted values.
 * </p>
 * 
 * @param textEncryptor
 *            the {@link TextEncryptor} to be used do decrypt values. It can
 *            not be null.
 */
public EncryptablePropertyOverrideConfigurer(final TextEncryptor textEncryptor) {
	super();
	CommonUtils.validateNotNull(textEncryptor, "Encryptor cannot be null");
	this.stringEncryptor = null;
	this.textEncryptor = textEncryptor;
}