반응형

이번에 사용자 패스워드에 암호화 적용을 하여 포스팅하게 되었어요.

패스워드는 보통 단방향을 사용해서 복호화가 안되게 되어야 하고 암호화된 문자들끼리 비교를 하여 패스워드가 맞는지 판별을 하게 돼요. 그 외 암호화, 복호화가 필요한 부분도 있어 양방향 암호화도 만들었어요.

	public static String encryptSha256(String value) {

		MessageDigest md;
		StringBuffer sb = new StringBuffer("");

		try {

			md = MessageDigest.getInstance("SHA-256");
			md.update(value.getBytes());
			byte byteData[] = md.digest();

			for (byte tmpStrByte : byteData) {
				String tmpEncTxt = Integer.toString((tmpStrByte & 0xff) + 0x100, 16).substring(1);

				sb.append(tmpEncTxt);
			}
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return sb.toString();

	}

	public static String encryptAes(String str, String key) throws Exception {

		Cipher cipher = Cipher.getInstance("AES");

		SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");

		cipher.init(Cipher.ENCRYPT_MODE, secretKey);

		byte[] encPassword = cipher.doFinal(str.getBytes("UTF-8"));

		String result = Base64.getEncoder().encodeToString(encPassword);

		return result;
	}

	/*
	* password = AES 방식으로 암호화된 암호문
	* key = 암호화시 사용했던 키워드
	*/
	public static String decryptAes(String str, String key) throws Exception {

		Cipher cipher = Cipher.getInstance("AES");
		SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");

		cipher.init(Cipher.DECRYPT_MODE, secretKey);

		byte[] decPassword = cipher.doFinal(Base64.getDecoder().decode(str));
		String result = new String(decPassword, "UTF-8");

		return result;
	}

단방향 암호화는 SHA-256 방식으로 했어요. 양방향 암호화는 AES 방식으로 사용을 하였는 데 사용되는 key는 값이 16, 24, 32 Byte로 작성이 되어야 해요. 그 외 byte에 안 맞는 키값이 입력이 되면 Invalid AES key length에러가 발생을 하게되므로 반드시 byte길이를 맞춰야해요.

반응형

+ Recent posts