π‘ SHA256μ΄λ?
SHA-256μ SHA(Secure Hash Algorithm) μκ³ λ¦¬μ¦μ ν μ’ λ₯λ‘μ SHA-2 κ³μ΄ μ€ νλμ΄λ©°, 2^256λ§νΌ κ²½μ°μ μλ₯Ό λ§λ€ μ μλ€.
μ΄λ€ κΈΈμ΄μ κ°μ μ λ ₯νλλΌλ 256λΉνΈμ κ³ μ λ κ²°κ³Όκ°(64μ리 λ¬Έμμ΄(32byte))μ λ°ννκ³ ,
SHA-256μ λ¨λ°©ν₯ μνΈν λ°©μμ΄κΈ° λλ¬Έμ 볡νΈνκ° λΆκ°λ₯ν©λλ€.
π‘ ν΄μ(Hash)λ?
ν΄μ(hash)λ λ¨λ°©ν₯ μνΈν κΈ°λ²μΌλ‘ ν΄μν¨μ(ν΄μ μκ³ λ¦¬μ¦)λ₯Ό μ΄μ©νμ¬ κ³ μ λ κΈΈμ΄μ μνΈνλ λ¬Έμμ΄λ‘ λ°κΏλ²λ¦¬λ κ²μ μλ―Έ
- ν΄μ ν¨μ(hash function) : ν΄μ μκ³ λ¦¬μ¦κ³Ό λμΌνλ©° ν° λ°μ΄ν° μ§ν©μ μ 체 μ§ν©μ λνλ΄λ μμ μ§ν©μΌλ‘ λ³ννλ μμ (=ν΄μ±)μ μν. μ΄ λ, 맀ν μ μλ λ°μ΄ν°μ κ°μ ν€(key), 맀ν ν λ°μ΄ν°μ κ°μ ν΄μκ°(hash value), 맀ννλ κ³Όμ μ ν΄μ±(hashing)μ΄λΌκ³ νλ€.
- ν΄μκ°(Hash Value) : ν¨μμ λν μλ΅μΌλ‘ μ 곡λ κ°μΌλ‘ μλ €μ§ λ°μ΄ν°
Swiftμμ μ΄λ€ λ°μ΄ν°λ₯Ό SHA-255 ν΄μκ°μΌλ‘ μ ννλ €λ©΄ cryptoKit λͺ¨λμ SHA256μ μ¬μ©νλ©΄ λλ€.
sha256λ SHA256.DigestsμΈλ°, μ¬κΈ°μ Digestλ hash ν¨μλ₯Ό ν΅κ³Όν μ΄νμ λ°μ΄ν°λ₯Ό μλ―Ένλ€.
[Swift ꡬν]
import Foundation
import CommonCrypto
extension Data{
public func sha256() -> String{
return hexStringFromData(input: digest(input: self as NSData))
}
private func digest(input : NSData) -> NSData {
let digestLength = Int(CC_SHA256_DIGEST_LENGTH)
var hash = [UInt8](repeating: 0, count: digestLength)
CC_SHA256(input.bytes, UInt32(input.length), &hash)
return NSData(bytes: hash, length: digestLength)
}
//sha-256μ νΈμΆ, 리ν΄μ byte[]λ‘ λ°κΈ° λλ¬Έμ, String λ³νμ΄ νμ
private func hexStringFromData(input: NSData) -> String {
var bytes = [UInt8](repeating: 0, count: input.length)
input.getBytes(&bytes, length: input.length)
var hexString = ""
for byte in bytes {
hexString += String(format:"%02x", UInt8(byte))
}
return hexString
}
}
public extension String {
func sha256() -> String{
if let stringData = self.data(using: String.Encoding.utf8) {
return stringData.sha256()
}
return ""
}
}
[ν μ€νΈ κ²°κ³Ό]
μμ μ½λλ‘ μμλ‘ "sha256Test"κ°μ ν΄μ± μ²λ¦¬ν΄ μ£Όμλλ μλμ κ°μ΄ κ°μ΄ λμ΅λλ€.
override func viewDidLoad() {
super.viewDidLoad()
var sha256Test = "sha256Test"
print("SHA256 ν΄μ± μ΄μ κ° : \(sha256Test)")
sha256Test = sha256Test.sha256()
print("SHA256 ν΄μ± μ΄ν κ° : \(sha256Test)")
}
[Objective-c ꡬν]
#import <CommonCrypto/CommonDigest.h>
-(NSString*)sha256HashForText:(NSString*)text {
const char* utf8chars = [text UTF8String];
unsigned char result[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(utf8chars, (CC_LONG)strlen(utf8chars), result);
NSMutableString *ret = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH*2];
for(int i = 0; i<CC_SHA256_DIGEST_LENGTH; i++) {
[ret appendFormat:@"%02x",result[i]];
}
return ret;
}
[ν μ€νΈ κ²°κ³Ό]
NSLog(@"output String: %@", [self sha256HashForText: inputTextField]);
NSLog(@"output String Length: %lu", (unsigned long)sha256Output.length);
[μλ μ¬μ΄νΈμμ κ²°κ³Όκ° λΉκ΅ν΄λ³΄κΈ°]
https://coding.tools/kr/sha256